1 | import com.sun.net.httpserver.HttpHandler;
|
---|
2 | import com.sun.net.httpserver.HttpExchange;
|
---|
3 | import com.fasterxml.jackson.databind.ObjectMapper;
|
---|
4 | import java.io.IOException;
|
---|
5 | import java.io.OutputStream;
|
---|
6 | import java.nio.file.Files;
|
---|
7 | import java.sql.SQLException;
|
---|
8 | import java.time.LocalDate;
|
---|
9 | import java.time.format.DateTimeFormatter;
|
---|
10 | import java.util.List;
|
---|
11 | import java.util.Map;
|
---|
12 | import java.util.concurrent.ExecutorService;
|
---|
13 | import java.util.concurrent.Executors;
|
---|
14 | import java.util.concurrent.Future;
|
---|
15 | import java.io.File;
|
---|
16 |
|
---|
17 | public class FrontendHandler implements HttpHandler {
|
---|
18 | private static final ExecutorService executorService = Executors.newFixedThreadPool(1);
|
---|
19 |
|
---|
20 | @Override
|
---|
21 | public void handle(HttpExchange exchange) throws IOException {
|
---|
22 | String uri = exchange.getRequestURI().toString();
|
---|
23 | String path = exchange.getRequestURI().getPath();
|
---|
24 | String method = exchange.getRequestMethod();
|
---|
25 |
|
---|
26 | if ("GET".equalsIgnoreCase(method)) {
|
---|
27 | handleGetRequests(exchange, path, uri);
|
---|
28 | } else if ("POST".equalsIgnoreCase(method)) {
|
---|
29 | handlePostRequests(exchange, path);
|
---|
30 | } else {
|
---|
31 | Server.sendResponse(exchange, 405, "{\"message\": \"Method not allowed.\"}");
|
---|
32 | }
|
---|
33 | }
|
---|
34 |
|
---|
35 | private void handleGetRequests(HttpExchange exchange, String path, String uri) throws IOException {
|
---|
36 | switch (path) {
|
---|
37 | case "/admin/last-update-time":
|
---|
38 | String lastUpdateTimeResponse = "{\"lastUpdateTime\": \"" + Server.getLastUpdateTime().toString() + "\"}";
|
---|
39 | Server.sendResponse(exchange, 200, lastUpdateTimeResponse);
|
---|
40 | break;
|
---|
41 | case "/admin/current-options-count":
|
---|
42 | int currentOptionsCount;
|
---|
43 | try {
|
---|
44 | currentOptionsCount = DatabaseUtil.getCurrentOptionsCount();
|
---|
45 | } catch (SQLException e) {
|
---|
46 | throw new RuntimeException(e);
|
---|
47 | }
|
---|
48 | String currentOptionsCountResponse = "{\"currentOptionsCount\": " + currentOptionsCount + "}";
|
---|
49 | Server.sendResponse(exchange, 200, currentOptionsCountResponse);
|
---|
50 | break;
|
---|
51 | case "/admin/changed-options-count":
|
---|
52 | int changedOptionsCount;
|
---|
53 | try {
|
---|
54 | changedOptionsCount = DatabaseUtil.getChangedOptionsCountSinceLastUpdate();
|
---|
55 | } catch (SQLException e) {
|
---|
56 | throw new RuntimeException(e);
|
---|
57 | }
|
---|
58 | String changedOptionsCountResponse = "{\"changedOptionsCount\": " + changedOptionsCount + "}";
|
---|
59 | Server.sendResponse(exchange, 200, changedOptionsCountResponse);
|
---|
60 | break;
|
---|
61 | case"/admin/drop-db":
|
---|
62 | try {
|
---|
63 | System.out.println("DROPPING DATABASE!");
|
---|
64 | DatabaseUtil.dropOptions();
|
---|
65 | } catch (SQLException e) {
|
---|
66 | throw new RuntimeException(e);
|
---|
67 | }
|
---|
68 | break;
|
---|
69 | default:
|
---|
70 | serveStaticFiles(exchange, uri);
|
---|
71 | break;
|
---|
72 | }
|
---|
73 | }
|
---|
74 |
|
---|
75 | private void handlePostRequests(HttpExchange exchange, String path) throws IOException {
|
---|
76 | if (path.equalsIgnoreCase("/admin/start-scraper")) {
|
---|
77 | Future<Void> future = executorService.submit(new Scraper());
|
---|
78 | Server.updateLastUpdateTime();
|
---|
79 | Server.sendResponse(exchange, 200, "{\"message\": \"Starting options update.\"}");
|
---|
80 | executorService.submit(() -> {
|
---|
81 | try {
|
---|
82 | future.get();
|
---|
83 | } catch (Exception e) {
|
---|
84 | e.printStackTrace();
|
---|
85 |
|
---|
86 | }
|
---|
87 | });
|
---|
88 | } else if (path.equalsIgnoreCase("/submit")) {
|
---|
89 | handleFormSubmit(exchange);
|
---|
90 | }else {
|
---|
91 | Server.sendResponse(exchange, 404, "{\"message\": \"Endpoint not found.\"}");
|
---|
92 | }
|
---|
93 | }
|
---|
94 |
|
---|
95 | private void handleFormSubmit(HttpExchange exchange) throws IOException {
|
---|
96 | String requestBody = new String(exchange.getRequestBody().readAllBytes());
|
---|
97 | System.out.println("Form data: " + requestBody);
|
---|
98 | ObjectMapper mapper = new ObjectMapper();
|
---|
99 | Map<String, String> formData = mapper.readValue(requestBody, Map.class);
|
---|
100 | String destination = formData.get("destination");
|
---|
101 | String departureDate = formData.get("departureDate");
|
---|
102 | String nightsNumberStr = formData.get("nightsNumber");
|
---|
103 | int numberOfNights = (nightsNumberStr != null && !nightsNumberStr.isEmpty()) ? Integer.parseInt(nightsNumberStr) : 0;
|
---|
104 | String queryDate = "";
|
---|
105 | boolean dateFlag = false;
|
---|
106 |
|
---|
107 | if (departureDate != null && !departureDate.isEmpty()) {
|
---|
108 | if (numberOfNights != 0) {
|
---|
109 | queryDate = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
|
---|
110 | .format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
|
---|
111 | String dateTo = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
|
---|
112 | .plusDays(numberOfNights).format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
|
---|
113 | queryDate += " - " + dateTo;
|
---|
114 | } else {
|
---|
115 | dateFlag = true; // send only from date
|
---|
116 | queryDate = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
|
---|
117 | .format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
|
---|
118 | }
|
---|
119 | }
|
---|
120 |
|
---|
121 | List<Option> options;
|
---|
122 | try {
|
---|
123 | options = DatabaseUtil.queryOptions(destination, queryDate, dateFlag);
|
---|
124 | } catch (SQLException e) {
|
---|
125 | e.printStackTrace();
|
---|
126 | exchange.sendResponseHeaders(500, -1);
|
---|
127 | exchange.close();
|
---|
128 | return;
|
---|
129 | }
|
---|
130 |
|
---|
131 | Server.sendResponse(exchange, 200, mapper.writeValueAsString(options));
|
---|
132 | }
|
---|
133 |
|
---|
134 | private void serveStaticFiles(HttpExchange exchange, String uri) throws IOException {
|
---|
135 | File file;
|
---|
136 | String contentType = "text/html";
|
---|
137 |
|
---|
138 | if (uri.equals("/admin-panel")) {
|
---|
139 | System.out.println("Serving admin panel");
|
---|
140 | file = new File(System.getProperty("user.dir") + "/frontend/admin-panel.html");
|
---|
141 | } else {
|
---|
142 | file = new File(System.getProperty("user.dir") + "/frontend" + uri);
|
---|
143 | if (uri.endsWith(".css")) {
|
---|
144 | contentType = "text/css";
|
---|
145 | } else if (uri.endsWith(".js")) {
|
---|
146 | contentType = "application/javascript";
|
---|
147 | }
|
---|
148 | }
|
---|
149 |
|
---|
150 | if (!file.exists() || !file.isFile()) {
|
---|
151 | file = new File("frontend/index.html");
|
---|
152 | }
|
---|
153 |
|
---|
154 | if (file.exists() && file.isFile()) {
|
---|
155 | exchange.getResponseHeaders().set("Content-Type", contentType);
|
---|
156 | exchange.sendResponseHeaders(200, file.length());
|
---|
157 | OutputStream outputStream = exchange.getResponseBody();
|
---|
158 | Files.copy(file.toPath(), outputStream);
|
---|
159 | outputStream.close();
|
---|
160 | } else {
|
---|
161 | exchange.sendResponseHeaders(404, -1);
|
---|
162 | }
|
---|
163 | }
|
---|
164 |
|
---|
165 | }
|
---|