diff --git a/WebServer/bin/code/Antifurto.class b/WebServer/bin/code/Antifurto.class new file mode 100644 index 0000000000000000000000000000000000000000..f871b0867c473ce9730206f1a112d9068e1b7959 Binary files /dev/null and b/WebServer/bin/code/Antifurto.class differ diff --git a/WebServer/bin/code/Helper.class b/WebServer/bin/code/Helper.class new file mode 100644 index 0000000000000000000000000000000000000000..bb0f1d6d7685bd3bb13df1db55da9a7b001bf1c3 Binary files /dev/null and b/WebServer/bin/code/Helper.class differ diff --git a/WebServer/bin/code/Home.class b/WebServer/bin/code/Home.class new file mode 100644 index 0000000000000000000000000000000000000000..02248b5aed7f1ca17d5dc40c1de639dffcdf8715 Binary files /dev/null and b/WebServer/bin/code/Home.class differ diff --git a/WebServer/bin/code/ImageRes.class b/WebServer/bin/code/ImageRes.class new file mode 100644 index 0000000000000000000000000000000000000000..acc095a51658baea141ce0f88df0e85d4b514735 Binary files /dev/null and b/WebServer/bin/code/ImageRes.class differ diff --git a/WebServer/bin/code/Luci.class b/WebServer/bin/code/Luci.class new file mode 100644 index 0000000000000000000000000000000000000000..66ed0d2ba7c80cf7a72091952eb6039a0ffbd35a Binary files /dev/null and b/WebServer/bin/code/Luci.class differ diff --git a/WebServer/bin/code/MissingPage.class b/WebServer/bin/code/MissingPage.class new file mode 100644 index 0000000000000000000000000000000000000000..22370e28580b139b3ff860fe5f3a479108e7f23d Binary files /dev/null and b/WebServer/bin/code/MissingPage.class differ diff --git a/WebServer/bin/code/Resources.class b/WebServer/bin/code/Resources.class new file mode 100644 index 0000000000000000000000000000000000000000..91d92f9127731a65dbbd38f1c1b080a612eba74e Binary files /dev/null and b/WebServer/bin/code/Resources.class differ diff --git a/WebServer/bin/code/Server.class b/WebServer/bin/code/Server.class new file mode 100644 index 0000000000000000000000000000000000000000..a441c4009b747ca9b741820b1be8831982f26b4f Binary files /dev/null and b/WebServer/bin/code/Server.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/.classpath b/WebServer_provaKeycloakSimileAWebAppDelProf/.classpath new file mode 100644 index 0000000000000000000000000000000000000000..7b58445cef93eb55108728dd0729cdf25fb4e18e --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/.classpath @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"> + <attributes> + <attribute name="module" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="lib" path="org.json-1.0.0.v201011060100.jar"/> + <classpathentry kind="lib" path="/home/elisa/Documenti/Reti 2/GitLab/pissirsmarthome/WebServer/gson-2.8.2.jar"/> + <classpathentry kind="lib" path="/home/elisa/Documenti/Reti 2/GitLab/pissirsmarthome/WebServer/org.apache.commons.io.jar"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/.project b/WebServer_provaKeycloakSimileAWebAppDelProf/.project new file mode 100644 index 0000000000000000000000000000000000000000..193e0c6a21bba6ecbe4478b901b61bc5673ac40f --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>pissirsmarthome_WebServer</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> + <filteredResources> + <filter> + <id>1658153304390</id> + <name></name> + <type>30</type> + <matcher> + <id>org.eclipse.core.resources.regexFilterMatcher</id> + <arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments> + </matcher> + </filter> + </filteredResources> +</projectDescription> diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Authentication.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Authentication.class new file mode 100644 index 0000000000000000000000000000000000000000..6b1bda54ea8eb8def2e43b5cbb040005791d4ac2 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Authentication.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Helper.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Helper.class new file mode 100644 index 0000000000000000000000000000000000000000..a8d172b0075d6b154bbe9599e85ccec4ede9c32b Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Helper.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Home.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Home.class new file mode 100644 index 0000000000000000000000000000000000000000..c05009e2a71e8415f64142e4e82dd043a61e7c38 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Home.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/ImageRes.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/ImageRes.class new file mode 100644 index 0000000000000000000000000000000000000000..67936e0a6cec2b43b71ec5c50407bcfbb1c7c0f5 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/ImageRes.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/InitLogin.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/InitLogin.class new file mode 100644 index 0000000000000000000000000000000000000000..245495823c935951ef7478edc11c6fa6a292fbe6 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/InitLogin.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/KeyCloak.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/KeyCloak.class new file mode 100644 index 0000000000000000000000000000000000000000..d9490aaa337aa277cdfcbf6258ae358dc0d4d520 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/KeyCloak.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/MissingPage.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/MissingPage.class new file mode 100644 index 0000000000000000000000000000000000000000..9688a26b4792255b99ed9d4220a23af05c604b0b Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/MissingPage.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Resources.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Resources.class new file mode 100644 index 0000000000000000000000000000000000000000..15fe2c29c8c9ffbd72294f5f7fd298064b704370 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Resources.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeHostnameVerifier.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeHostnameVerifier.class new file mode 100644 index 0000000000000000000000000000000000000000..29849feb25b079276fde2d0ad67e5297afcc8f3d Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeHostnameVerifier.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeX509TrustManager.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeX509TrustManager.class new file mode 100644 index 0000000000000000000000000000000000000000..524f75e1cf73a3251e9ad89e6bdbab3584302279 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$FakeX509TrustManager.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeHostnameVerifier.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeHostnameVerifier.class new file mode 100644 index 0000000000000000000000000000000000000000..1463990fb3ab58ac023ef2d4477f97ae3881d311 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeHostnameVerifier.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeX509TrustManager.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeX509TrustManager.class new file mode 100644 index 0000000000000000000000000000000000000000..286a845984d02114bf2774b968e3dfdde68f6d95 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities$_FakeX509TrustManager.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities.class new file mode 100644 index 0000000000000000000000000000000000000000..0f1a84853cdad731b52958cd839a4b68c6e2a557 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/SSLUtilities.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Server.class b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Server.class new file mode 100644 index 0000000000000000000000000000000000000000..82efb67d572977028fbaa913ae02bd6e8ab93187 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/bin/code/Server.class differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/cert.pem b/WebServer_provaKeycloakSimileAWebAppDelProf/cert.pem new file mode 100644 index 0000000000000000000000000000000000000000..c2b2907814c0b83892535fe2e9802b2066f6c715 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/cert.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT +EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp +ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz +NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH +EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE +AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD +E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH +/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy +DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh +GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR +tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA +AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX +WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu +9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr +gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo +2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI +4uJEvlz36hz1 +-----END CERTIFICATE----- diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/curlCalls.txt b/WebServer_provaKeycloakSimileAWebAppDelProf/curlCalls.txt new file mode 100644 index 0000000000000000000000000000000000000000..f404ea34bbc2c1801a9c2dc29e2d4c393aa0d074 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/curlCalls.txt @@ -0,0 +1,33 @@ +GET + +curl localhost:3000 + +POST + +curl -X POST -H "Content-Type: application/json" -d "{JSON}" localhost:3000 + +curl -X POST "YOUR_URI" -F 'file=@/file-path.csv' + + +PUT + +curl -X PUT -H "Content-Type: application/json" -d "{JSON}" -d "{newJSON}" localhost:3000 + +curl -X PUT -H "Content-Type: multipart/form-data;" -F "key1=val1" localhost:3000 + +curl -X PUT -H "Content-Type: application/json" -d "{'email': 'text@mail.com'}" localhost:3000/bulloni?email=linuxize@example.com + + +DELETE + + +curl -X DELETE -d "{JSON}" localhost:3000 + +curl -X DELETE localhost:3000/bulloni?email=linuxize@example.com + zsh: no matches found: localhost:3000/bulloni?email=linuxize@example.com + + + +HTTPS + +curl --cacert cert.pem -k -H "version: 1.0" https://localhost/ \ No newline at end of file diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/gencert.bash b/WebServer_provaKeycloakSimileAWebAppDelProf/gencert.bash new file mode 100644 index 0000000000000000000000000000000000000000..04edfc14bf0f2ae308545ba85781d5307aeda4aa --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/gencert.bash @@ -0,0 +1 @@ +keytool -genkeypair -keyalg RSA -alias self_signed -keypass miapasswd -keystore lig.keystore -storepass miapasswd diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/gson-2.8.2.jar b/WebServer_provaKeycloakSimileAWebAppDelProf/gson-2.8.2.jar new file mode 100644 index 0000000000000000000000000000000000000000..d0d030c6371cb44e7caee238f7bf148c7732ce28 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/gson-2.8.2.jar differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/org.apache.commons.io.jar b/WebServer_provaKeycloakSimileAWebAppDelProf/org.apache.commons.io.jar new file mode 100644 index 0000000000000000000000000000000000000000..7affdefcd2747f924d078dbe5e85bb1503532a4f Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/org.apache.commons.io.jar differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/org.json-1.0.0.v201011060100.jar b/WebServer_provaKeycloakSimileAWebAppDelProf/org.json-1.0.0.v201011060100.jar new file mode 100644 index 0000000000000000000000000000000000000000..2aa70fdf80f4cc14a2063a8f118c847506c6c579 Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/org.json-1.0.0.v201011060100.jar differ diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/server.bash b/WebServer_provaKeycloakSimileAWebAppDelProf/server.bash new file mode 100755 index 0000000000000000000000000000000000000000..62b8300a700d6e60764ef37751a8b7ee05c82bec --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/server.bash @@ -0,0 +1,5 @@ +#!/bin/bash +javac -cp .:./org.json-1.0.0.v201011060100.jar -d bin src/code/* +echo 'server compiled' +cd bin +java -classpath .:../org.json-1.0.0.v201011060100.jar code.Server $1 diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Authentication.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Authentication.java new file mode 100644 index 0000000000000000000000000000000000000000..3de0dcd846898b1fd15d45a9f908a1dcfe0feef7 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Authentication.java @@ -0,0 +1,97 @@ +package code; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; + +import javax.net.ssl.HttpsURLConnection; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class Authentication implements HttpHandler { + + private static KeyCloak kcs; + private static String remoteHost; + private static String localHost; + private static String token; + + + public Authentication() throws MalformedURLException, IOException { + String path = "../webapp/public/"; + kcs = new KeyCloak(path+"keycloak.json", path+"params.json"); + remoteHost = kcs.authServer(); + localHost = "http://localhost:3000"; + token = ""; + } + + @Override + public void handle(HttpExchange exchange) throws IOException { + URI requestUri = exchange.getRequestURI(); + String response; + String requestMethod = exchange.getRequestMethod(); + + if(requestMethod.compareTo("POST")==0 || requestMethod.compareTo("post")==0) { + URI tokenrq = URI.create(kcs.tokenRQ()); + response = postRemote(tokenrq, exchange.getRequestBody(), kcs.extraBody()); + token = response; + exchange.sendResponseHeaders(200, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + else { + Helper.methodNotAllowed(exchange); + } + + } + + private String postRemote(URI pageUri, InputStream httpBody, String extraBody) throws IOException { + String url = remoteHost + pageUri.toString(); + InputStream is; + InputStreamReader isr; + BufferedReader br; + String body = extraBody; + String response = ""; + int i; + char c; + while((i=httpBody.read()) != -1) { + c = (char)i; + body += c; + } + httpBody.close(); + URL myUrl = new URL(url); + SSLUtilities.trustAllHttpsCertificates(); + SSLUtilities.trustAllHostnames(); + HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection(); + + conn.setReadTimeout(7000); + conn.setConnectTimeout(7000); + conn.setRequestMethod("POST"); + conn.setDoOutput(true); + conn.setDoInput(true); + + OutputStream outputStream = conn.getOutputStream(); + outputStream.write(body.getBytes("UTF-8")); + outputStream.close(); + + String inputLine; + is = conn.getInputStream(); + isr = new InputStreamReader(is); + br = new BufferedReader(isr); + while ((inputLine = br.readLine()) != null) { + response += inputLine; + } + + br.close(); + String answer = response.replace(remoteHost,localHost); + return answer; + + } + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Helper.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Helper.java new file mode 100644 index 0000000000000000000000000000000000000000..85699ce101f361a52056d6f9b37f8ba76f50e7db --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Helper.java @@ -0,0 +1,76 @@ +package code; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.json.JSONException; +import org.json.JSONObject; + +import com.sun.net.httpserver.HttpExchange; + +public class Helper { + + public static void sendResponse(String response, HttpExchange exchange) throws IOException { + System.out.println(response); + exchange.sendResponseHeaders(200, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + + public static void badRequest(HttpExchange exchange) throws IOException { + System.out.println("Errors in the request!"); +// exchange.getResponseHeaders().remove("content-type"); + String response = "{\"message\":\"Errors in the request!\"}"; + exchange.sendResponseHeaders(400, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + + public static void pageNotFound(HttpExchange exchange) throws IOException { + System.out.println("Page not found!"); +// exchange.getResponseHeaders().remove("content-type"); + String response = "{\"message\":\"Page not found!\"}"; + exchange.sendResponseHeaders(404, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + + public static void methodNotAllowed(HttpExchange exchange) throws IOException { + System.out.println("Method not allowed!"); +// exchange.getResponseHeaders().remove("content-type"); + String response = "{\"message\":\"Method not allowed!\"}"; + exchange.sendResponseHeaders(405, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + + public static boolean compareText(String a, String b){ + return a.compareToIgnoreCase(b) == 0; + } + + public static String readBody(InputStream requestBody) { + int req; + StringBuffer sb = new StringBuffer(); + try { + while((req = requestBody.read()) != -1) + sb.append(Character.toString((char)req)); + } catch (IOException e) { + e.printStackTrace(); + } + return sb.toString(); + } + + public static boolean checkJSON(String body) { + try { + new JSONObject(body); + return true; + } catch (JSONException e) { + return false; + } + } +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Home.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Home.java new file mode 100644 index 0000000000000000000000000000000000000000..b6abb6df6e7b651d9f84931f6be92aff4628d777 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Home.java @@ -0,0 +1,157 @@ +package code; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONException; +import org.json.JSONObject; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class Home implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + URI requestURI = exchange.getRequestURI(); + boolean wantsHome = Helper.compareText(requestURI.toString(),URI.create("/home").toString()); + boolean wantsKeycloak = Helper.compareText(requestURI.toString(),URI.create("/keycloak.json").toString()); + if(!wantsHome && !wantsKeycloak) { + String error = "Invalid URI"; + OutputStream os = exchange.getResponseBody(); + exchange.sendResponseHeaders(400, error.getBytes().length); + os.write(error.getBytes()); + os.close(); + return; + } + + String requestMethod = exchange.getRequestMethod(); + if (Helper.compareText(requestMethod, "GET")) { + List<String> strlist = new ArrayList<>(); + String response = null; + if(wantsHome){ + response = getHomePage(); + strlist.add("text/html"); + } else if (wantsKeycloak){ + response = getKeycloak(); + strlist.add("text/json"); + } + if(response != null && !Helper.compareText(response, "fail")){ + exchange.getResponseHeaders().put("content-type", strlist); + exchange.sendResponseHeaders(200, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } else { + exchange.sendResponseHeaders(500, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } + } else { + Helper.methodNotAllowed(exchange); + } + } + + private static String getHomePage() { + String line; +// String pageIDString = pageid.toString(); + String page = Server.CLIENT_PATH+"/index.html";// + pageIDString.substring(0, pageIDString.length() - 1) + ".txt";// entro nella cartella + // html e leggo il file + // txt + + StringBuilder answer = new StringBuilder(); + if (getExtension(page).length() == 0) + page += ".html"; + + BufferedReader bufferedReader = null; + try { + FileReader fileReader = new FileReader(page); + + bufferedReader = new BufferedReader(fileReader); + boolean isComment = false; + while ((line = bufferedReader.readLine()) != null) { + line = line.trim(); + + if(line.startsWith("<!--") && line.endsWith("-->")) { + continue; + } + if(line.startsWith("<!--")) { + isComment = true; + continue; + } + if(line.endsWith("-->")) { + isComment = false; + continue; + } + + if(!isComment && line.length()>0) + answer.append(line).append("\n"); + } + } catch (FileNotFoundException ex) { + System.out.println("Unable to open file '" + page + "'"); + return "fail"; + } catch (IOException ex) { + System.out.println("Error reading file '" + page + "'"); + return "fail"; + } finally { + try{ + if(bufferedReader != null) + bufferedReader.close(); + } catch (IOException ex){ + System.out.println("Error closing bufferedReader"); + } + } + return answer.toString(); + } + + private static String getKeycloak(){ + String page = Server.CLIENT_PATH+"/keycloak.json"; + BufferedReader bufferedReader = null; + StringBuilder answer = new StringBuilder(); + try { + FileReader fileReader = new FileReader(page); + bufferedReader = new BufferedReader(fileReader); + String line; + while ((line = bufferedReader.readLine()) != null) { + answer.append(line.trim()); + } + + JSONObject js = new JSONObject(answer.toString()); + return js.toString(); + } catch (FileNotFoundException ex) { + System.out.println("Unable to open file '" + page + "'"); + return "fail"; + } catch (IOException ex) { + System.out.println("Error reading file '" + page + "'"); + return "fail"; + } catch (JSONException e) { + System.out.println("The file doesn't contain a JSON '" + page + "'"); + return "fail"; + } finally { + try{ + if(bufferedReader != null) + bufferedReader.close(); + } catch (IOException ex){ + System.out.println("Error closing bufferedReader"); + } + } + } + + private static String getExtension(String file) { + int i = file.length() - 1; + while (i > 0 && file.charAt(i) != '.' && file.charAt(i) != '/') + i--; + if (file.charAt(i) == '.') + return file.substring(i + 1); + else + return ""; + } + +} \ No newline at end of file diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/ImageRes.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/ImageRes.java new file mode 100644 index 0000000000000000000000000000000000000000..87b766aed14e7d52f905aee13caa74a39d4d724f --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/ImageRes.java @@ -0,0 +1,56 @@ +package code; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import javax.imageio.ImageIO; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class ImageRes implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + URI requestURI = exchange.getRequestURI(); + + String requestMethod = exchange.getRequestMethod(); + if (Helper.compareText(requestMethod, "GET")) { + BufferedImage image = getLocalImage(requestURI.toASCIIString()); + if (image == null) + Helper.pageNotFound(exchange); + List<String> strlist = new ArrayList<>(); + strlist.add("image/png"); + OutputStream os = exchange.getResponseBody(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(image, "png", baos); + baos.flush(); + byte[] imageInByte = baos.toByteArray(); + exchange.getResponseHeaders().put("content-type", strlist); + exchange.sendResponseHeaders(200, imageInByte.length); + os.write(imageInByte); + os.close(); + } else { + Helper.methodNotAllowed(exchange); + } + } + + private BufferedImage getLocalImage(String uri) { + String page = Server.CLIENT_PATH + uri; + try { + File f = new File(page); + BufferedImage image = ImageIO.read(f); + return image; + } catch (IOException e) { + System.out.println("Error reading file '" + page + "'"); + return null; + } + } + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/InitLogin.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/InitLogin.java new file mode 100644 index 0000000000000000000000000000000000000000..204d2cc9d0fc532ea25f3c6312f3600378784af6 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/InitLogin.java @@ -0,0 +1,24 @@ +package code; + +import java.io.IOException; +import java.net.URI; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class InitLogin implements HttpHandler{ + + + + @Override + public void handle(HttpExchange exchange) throws IOException { + URI requestURI = exchange.getRequestURI(); + String response; + String requestMethod = exchange.getRequestMethod(); + if(requestMethod.compareTo("GET")==0 || requestMethod.compareTo("get")==0) { + // QUI DEVO RITORNARE IL PROGRAMMA DA ESEGUIRE CHE CONTIENE L'URI PER L'AUTENTICAZIONE + } + + } + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/KeyCloak.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/KeyCloak.java new file mode 100644 index 0000000000000000000000000000000000000000..cc2d4c83688e209cb23bec29bf7033f67e310090 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/KeyCloak.java @@ -0,0 +1,75 @@ +package code; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.io.*; +import java.util.HashMap; +import java.util.Arrays; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +public class KeyCloak extends HashMap<String,String> { + + public String extraBody() { + return get("extrabodyTemplate").replace("$CLIENTID",get("client-id")); + } + + public String authServer() { + String val = get("auth-server-url"); + int i = val.length()-2; + while(i>0 && val.charAt(i)!='/') i--; + return val.substring(0,i); + } + + public String codeRQ () { + String val = get("coderq").replace("$CLIENTID",get("client-id")); + return val.replace("$REALM", get("realm")); + } + + + public String tokenRQ () { + String val = get("tokenrq").replace("$CLIENTID",get("client-id")); + return val.replace("$REALM", get("realm")); + } + + public void print() { + System.out.println(Arrays.asList(this)); + } + + public KeyCloak(String keycloakpath, String params) throws MalformedURLException, IOException { + BufferedReader data; + String json = ""; + String line; + data = new BufferedReader(new FileReader(keycloakpath)); + while((line = data.readLine())!=null) json += line; + JsonParser parser = new JsonParser(); + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject keycloak = element.getAsJsonObject(); + put("realm", keycloak.get("realm").getAsString()); + put("auth-server-url", keycloak.get("auth-server-url").getAsString()); + put("ssl-required", keycloak.get("ssl-required").getAsString()); + put("resouce", keycloak.get("resource").getAsString()); + put("client-id", keycloak.get("resource").getAsString()); + put("public-client", keycloak.get("public-client").getAsString()); + put("confidential-port", keycloak.get("confidential-port").getAsString()); + } + data.close(); + BufferedReader data2 = new BufferedReader(new FileReader(params)); + json = ""; + while((line = data2.readLine())!=null) json += line; + element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject parameters = element.getAsJsonObject(); + put("coderq", parameters.get("coderq").getAsString()); + put("tokenrq", parameters.get("tokenrq").getAsString()); + put("extrabodyTemplate", parameters.get("extrabody").getAsString()); + } + data2.close(); + + } +} + + diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/MissingPage.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/MissingPage.java new file mode 100644 index 0000000000000000000000000000000000000000..854ed4f771c59758f4163bae8d7f549b463f4f50 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/MissingPage.java @@ -0,0 +1,15 @@ +package code; + +import java.io.IOException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class MissingPage implements HttpHandler { + + @Override + public void handle(HttpExchange exchange) throws IOException { + Helper.pageNotFound(exchange); + } + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Resources.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Resources.java new file mode 100644 index 0000000000000000000000000000000000000000..4792161b8834f5de4d56ae39722ae2ee1a163826 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Resources.java @@ -0,0 +1,97 @@ +package code; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +public class Resources implements HttpHandler { + + + @Override + public void handle(HttpExchange exchange) throws IOException { + URI requestURI = exchange.getRequestURI(); + + String requestMethod = exchange.getRequestMethod(); + if (Helper.compareText(requestMethod, "GET")) { + String response = getLocalPage(requestURI.toASCIIString()); + if(response.equals("fail")){ + //nel caso in cui non ci sia il file (perche non stato scaricato), allora creo un file fittizzio per non far crashare tutto il resto + String[] requestedPath = requestURI.toASCIIString().split("/"); + // get the last element of requestedPath and remove .js + String[] requestedPage = requestedPath[requestedPath.length-1].split("\\."); + String className = requestedPage[0]; + // make requested page with the first letter capitalized + className = className.substring(0, 1).toUpperCase() + className.substring(1); + response = "class "+className+"{}\nexport default " +className; + } + List<String> strlist = new ArrayList<>(); + switch (requestURI.toASCIIString().substring(1, 4)) { + case "js/" : strlist.add("text/javascript"); break; + case "css" : strlist.add("text/css"); break; + default : strlist.add("text"); break; + } + exchange.getResponseHeaders().put("content-type", strlist); + exchange.sendResponseHeaders(200, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } else { + Helper.methodNotAllowed(exchange); + } + } + + private static String getLocalPage(String uri) { + String page = Server.CLIENT_PATH+uri; + StringBuilder answer = new StringBuilder(); + BufferedReader bufferedReader = null; + + try { + FileReader fileReader = new FileReader(page); + + bufferedReader = new BufferedReader(fileReader); + boolean isComment = false; + String line; + while ((line = bufferedReader.readLine()) != null) { + line = line.trim(); + if((line.startsWith("/*") && line.endsWith("*/")) || line.startsWith("//")) { + continue; + } + if(line.startsWith("/*")) { + isComment = true; + continue; + } + if(line.endsWith("*/")) { + isComment = false; + continue; + } + if(!isComment && line.length()>0) + answer.append(line).append("\n"); + } + } catch (FileNotFoundException ex) { + System.out.println("Unable to open file '" + page + "'"); + return "fail"; + } catch (IOException ex) { + System.out.println("Error reading file '" + page + "'"); + return "fail"; + } finally { + try{ + if(bufferedReader != null) + bufferedReader.close(); + } catch (IOException ex){ + System.out.println("Error closing bufferedReader"); + } + } + return answer.substring(0,answer.length()-1); + } + + + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/SSLUtilities.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/SSLUtilities.java new file mode 100755 index 0000000000000000000000000000000000000000..71f15f4ee3ee7af64cc7095f025d88a7c1248177 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/SSLUtilities.java @@ -0,0 +1,318 @@ + +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * This class provide various static methods that relax X509 certificate and + * hostname verification while using the SSL over the HTTP protocol. + * + * @author Francis Labrie + */ +public final class SSLUtilities { + + /** + * Hostname verifier for the Sun's deprecated API. + * + * @deprecated see {@link #_hostnameVerifier}. + */ + private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier; + /** + * Thrust managers for the Sun's deprecated API. + * + * @deprecated see {@link #_trustManagers}. + */ + private static com.sun.net.ssl.TrustManager[] __trustManagers; + /** + * Hostname verifier. + */ + private static HostnameVerifier _hostnameVerifier; + /** + * Thrust managers. + */ + private static TrustManager[] _trustManagers; + + + /** + * Set the default Hostname Verifier to an instance of a fake class that + * trust all hostnames. This method uses the old deprecated API from the + * com.sun.ssl package. + * + * @deprecated see {@link #_trustAllHostnames()}. + */ + private static void __trustAllHostnames() { + // Create a trust manager that does not validate certificate chains + if(__hostnameVerifier == null) { + __hostnameVerifier = new _FakeHostnameVerifier(); + } // if + // Install the all-trusting host name verifier + com.sun.net.ssl.HttpsURLConnection. + setDefaultHostnameVerifier(__hostnameVerifier); + } // __trustAllHttpsCertificates + + /** + * Set the default X509 Trust Manager to an instance of a fake class that + * trust all certificates, even the self-signed ones. This method uses the + * old deprecated API from the com.sun.ssl package. + * + * @deprecated see {@link #_trustAllHttpsCertificates()}. + */ + private static void __trustAllHttpsCertificates() { + com.sun.net.ssl.SSLContext context; + + // Create a trust manager that does not validate certificate chains + if(__trustManagers == null) { + __trustManagers = new com.sun.net.ssl.TrustManager[] + {new _FakeX509TrustManager()}; + } // if + // Install the all-trusting trust manager + try { + context = com.sun.net.ssl.SSLContext.getInstance("SSL"); + context.init(null, __trustManagers, new SecureRandom()); + } catch(GeneralSecurityException gse) { + throw new IllegalStateException(gse.getMessage()); + } // catch + com.sun.net.ssl.HttpsURLConnection. + setDefaultSSLSocketFactory(context.getSocketFactory()); + } // __trustAllHttpsCertificates + + /** + * Return true if the protocol handler property java. + * protocol.handler.pkgs is set to the Sun's com.sun.net.ssl. + * internal.www.protocol deprecated one, false + * otherwise. + * + * @return true if the protocol handler + * property is set to the Sun's deprecated one, false + * otherwise. + */ + private static boolean isDeprecatedSSLProtocol() { + return("com.sun.net.ssl.internal.www.protocol".equals(System. + getProperty("java.protocol.handler.pkgs"))); + } // isDeprecatedSSLProtocol + + /** + * Set the default Hostname Verifier to an instance of a fake class that + * trust all hostnames. + */ + private static void _trustAllHostnames() { + // Create a trust manager that does not validate certificate chains + if(_hostnameVerifier == null) { + _hostnameVerifier = new FakeHostnameVerifier(); + } // if + // Install the all-trusting host name verifier: + HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier); + } // _trustAllHttpsCertificates + + /** + * Set the default X509 Trust Manager to an instance of a fake class that + * trust all certificates, even the self-signed ones. + */ + private static void _trustAllHttpsCertificates() { + SSLContext context; + + // Create a trust manager that does not validate certificate chains + if(_trustManagers == null) { + _trustManagers = new TrustManager[] {new FakeX509TrustManager()}; + } // if + // Install the all-trusting trust manager: + try { + context = SSLContext.getInstance("SSL"); + context.init(null, _trustManagers, new SecureRandom()); + } catch(GeneralSecurityException gse) { + throw new IllegalStateException(gse.getMessage()); + } // catch + HttpsURLConnection.setDefaultSSLSocketFactory(context. + getSocketFactory()); + } // _trustAllHttpsCertificates + + /** + * Set the default Hostname Verifier to an instance of a fake class that + * trust all hostnames. + */ + public static void trustAllHostnames() { + // Is the deprecated protocol setted? + if(isDeprecatedSSLProtocol()) { + __trustAllHostnames(); + } else { + _trustAllHostnames(); + } // else + } // trustAllHostnames + + /** + * Set the default X509 Trust Manager to an instance of a fake class that + * trust all certificates, even the self-signed ones. + */ + public static void trustAllHttpsCertificates() { + // Is the deprecated protocol setted? + if(isDeprecatedSSLProtocol()) { + __trustAllHttpsCertificates(); + } else { + _trustAllHttpsCertificates(); + } // else + } // trustAllHttpsCertificates + + /** + * This class implements a fake hostname verificator, trusting any host + * name. This class uses the old deprecated API from the com.sun. + * ssl package. + * + * @author Francis Labrie + * + * @deprecated see {@link SSLUtilities.FakeHostnameVerifier}. + */ + public static class _FakeHostnameVerifier + implements com.sun.net.ssl.HostnameVerifier { + + /** + * Always return true, indicating that the host name is an + * acceptable match with the server's authentication scheme. + * + * @param hostname the host name. + * @param session the SSL session used on the connection to + * host. + * @return the true boolean value + * indicating the host name is trusted. + */ + public boolean verify(String hostname, String session) { + return(true); + } // verify + } // _FakeHostnameVerifier + + + /** + * This class allow any X509 certificates to be used to authenticate the + * remote side of a secure socket, including self-signed certificates. This + * class uses the old deprecated API from the com.sun.ssl + * package. + * + * @author Francis Labrie + * + * @deprecated see {@link SSLUtilities.FakeX509TrustManager}. + */ + public static class _FakeX509TrustManager + implements com.sun.net.ssl.X509TrustManager { + + /** + * Empty array of certificate authority certificates. + */ + private static final X509Certificate[] _AcceptedIssuers = + new X509Certificate[] {}; + + + /** + * Always return true, trusting for client SSL + * chain peer certificate chain. + * + * @param chain the peer certificate chain. + * @return the true boolean value + * indicating the chain is trusted. + */ + public boolean isClientTrusted(X509Certificate[] chain) { + return(true); + } // checkClientTrusted + + /** + * Always return true, trusting for server SSL + * chain peer certificate chain. + * + * @param chain the peer certificate chain. + * @return the true boolean value + * indicating the chain is trusted. + */ + public boolean isServerTrusted(X509Certificate[] chain) { + return(true); + } // checkServerTrusted + + /** + * Return an empty array of certificate authority certificates which + * are trusted for authenticating peers. + * + * @return a empty array of issuer certificates. + */ + public X509Certificate[] getAcceptedIssuers() { + return(_AcceptedIssuers); + } // getAcceptedIssuers + } // _FakeX509TrustManager + + + /** + * This class implements a fake hostname verificator, trusting any host + * name. + * + * @author Francis Labrie + */ + public static class FakeHostnameVerifier implements HostnameVerifier { + + /** + * Always return true, indicating that the host name is + * an acceptable match with the server's authentication scheme. + * + * @param hostname the host name. + * @param session the SSL session used on the connection to + * host. + * @return the true boolean value + * indicating the host name is trusted. + */ + public boolean verify(String hostname, + javax.net.ssl.SSLSession session) { + return(true); + } // verify + } // FakeHostnameVerifier + + + /** + * This class allow any X509 certificates to be used to authenticate the + * remote side of a secure socket, including self-signed certificates. + * + * @author Francis Labrie + */ + public static class FakeX509TrustManager implements X509TrustManager { + + /** + * Empty array of certificate authority certificates. + */ + private static final X509Certificate[] _AcceptedIssuers = + new X509Certificate[] {}; + + + /** + * Always trust for client SSL chain peer certificate + * chain with any authType authentication types. + * + * @param chain the peer certificate chain. + * @param authType the authentication type based on the client + * certificate. + */ + public void checkClientTrusted(X509Certificate[] chain, + String authType) { + } // checkClientTrusted + + /** + * Always trust for server SSL chain peer certificate + * chain with any authType exchange algorithm types. + * + * @param chain the peer certificate chain. + * @param authType the key exchange algorithm used. + */ + public void checkServerTrusted(X509Certificate[] chain, + String authType) { + } // checkServerTrusted + + /** + * Return an empty array of certificate authority certificates which + * are trusted for authenticating peers. + * + * @return a empty array of issuer certificates. + */ + public X509Certificate[] getAcceptedIssuers() { + return(_AcceptedIssuers); + } // getAcceptedIssuers + } // FakeX509TrustManager +} // SSLUtilities + diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Server.java b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Server.java new file mode 100644 index 0000000000000000000000000000000000000000..531d9739fe3bed9a903044d9263547c2de65bdd5 --- /dev/null +++ b/WebServer_provaKeycloakSimileAWebAppDelProf/src/code/Server.java @@ -0,0 +1,116 @@ +package code; + +/*import java.io.FileInputStream; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; + +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsParameters; +import com.sun.net.httpserver.HttpsServer;*/ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; +import com.sun.net.httpserver.HttpServer; + +public class Server { + +// private static int port = 443; + private static int port = 3000; + public static String CLIENT_PATH = "./../../webapp/public"; + + public static void main(String[] args) throws IOException { + if (args.length > 1 && args[0].equals("-port")) + try { + port = Integer.parseInt(args[1]); + } catch (Exception e) { + e.printStackTrace(); + } +// HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 0); + HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); + + // initialise the HTTPS server + /*try { + SSLContext sslContext = SSLContext.getInstance("TLS"); + + // initialise the keystore + char[] password = "simulator".toCharArray(); + KeyStore ks = KeyStore.getInstance("JKS"); + FileInputStream fis = new FileInputStream("testkey.jks"); + ks.load(fis, password); + + // setup the key manager factory + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, password); + + // setup the trust manager factory + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(ks); + + // setup the HTTPS context and parameters + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { + @Override + public void configure(HttpsParameters params) { + try { + // initialise the SSL context + SSLContext context = getSSLContext(); + SSLEngine engine = context.createSSLEngine(); + params.setNeedClientAuth(false); + params.setCipherSuites(engine.getEnabledCipherSuites()); + params.setProtocols(engine.getEnabledProtocols()); + + // Set the SSL parameters + SSLParameters sslParameters = context.getSupportedSSLParameters(); + params.setSSLParameters(sslParameters); + + } catch (Exception ex) { + System.out.println("Failed to create HTTPS port"); + } + } + }); + + //API del server + server.createContext("/js/",new Resources()); + server.createContext("/css/",new Resources()); + server.createContext("/res/",new ImageRes()); + server.createContext("/",new Home()); + +// server.setExecutor(Executors.newFixedThreadPool(11)); + server.setExecutor(Executors.newCachedThreadPool()); + server.start(); + System.out.println("webserver running on localhost:"+port); + } catch (Exception e) { + System.out.println("Failed to create HTTPS server on port " + port + " of localhost"); + e.printStackTrace(); + }*/ + //API del server +// server.createContext("/api/luci/",new Luci());//post, get [put, delete] {luogo e stato di tutte luci} +// server.createContext("/api/luci/stato/",new Luci());//put {aggiorna lo stato di una luce} +// server.createContext("/api/scenari/",new Scenari());//get {nome e data di tutti gli scenari} +// server.createContext("/api/scenari/attiva/",new Scenari());//put {attiva/disattiva} +// server.createContext("/api/scenari/registra/",new Scenari());//put {registra/termina} +// server.createContext("/api/scenari/salva/",new Scenari());//post {conferma salvataggio, altrimenti cancella dopo timer; ritorna i valori dello scenario} +// server.createContext("/api/antifurto/",new Antifurto());//get {stato, allarme, attenzione, soglia, sensori} +// server.createContext("/api/antifurto/stato/",new Antifurto());//get, put {se l'antifurto e' attivo + aggiornamento} +// server.createContext("/api/antifurto/allarme/",new Antifurto());//get, put {se l'allarme sta suonando + aggiornamento} +// server.createContext("/api/antifurto/attenzione/",new Antifurto());//put {valore della progress bar} +// server.createContext("/api/antifurto/soglia/",new Antifurto());//put {valore scelto dall'utente per la soglia} + server.createContext("/js/",new Resources()); + server.createContext("/css/",new Resources()); + server.createContext("/res/",new ImageRes()); + server.createContext("/",new InitLogin()); + server.createContext("/secured", new Authentication()); + + server.createContext("/home",new Home()); + + server.setExecutor(Executors.newCachedThreadPool()); + server.start(); + System.out.println("webserver running on localhost:"+port); + } + +} diff --git a/WebServer_provaKeycloakSimileAWebAppDelProf/testkey.jks b/WebServer_provaKeycloakSimileAWebAppDelProf/testkey.jks new file mode 100644 index 0000000000000000000000000000000000000000..a709bb78edd1ec288e9fcd7373a38346f27d2cbc Binary files /dev/null and b/WebServer_provaKeycloakSimileAWebAppDelProf/testkey.jks differ