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 = getHomePage(); 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 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 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 ""; } }