-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetadataServer.java
More file actions
413 lines (360 loc) · 16.9 KB
/
MetadataServer.java
File metadata and controls
413 lines (360 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// importing libraries
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpExchange;
import java.lang.*;
public class MetadataServer {
private final int port; // port number that the server listens on
private final String serverId; // unique id for the server instance
private final Map<String, MetadataEntry> metadata; // in-memory storage of file metadata
private HttpServer server; // http server instance
// 1. Initialise + declare the file where we persistenty store metadata so that it survives server restarts
private static final String DATA_FILE = "/data/meta.txt";
// 2. Constructor
public MetadataServer(int port, String serverId) {
this.port = port;
this.serverId = serverId;
this.metadata = new ConcurrentHashMap<>(); // thread-safe map for concurrent access
// Auto-create root directory if this server is responsible for it
String rootPath = "/";
if (isResponsibleForPath(rootPath)) {
if (!metadata.containsKey(rootPath)) {
metadata.put(rootPath, new MetadataEntry(rootPath, "dir", null, System.currentTimeMillis()));
save();
System.out.println("[Server " + serverId + "] Auto-created root directory");
}
}
load(); // load any existing metadata from disk
System.out.println("[Server " + serverId + "] Initialized");
}
// Helper: simple hash-based responsibility check
private boolean isResponsibleForPath(String path) {
int hash = Math.abs(path.hashCode());
int serverIndex = hash % 3;
return Integer.parseInt(serverId) == (serverIndex + 1);
}
// 3. Load metadata from disk file when server starts
private void load() {
try {
Path file = Paths.get(DATA_FILE);
if (Files.exists(file)) {
// 3.1 Try to read the file line by line
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\|"); // each line format: path/type/parent/timestamp
if (parts.length == 4) {
String path = parts[0];
String type = parts[1];
String parent = parts[2].equals("null") ? null : parts[2];
long timestamp = Long.parseLong(parts[3]);
// 3.2 Restoring the emtadata entry to memory
metadata.put(path, new MetadataEntry(path, type, parent, timestamp));
}
}
}
System.out.println("[Server " + serverId + "] Loaded " + metadata.size() + " entries from checkpoint");
}
} catch (Exception e) {
System.out.println("[Server " + serverId + "] No checkpoint found or error loading: " + e.getMessage());
}
}
// 4. Saving the current metadata to the disk, this is called after each change
private void save() {
try {
Path file = Paths.get(DATA_FILE);
Files.createDirectories(file.getParent()); // creates the directory if it does not exist
// 4.1 Writing all metadata entries to file
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(file, StandardCharsets.UTF_8))) {
for (MetadataEntry entry : metadata.values()) {
writer.printf("%s|%s|%s|%d%n",
entry.getPath(),
entry.getType(),
entry.getParent() != null ? entry.getParent() : "null", // here parent is saved
entry.getTimestamp());
}
}
} catch (Exception e) {
System.err.println("[Server " + serverId + "] Error saving checkpoint: " + e.getMessage());
}
}
// 5. Starting the http server + register API endpoints
public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(port), 0);
// 5.1 Register endpoints that the server will handle
server.createContext("/mkdir", this::handleMkdir);
server.createContext("/touch", this::handleTouch);
server.createContext("/readdir", this::handleReaddir); // list directory contents
server.createContext("/stat", this::handleStat); // get file/directory info
server.createContext("/rm", this::handleRm); // remove file/directory
server.createContext("/dump", this::handleDump); // show all metadata (for debugging)
//server.createContext("/tree", this::handleTree); // show the tree of the directory with relative paths
//server.createContext("/fulltree", this::handleFullTree); // show the tree of the directory
server.start();
System.out.println("[Server " + serverId + "] port=" + port);
}
// 6. Handling the creation of a new directory
private void handleMkdir(HttpExchange exchange) throws IOException {
if (!"POST".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method not allowed");
return;
}
// 6.1 Extracting the path param from the URL query string
String query = exchange.getRequestURI().getQuery();
String path = getQueryParam(query, "path");
if (path == null || path.isEmpty()) {
sendResponse(exchange, 400, "Missing or invalid 'path' parameter");
return;
}
try {
// 6.2 Checking if the path already exists
if (metadata.containsKey(path)) {
sendResponse(exchange, 409, "Path already exists");
return;
}
// 6.3 Creating a new directory entry + save to disk
String parent = getParentPath(path);
MetadataEntry entry = new MetadataEntry(path, "dir", parent, System.currentTimeMillis());
metadata.put(path, entry);
save(); // persist the change
System.out.println("[Server " + serverId + "] Created directory: " + path);
sendResponse(exchange, 200, "Directory created: " + path);
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// 7. Handling the creation of a new file
private void handleTouch(HttpExchange exchange) throws IOException {
if (!"POST".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method not allowed");
return;
}
String query = exchange.getRequestURI().getQuery();
String path = getQueryParam(query, "path");
if (path == null || path.isEmpty()) {
sendResponse(exchange, 400, "Missing or invalid 'path' parameter");
return;
}
try {
if (metadata.containsKey(path)) {
sendResponse(exchange, 409, "File already exists");
return;
}
// 7.1 Creating a new file entry + save to disk
String parent = getParentPath(path);
MetadataEntry entry = new MetadataEntry(path, "file", parent, System.currentTimeMillis());
metadata.put(path, entry);
save();
System.out.println("[Server " + serverId + "] Created file: " + path);
sendResponse(exchange, 200, "File created: " + path);
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// 8. Handling listing directory contents
private void handleReaddir(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (!"GET".equals(requestMethod)) {
System.out.println("Unsupported method: " + requestMethod);
System.out.flush();
sendResponse(exchange, 405, "Method not allowed");
return;
}
String query = exchange.getRequestURI().getQuery();
String path = getQueryParam(query, "path");
if (path == null || path.isEmpty()) {
sendResponse(exchange, 400, "Missing or invalid 'path' parameter");
return;
}
try {
// 8.1 Checking if the path exists
MetadataEntry entry = metadata.get(path);
if (entry == null) {
sendResponse(exchange, 404, "Path not found");
return;
}
// 8.2 Verifying that it is a directory
if (!"dir".equals(entry.getType())) {
sendResponse(exchange, 400, "Path is not a directory");
return;
}
// 8.3 Finding all children of the directory
List<String> children = new ArrayList<>();
for (Map.Entry<String, MetadataEntry> e : metadata.entrySet()) {
// aka entries where this path is the parent
if (path.equals(e.getValue().getParent())) {
children.add(e.getKey());
}
}
// 8.4 Returning the sorted list of children
Collections.sort(children);
String response = String.join(", ", children);
System.out.println("[Server " + serverId + "] Listed directory: " + path);
sendResponse(exchange, 200, response.isEmpty() ? "(empty)" : response);
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// 9. Handling getting file/directory metadata
private void handleStat(HttpExchange exchange) throws IOException {
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method not allowed");
return;
}
String query = exchange.getRequestURI().getQuery();
String path = getQueryParam(query, "path");
if (path == null || path.isEmpty()) {
sendResponse(exchange, 400, "Missing or invalid 'path' parameter");
return;
}
try {
MetadataEntry entry = metadata.get(path);
if (entry == null) {
sendResponse(exchange, 404, "Path not found");
return;
}
// 9.1 Formating + returning the metadata
String response = String.format("Path: %s, Type: %s, Parent: %s, Timestamp: %d",
entry.getPath(), entry.getType(),
entry.getParent() != null ? entry.getParent() : "root",
entry.getTimestamp());
System.out.println("[Server " + serverId + "] Stat: " + path);
sendResponse(exchange, 200, response);
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// 10. Handling the removal of a file or directory
private void handleRm(HttpExchange exchange) throws IOException {
if (!"POST".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method not allowed");
return;
}
String query = exchange.getRequestURI().getQuery();
String path = getQueryParam(query, "path");
if (path == null || path.isEmpty()) {
sendResponse(exchange, 400, "Missing or invalid 'path' parameter");
return;
}
try {
MetadataEntry entry = metadata.get(path);
if (entry == null) {
sendResponse(exchange, 404, "Path not found");
return;
}
// 10.1 Check if directory is empty (only for directories)
if ("dir".equals(entry.getType())) {
for (Map.Entry<String, MetadataEntry> e : metadata.entrySet()) {
if (path.equals(e.getValue().getParent())) {
sendResponse(exchange, 400, "Directory not empty");
return;
}
}
}
// 10.2 Remove the entry + save to disk
metadata.remove(path);
save();
System.out.println("[Server " + serverId + "] Removed: " + path);
sendResponse(exchange, 200, "Removed: " + path);
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// 11. Dumping all metadata stored on the server
private void handleDump(HttpExchange exchange) throws IOException {
if (!"GET".equals(exchange.getRequestMethod())) {
sendResponse(exchange, 405, "Method not allowed");
return;
}
try {
StringBuilder sb = new StringBuilder();
sb.append("[Server ").append(serverId).append("]\n");
// 11.1 Getting all entries sorted by path for readble output
List<MetadataEntry> entries = new ArrayList<>(metadata.values());
entries.sort(Comparator.comparing(MetadataEntry::getPath));
// 11.2 Formating each entry
for (MetadataEntry entry : entries) {
sb.append(String.format(" %s -> {type=%s, parent=%s, ts=%d}\n",
entry.getPath(),
entry.getType(),
entry.getParent() != null ? entry.getParent() : "root",
entry.getTimestamp()));
}
if (entries.isEmpty()) {
sb.append(" (no entries)\n");
}
System.out.println("[Server " + serverId + "] Dump requested");
sendResponse(exchange, 200, sb.toString());
} catch (Exception e) {
sendResponse(exchange, 500, "Error: " + e.getMessage());
}
}
// Helper method: extracting parent path from a given path
// example: "/home/maria" -> "/home", "/home" -> "/", "/" -> null
private String getParentPath(String path) {
if (path.equals("/")) {
return null; // root has no parent
}
int lastSlash = path.lastIndexOf('/');
if (lastSlash == 0) {
return "/"; // parent is root
}
return lastSlash > 0 ? path.substring(0, lastSlash) : null;
}
// Helper method: extracting query param from URL
private String getQueryParam(String query, String key) {
if (query == null) return null;
String[] params = query.split("&");
for (String param : params) {
String[] pair = param.split("=", 2);
if (pair.length == 2 && key.equals(pair[0])) {
try {
return java.net.URLDecoder.decode(pair[1], StandardCharsets.UTF_8.name());
} catch (Exception e) {
return pair[1];
}
}
}
return null;
}
// Helper method: sending HTTP response
private void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
byte[] bytes = response == null ? new byte[0] : response.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(statusCode, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
// Inner class: representing a single metadata entry
public static class MetadataEntry {
private final String path; // full path
private final String type; // "file" or "dir"
private final String parent; // parent directory path
private final long timestamp; // creation time
public MetadataEntry(String path, String type, String parent, long timestamp) {
this.path = path;
this.type = type;
this.parent = parent;
this.timestamp = timestamp;
}
public String getPath() { return path; }
public String getType() { return type; }
public String getParent() { return parent; }
public long getTimestamp() { return timestamp; }
}
// 13. Stop the HTTP server
public void stop() {
if (server != null) {
server.stop(0);
System.out.println("[Server " + serverId + "] HTTP server stopped");
}
}
}