InstallHandler.java 6.06 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();
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);
if(user.equals(""))return;
} catch (NoSuchAlgorithmException | IOException | JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//verifica user
System.out.println(body);
if (requestMethod.compareToIgnoreCase("POST") == 0) {// || requestMethod.compareTo("post") == 0) {
JSONObject j = null;
try {
j = new JSONObject(body);
System.out.println(j.toString());
String dm = j.getString("domain");
System.out.println(
requestMethod + "\n" + query + "\n" + body + "\n" + response + "\n" + user + "\n" + dm + "\n");
//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();
os.write(response.getBytes());
os.close();
return;
}
} 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
URL url = new URL("http://127.0.0.1:3000");// maybe, se CloudAppe è in localhost porta 8080
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 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);
DataOutputStream out = new DataOutputStream(con.getOutputStream());// inserimento param in call
out.writeBytes(j.toString());// ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
// con.setRequestProperty("Content-Type", "application/json");
// String contentType = con.getHeaderField("Content-Type");
// leggo risposta
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
// finita chiamata a CloudApp
// f.close();
OutputStream os = he.getResponseBody();
he.sendResponseHeaders(status, content.length());
os.write(content.toString().getBytes());
// he.sendResponseHeaders(status, response.length());//status
// os.write(response.getBytes());
os.close();
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();
}
}