Newer
Older
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.getPath().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")) {//post, get [put, delete] {luogo e stato di tutte luci}
String response = "[{\"luogo\":\"ingresso\",\"stato\":true,\"in\":\"in2\",\"out\":\"out2\"},{\"luogo\":\"cucina\",\"stato\":false,\"in\":\"in3\",\"out\":\"out3\"}]";
} else if(Helper.compareText(requestMethod,"POST")) {
String body = Helper.readBody(exchange.getRequestBody());
//check body is json or xml
if(!Helper.checkJSON(body) || !body.contains("\"luogo\"")) {
Helper.badRequest(exchange);
return;
}
String luogo = body.split("\"luogo\"",2)[1].split("\"",3)[1].trim();
String response = "{\"luogo\":\""+luogo+"\"}";
Helper.sendResponse(response,exchange);
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
if(Helper.compareText(lastfile,"stato")) {//put {aggiorna lo stato di una luce}
String body = Helper.readBody(exchange.getRequestBody());
//check body is json or xml
if(!Helper.checkJSON(body) || !body.contains("\"luogo\"")) {
Helper.badRequest(exchange);
return;
}
String stato = body.split("\"stato\"",2)[1].split(":",3)[1].split(",",2)[0].split("}",2)[0].trim();
try {
boolean st = Boolean.parseBoolean(stato);
String response = "{\"luce\":\"ok\",\"stato\":"+st+"}";
Helper.sendResponse(response,exchange);
} catch (Exception e) {
System.out.println("Conversion error.\t"+stato);
e.printStackTrace();
Helper.badRequest(exchange);
}
} else {
Helper.methodNotAllowed(exchange);
}
return;
}
Helper.pageNotFound(exchange);
}