source: backend/GlobeGuru-backend/src/main/java/Server.java@ c164f8f

Last change on this file since c164f8f was c164f8f, checked in by Kristijan <kristijanzafirovski26@…>, 6 days ago

pred-finalna

  • Property mode set to 100644
File size: 8.6 KB
Line 
1import com.fasterxml.jackson.databind.JsonNode;
2import com.fasterxml.jackson.databind.ObjectMapper;
3import com.fasterxml.jackson.databind.node.ObjectNode;
4import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
5import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
6import com.google.api.client.http.HttpTransport;
7import com.google.api.client.http.javanet.NetHttpTransport;
8import com.google.api.client.json.JsonFactory;
9import com.google.api.client.json.jackson2.JacksonFactory;
10
11import com.sun.net.httpserver.HttpExchange;
12import com.sun.net.httpserver.HttpHandler;
13import com.sun.net.httpserver.HttpServer;
14
15import java.io.File;
16import java.io.IOException;
17import java.io.OutputStream;
18
19import java.net.InetSocketAddress;
20import java.net.URL;
21import java.nio.charset.StandardCharsets;
22import java.nio.file.Files;
23import java.nio.file.Path;
24import java.nio.file.Paths;
25import java.security.GeneralSecurityException;
26import java.sql.SQLException;
27import java.time.LocalDate;
28import java.time.LocalDateTime;
29import java.time.format.DateTimeFormatter;
30import java.util.*;
31import java.util.concurrent.ExecutorService;
32import java.util.concurrent.Executors;
33import java.util.concurrent.Future;
34
35public class Server {
36
37 public static void main(String[] args) throws IOException, SQLException {
38 // Start HTTP server
39 DatabaseUtil.initializeDatabase();
40 HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
41 server.createContext("/", new FrontendHandler());
42 server.createContext("/submit", new FrontendHandler());
43 server.createContext("/admin/start-scraper", new FrontendHandler());
44 server.createContext("/admin/last-update-time", new FrontendHandler());
45 server.createContext("/admin/current-options-count", new FrontendHandler());
46 server.createContext("/admin/changed-options-count", new FrontendHandler());
47
48 server.createContext("/account/login", new AccountHandler());
49 server.createContext("/account/register", new AccountHandler());
50 server.createContext("/account/delete-account", new AccountHandler());
51 server.createContext("/account/session", new AccountHandler());
52
53
54 server.createContext("/save-favorite", new SaveFavoriteHandler());
55 server.createContext("/get-saved-trips", new GetSavedTripsHandler());
56 server.createContext("/remove-from-saved", new RemoveFromSavedTripsHandler());
57
58 server.start();
59
60 System.out.println("Server started on port 8000");
61 }
62 static class RemoveFromSavedTripsHandler implements HttpHandler {
63 @Override
64 public void handle(HttpExchange exchange) throws IOException {
65 if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
66 String requestBody = new String(exchange.getRequestBody().readAllBytes());
67 ObjectMapper mapper = new ObjectMapper();
68 Map<String, Object> requestData = mapper.readValue(requestBody, Map.class);
69 String userEmail = (String) requestData.get("userEmail");
70 int optionId = (int) requestData.get("optionId");
71
72 int userId;
73 try {
74 userId = DatabaseUtil.getUserIdByEmail(userEmail);
75 boolean removed = DatabaseUtil.removeFavoriteOption(userId, optionId);
76 if (removed) {
77 sendResponse(exchange, 200, "{\"success\": true}");
78 } else {
79 sendResponse(exchange, 500, "{\"success\": false, \"message\": \"Failed to remove option\"}");
80 }
81 } catch (SQLException e) {
82 e.printStackTrace();
83 sendResponse(exchange, 500, "{\"message\": \"Failed to retrieve user ID.\"}");
84 }
85 } else {
86 sendResponse(exchange, 405, "{\"message\": \"Method not allowed.\"}");
87 }
88 }
89 }
90 static class SaveFavoriteHandler implements HttpHandler {
91 @Override
92 public void handle(HttpExchange exchange) throws IOException {
93 if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
94 String requestBody = new String(exchange.getRequestBody().readAllBytes());
95 ObjectMapper mapper = new ObjectMapper();
96 Map<String, String> requestData = mapper.readValue(requestBody, Map.class);
97 String optionId = requestData.get("optionId");
98 String userEmail = requestData.get("user");
99
100 int userId;
101 try {
102 userId = DatabaseUtil.getUserIdByEmail(userEmail);
103 } catch (SQLException e) {
104 e.printStackTrace();
105 sendResponse(exchange, 500, "{\"message\": \"Failed to retrieve user ID.\"}");
106 return;
107 }
108
109 try {
110 if (DatabaseUtil.saveFavoriteOption(userId, Integer.parseInt(optionId))) {
111 sendResponse(exchange, 200, "{\"message\": \"Favorite saved successfully!\"}");
112 } else {
113 sendResponse(exchange, 500, "{\"message\": \"Failed to save favorite.\"}");
114 }
115 } catch (SQLException e) {
116 e.printStackTrace();
117 sendResponse(exchange, 500, "{\"message\": \"Failed to save favorite.\"}");
118 }
119 } else {
120 sendResponse(exchange, 405, "{\"message\": \"Method not allowed.\"}");
121 }
122 }
123
124 }
125 static class GetSavedTripsHandler implements HttpHandler {
126 @Override
127 public void handle(HttpExchange exchange) throws IOException {
128 if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
129 String requestBody = new String(exchange.getRequestBody().readAllBytes());
130 ObjectMapper mapper = new ObjectMapper();
131 Map<String, String> requestData = mapper.readValue(requestBody, Map.class);
132 String userEmail = requestData.get("userEmail");
133
134 int userId;
135 try {
136 userId = DatabaseUtil.getUserIdByEmail(userEmail);
137 } catch (SQLException e) {
138 e.printStackTrace();
139 sendResponse(exchange, 500, "{\"message\": \"Failed to retrieve user ID.\"}");
140 return;
141 }
142
143 List<Option> savedTrips;
144 try {
145 savedTrips = DatabaseUtil.getSavedTripsByUser(userId);
146 } catch (SQLException e) {
147 e.printStackTrace();
148 sendResponse(exchange, 500, "{\"message\": \"Failed to retrieve saved trips.\"}");
149 return;
150 }
151
152 String responseJson = mapper.writeValueAsString(Map.of("savedTrips", savedTrips));
153 System.out.println(responseJson);
154 sendResponse(exchange, 200, responseJson);
155 } else {
156 sendResponse(exchange, 405, "{\"message\": \"Method not allowed.\"}");
157 }
158 }
159 }
160 public static LocalDateTime getLastUpdateTime() throws IOException {
161 ClassLoader classLoader = Server.class.getClassLoader();
162 ObjectMapper mapper = new ObjectMapper();
163 JsonNode root = mapper.readTree(new File(classLoader.getResource("lastUpdateTime.json").getFile()));
164 String lastUpdateTimeStr = root.get("lastUpdateTime").asText();
165 return LocalDateTime.parse(lastUpdateTimeStr);
166 }
167 public static void updateLastUpdateTime() throws IOException {
168 LocalDateTime now = LocalDateTime.now();
169 ObjectMapper mapper = new ObjectMapper();
170 ObjectNode rootNode = mapper.createObjectNode();
171 rootNode.put("lastUpdateTime", now.toString());
172
173 File file = new File(Server.class.getClassLoader().getResource("lastUpdateTime.json").getFile());
174
175 mapper.writerWithDefaultPrettyPrinter().writeValue(file, rootNode);
176
177 System.out.println("Last update time saved: " + now);
178 }
179
180 public static void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
181 exchange.getResponseHeaders().add("Cross-Origin-Opener-Policy", "unsafe-none");
182 exchange.getResponseHeaders().add("Cross-Origin-Embedder-Policy", "require-corp");
183 exchange.getResponseHeaders().add("Content-Type", "application/json");
184 exchange.sendResponseHeaders(statusCode, response.length());
185 exchange.getResponseBody().write(response.getBytes());
186 exchange.getResponseBody().close();
187 }
188
189}
190
191
192
193
Note: See TracBrowser for help on using the repository browser.