Newer
Older
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();
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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("-->")) {
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 "";
}
}