-
Alfredo Chissotti authoredAlfredo Chissotti authored
InstallHandler.java 8.11 KiB
package code;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
import db.DBC;
import db.Dominio;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpPrincipal;
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
public class InstallHandler implements HttpHandler {
@Override
public void handle(HttpExchange he) throws IOException {
// URI requestedUri = he.getRequestURI();
String requestMethod = he.getRequestMethod();
if (requestMethod.compareToIgnoreCase("options") == 0) {
System.out.println("OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");// se non mettiamo *, viene errore CORS //http://localhost:3001/secured/domains
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
he.sendResponseHeaders(200, -1);
return;
}
String response = "";
// String query = requestedUri.getRawQuery();
String body = readBody(he.getRequestBody());
//he.getRequestHeaders().get("user").get(0);
String token=he.getRequestHeaders().get("Authorization").get(0).substring(7);
String user ="";
try {
//JSONObject tok=new JSONObject(token);
//String accessToken=tok.getString("access_token");
String[] tokSplit=token.split("[.]");
if(tokSplit.length!=3)return;//controllo che il token abbia header,body e signature(abbia 2 punti :s)
//int scnddot=accessToken.lastIndexOf(".");//dopo questo indice è tutta signature
String signature=tokSplit[2];
user=TokenHandler.verificaToken(token,signature);
System.out.println("user: "+user);
if(user.equals(""))return;
} catch (NoSuchAlgorithmException | IOException | JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//verifica user
if (requestMethod.compareToIgnoreCase("POST") == 0) {// || requestMethod.compareTo("post") == 0) {
System.out.println("POST");
JSONObject j = null;
try {
j = new JSONObject(body);
String dm = j.getString("domain");
//try {
Dominio d = DBC.getDom(dm);
if (d != null) {
System.out.println("DOMINIO GIA' IN USO");
response = "DOMINIO GIA' IN USO";
he.sendResponseHeaders(401, response.length());
OutputStream os = he.getResponseBody();
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");//http://localhost:3001/secured/domains
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");//non c'era POST
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
// questa parte sopra serve anche qui, non solo quando si chiama con OPTIONS
os.write(response.getBytes());
os.close();
return;
}
System.out.println("DOMINIO NON IN USO");
} catch (JSONException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// effettuo chiamata a CloudAppManager
// preso da https://www.baeldung.com/java-http-request
// è una chiamata annidata nella risposta alla webapp
// -richiesta REST da webApp a /install
// -prendo da DB e poi chiamo CloudAppMng su /install
// -attendo risposta da CloudAppMng e chiudo
// -rispondo a webApp e chiudo
// EZ
//
// standard per chiamata in slide
// https://www.dir.uniupo.it/pluginfile.php/948883/mod_resource/content/1/FrameworkProgetto5.pdf
//
// http://127.0.0.1:8080/install
HttpURLConnection con;
try {
URL url = new URL("http://127.0.0.1:3002");// maybe, se CloudAppe è in localhost porta 8080
System.out.println("opening connection");
con = (HttpURLConnection) url.openConnection();
System.out.println("connection opened");
// 3000/install da inserire
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
System.out.println("all set");
DataOutputStream outForCloudApp = new DataOutputStream(con.getOutputStream());// inserimento param in call
outForCloudApp.writeBytes(j.toString());// ParameterStringBuilder.getParamsString(parameters));
outForCloudApp.flush();
// he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");//http://localhost:3001/secured/domains
// he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");//non c'era POST
// he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
// questa parte sopra serve anche qui, non solo quando si chiama con OPTIONS
outForCloudApp.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return;
}
// con.setRequestProperty("Content-Type", "application/json");
// String contentType = con.getHeaderField("Content-Type");
System.out.println("written to cloud app");
// leggo risposta
int status;
StringBuffer content;
try {
status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return;
}
// finita chiamata a CloudApp
// f.close();
OutputStream os = he.getResponseBody();
he.sendResponseHeaders(status, content.length());
os.write(content.toString().getBytes());
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");//http://localhost:3001/secured/domains
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");//non c'era POST
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
// questa parte sopra serve anche qui, non solo quando si chiama con OPTIONS
// he.sendResponseHeaders(status, response.length());//status
// os.write(response.getBytes());
System.out.println("sent response to web app");
os.close();
System.out.println("status: "+status);
if (status==200) {
//String s = user + "-A";
try {
//qui leggo e parsifico i json nel body, inserisco tutti i campi nel db
String domain=j.getString("domain");
DBC.insertDom(domain);
DBC.insertAmministra(user, domain);
JSONArray arrUsers = j.getJSONArray("users");
for(int i=0;i<arrUsers.length();i++) {
if(((JSONObject) arrUsers.get(i)).getString("role").equals("A")) {
String usr=((JSONObject) arrUsers.get(i)).getString("user");
DBC.insertAmministra(usr, domain);
}
else if(((JSONObject) arrUsers.get(i)).getString("role").equals("U")) {
String usr=((JSONObject) arrUsers.get(i)).getString("user");
DBC.insertUsa(usr, domain);
}
}
JSONArray arrServ = j.getJSONArray("services");
for(int i=0;i<arrServ.length();i++) {
String modul=((JSONObject) arrUsers.get(i)).getString("service");
String host=((JSONObject) arrUsers.get(i)).getString("host");
DBC.insertService(domain,host,modul);
}
//non ci sono controlli!!!!
} catch (SQLException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private 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();
}
}