This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 302
/
DocSearchServer.java
77 lines (71 loc) · 2.5 KB
/
DocSearchServer.java
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
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
class FileHelpers {
static List<File> getFiles(Path start) throws IOException {
File f = start.toFile();
List<File> result = new ArrayList<>();
if(f.isDirectory()) {
File[] paths = f.listFiles();
for(File subFile: paths) {
result.addAll(getFiles(subFile.toPath()));
}
}
else {
result.add(start.toFile());
}
return result;
}
static String readFile(File f) throws IOException {
return new String(Files.readAllBytes(f.toPath()));
}
}
class Handler implements URLHandler {
List<File> files;
Handler(String directory) throws IOException {
this.files = FileHelpers.getFiles(Paths.get(directory));
}
public String handleRequest(URI url) throws IOException {
List<File> paths = FileHelpers.getFiles(Paths.get("./technical"));
if (url.getPath().equals("/")) {
return String.format("There are %d total files to search.", paths.size());
} else if (url.getPath().equals("/search")) {
String[] parameters = url.getQuery().split("=");
if (parameters[0].equals("q")) {
String result = "";
List<String> foundPaths = new ArrayList<>();
for(File f: paths) {
if(FileHelpers.readFile(f).contains(parameters[1])) {
foundPaths.add(f.toString());
}
}
Collections.sort(foundPaths);
result = String.join("\n", foundPaths);
return String.format("Found %d paths:\n%s", foundPaths.size(), result);
}
else {
return "Couldn't find query parameter q";
}
}
else {
return "Don't know how to handle that path!";
}
}
}
class DocSearchServer {
public static void main(String[] args) throws IOException {
if(args.length == 0){
System.out.println("Missing port number! Try any number between 1024 to 49151");
return;
}
int port = Integer.parseInt(args[0]);
Server.start(port, new Handler("./technical/"));
}
}