source: backend/GlobeGuru-backend/src/main/java/FrontendHandler.java@ df7f390

Last change on this file since df7f390 was cd64b06, checked in by Kristijan <kristijanzafirovski26@…>, 5 days ago

Added info scraping for escape travel

  • Property mode set to 100644
File size: 7.0 KB
Line 
1import com.sun.net.httpserver.HttpHandler;
2import com.sun.net.httpserver.HttpExchange;
3import com.fasterxml.jackson.databind.ObjectMapper;
4import java.io.IOException;
5import java.io.OutputStream;
6import java.nio.file.Files;
7import java.sql.SQLException;
8import java.time.LocalDate;
9import java.time.format.DateTimeFormatter;
10import java.util.List;
11import java.util.Map;
12import java.util.concurrent.ExecutorService;
13import java.util.concurrent.Executors;
14import java.util.concurrent.Future;
15import java.io.File;
16
17public 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 String numPeopleStr = formData.get("numberPeople");
104 int numberOfNights = (nightsNumberStr != null && !nightsNumberStr.isEmpty()) ? Integer.parseInt(nightsNumberStr) : 0;
105 int numPeople = Integer.parseInt(numPeopleStr);
106 String queryDate = "";
107 boolean dateFlag = false;
108
109 if (departureDate != null && !departureDate.isEmpty()) {
110 if (numberOfNights != 0) {
111 queryDate = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
112 .format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
113 String dateTo = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
114 .plusDays(numberOfNights).format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
115 queryDate += " - " + dateTo;
116 } else {
117 dateFlag = true; // send only from date
118 queryDate = LocalDate.parse(departureDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
119 .format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));
120 }
121 }
122
123 List<Option> options;
124 try {
125 options = DatabaseUtil.queryOptions(destination, queryDate, numPeople, dateFlag);
126 } catch (SQLException e) {
127 e.printStackTrace();
128 exchange.sendResponseHeaders(500, -1);
129 exchange.close();
130 return;
131 }
132 Server.sendResponse(exchange, 200, mapper.writeValueAsString(options));
133 }
134
135 private void serveStaticFiles(HttpExchange exchange, String uri) throws IOException {
136 File file;
137 String contentType = "text/html";
138
139 if (uri.equals("/admin-panel")) {
140 System.out.println("Serving admin panel");
141 file = new File(System.getProperty("user.dir") + "/frontend/admin-panel.html");
142 } else {
143 file = new File(System.getProperty("user.dir") + "/frontend" + uri);
144 if (uri.endsWith(".css")) {
145 contentType = "text/css";
146 } else if (uri.endsWith(".js")) {
147 contentType = "application/javascript";
148 }
149 }
150
151 if (!file.exists() || !file.isFile()) {
152 file = new File("frontend/index.html");
153 }
154
155 if (file.exists() && file.isFile()) {
156 exchange.getResponseHeaders().set("Content-Type", contentType);
157 exchange.sendResponseHeaders(200, file.length());
158 OutputStream outputStream = exchange.getResponseBody();
159 Files.copy(file.toPath(), outputStream);
160 outputStream.close();
161 } else {
162 exchange.sendResponseHeaders(404, -1);
163 }
164 }
165
166}
Note: See TracBrowser for help on using the repository browser.