Skip to content
Snippets Groups Projects
Commit 49fa8f48 authored by Alfredo Chissotti's avatar Alfredo Chissotti
Browse files

Inizio server 2

parent 9ad037f1
No related branches found
No related tags found
No related merge requests found
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
Za warudo!
\ No newline at end of file
package code;
import java.io.IOException;
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 Antifurto implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
String path[] = requestURI.toString().split("/");
String lastfile = path[path.length - 1];
String requestMethod = exchange.getRequestMethod();
List<String> strlist = new ArrayList<>(); //serve List<String> a causa di .put("content-type", strlist);
strlist.add("text/json");
exchange.getResponseHeaders().put("content-type", strlist);//opzionale, per dire cosa c'e' nel body
if(Helper.compareText(lastfile,"antifurto")) {
if(Helper.compareText(requestMethod,"GET")) {
String response = "ecco le tutto il necessario";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"stato")) {
if(Helper.compareText(requestMethod,"GET")) {
String response = "ecco lo stato dell'antifurto";
Helper.sendResponse(response,exchange);
} else if(Helper.compareText(requestMethod,"PUT")) {
String response = "stato antifurto aggiornato";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"allarme")) {
if(Helper.compareText(requestMethod,"GET")) {
String response = "ecco l'allarme";
Helper.sendResponse(response,exchange);
} else if(Helper.compareText(requestMethod,"PUT")) {
String response = "allarme aggiornato";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"attenzione")) {
if(Helper.compareText(requestMethod,"PUT")) {
String response = "valore progress bar aggiornato";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"soglia")) {
if(Helper.compareText(requestMethod,"PUT")) {
String response = "soglia aggiornata";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
Helper.pageNotFound(exchange);
}
}
package code;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.net.httpserver.HttpExchange;
public class Helper {
public static void sendResponse(String response, HttpExchange exchange) throws IOException {
exchange.sendResponseHeaders(200, 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");
exchange.sendResponseHeaders(404, 0);
exchange.getResponseBody().close();
}
public static void methodNotAllowed(HttpExchange exchange) throws IOException {
System.out.println("Method not allowed!");
exchange.getResponseHeaders().remove("content-type");
exchange.sendResponseHeaders(405, 0);
exchange.getResponseBody().close();
}
public static boolean compareText(String a, String b){
return a.compareToIgnoreCase(b) == 0;
}
}
package code;public class Home {
}
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 Home implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
if(requestURI.compareTo(URI.create("/")) != 0) {
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")) {
String response = getLocalPage(URI.create("/home/"));
List<String> strlist = new ArrayList<>();
strlist.add("text/html");
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(URI pageid) {
String line;
// String pageIDString = pageid.toString();
String page = "./../webapp/public/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("-->")) {
isComment = false;
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 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
package code;
import java.io.IOException;
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 Luci implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
String path[] = requestURI.toString().split("/");
String lastfile = path[path.length - 1];
String requestMethod = exchange.getRequestMethod();
List<String> strlist = new ArrayList<>(); //serve List<String> a causa di .put("content-type", strlist);
strlist.add("text/json");
exchange.getResponseHeaders().put("content-type", strlist);//opzionale, per dire cosa c'e' nel body
if(Helper.compareText(lastfile,"luci")) {
if(Helper.compareText(requestMethod,"GET")) {
String response = "ecco le luci";
Helper.sendResponse(response,exchange);
} else if(Helper.compareText(requestMethod,"POST")) {
String response = "luce aggiunta";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"stato")) {
if(Helper.compareText(requestMethod,"PUT")) {
String response = "stato luce aggiornato";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
Helper.pageNotFound(exchange);
}
}
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);
}
}
package code;
import java.io.IOException;
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 Scenari implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
String path[] = requestURI.toString().split("/");
String lastfile = path[path.length - 1];
String requestMethod = exchange.getRequestMethod();
List<String> strlist = new ArrayList<>(); //serve List<String> a causa di .put("content-type", strlist);
strlist.add("text/json");
exchange.getResponseHeaders().put("content-type", strlist);//opzionale, per dire cosa c'e' nel body
if(Helper.compareText(lastfile,"scenari")) {
if(Helper.compareText(requestMethod,"GET")) {
String response = "ecco gli scenari";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"attiva")) {
if(Helper.compareText(requestMethod,"PUT")) {
String response = "scenario attivato/disattivato";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"registra")) {
if(Helper.compareText(requestMethod,"PUT")) {
String response = "registrazione ingaggiata";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"conferma")) {
if(Helper.compareText(requestMethod,"POST")) {
String response = "scenario aggiunto";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
Helper.pageNotFound(exchange);
}
}
package code;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.KeyStore;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
......@@ -23,8 +18,7 @@ import com.sun.net.httpserver.HttpsServer;
public class Server {
public static int port = 443;
public static final String VERSION = "1.0";
private static int port = 443;
public static void main(String[] args) throws IOException {
if (args.length > 1 && args[0].equals("-port"))
......@@ -57,6 +51,7 @@ public class Server {
// 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
......@@ -77,83 +72,27 @@ public class Server {
});
//API del server
server.createContext("/index/", new AllURIs());
server.createContext("/bulloni/", new Handler());
server.createContext("/utensili/", new Handler());
server.createContext("/vernici/", new Handler());
server.createContext("/altro/", new Handler());
server.createContext("/", new Home());
server.setExecutor((ThreadPoolExecutor) Executors.newFixedThreadPool(5));
server.start();
System.out.println("server running on localhost:"+port);
server.createContext("/luci/",new Luci());//post, get [put, delete] {luogo e stato di tutte luci}
server.createContext("/luci/stato/",new Luci());//put {aggiorna lo stato di una luce}
server.createContext("/scenari/",new Scenari());//get {nome e data di tutti gli scenari}
server.createContext("/scenari/attiva/",new Scenari());//put {attiva/disattiva}
server.createContext("/scenari/registra/",new Scenari());//put {registra/termina}
server.createContext("/scenari/registra/conferma/",new Scenari());//post {conferma salvataggio; altrimenti cancella}
server.createContext("/antifurto/",new Antifurto());//get {stato, allarme, attenzione, soglia, sensori}
server.createContext("/antifurto/stato/",new Antifurto());//get, put {se l'antifurto e' attivo + aggiornamento}
server.createContext("/antifurto/allarme/",new Antifurto());//get, put {se l'allarme sta suonando + aggiornamento}
server.createContext("/antifurto/attenzione/",new Antifurto());//put {valore della progress bar}
server.createContext("/antifurto/soglia/",new Antifurto());//put {valore scelto dall'utente per la soglia}
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");
System.out.println("Failed to create HTTPS server on port " + port + " of localhost");
e.printStackTrace();
}
}
// public static void main(String[] args) throws IOException {//main HTTP
// if (args.length > 1 && args[0].equals("-port"))
// try {
// port = Integer.parseInt(args[1]);
// } catch (Exception e) {
// e.printStackTrace();
// }
// ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);//Executors.newWorkStealingPool() doesn't work
// HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
//
// server.createContext("/index/", new AllURIs());
// server.createContext("/bulloni/", new Handler());
// server.createContext("/utensili/", new Handler());
// server.createContext("/vernici/", new Handler());
// server.createContext("/altro/", new Handler());
// server.createContext("/", new Home());
//
// server.setExecutor(threadPoolExecutor);
// server.start();
//
// System.out.println("server running on localhost:"+port);
//
// }
public static String getLocalPage(URI pageid) {
String line;
String pageIDString = pageid.toString();
String page = "./html" + pageIDString.substring(0, pageIDString.length() - 1) + ".txt";// entro nella cartella
// html e leggo il file
// txt
String answer = "";
if (getExtension(page).length() == 0)
page += ".html";
try {
FileReader fileReader = new FileReader(page);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
answer += (line + "\n");
}
bufferedReader.close();
} 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";
}
return answer;
}
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 "";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="src" path=""/>
<classpathentry kind="output" path=""/>
</classpath>
<component name="ProjectDictionaryState">
<dictionary name="alfredochissotti" />
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>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>
</projectDescription>
......@@ -49,7 +49,7 @@ class Antifurto {
const bell = document.getElementById('antifurto-bell');
bell.addEventListener('click', () => {
Antifurto.activateAlarm(false);
// TODO ask if they want to turn off the antitheft
// TODO? ask if they want to turn off the antitheft
}, false);
}
/**
......
......@@ -508,7 +508,7 @@ class Scenari {
for (const scenario of scenari) {
Scenari.mostraNuovoScenario(scenario)
// TODO server if scenario is active, change the toggle to active
// TODO if scenario is active, change the toggle to active
// also set Scenari.scenarioAttivoToggle to its toggle
}
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment