-
Notifications
You must be signed in to change notification settings - Fork 79
/
StringServer.java
67 lines (63 loc) · 1.84 KB
/
StringServer.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
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
class StringHandler implements URLHandler {
List<String> lines;
String path;
StringHandler(String path) throws IOException {
this.path = path;
this.lines = Files.readAllLines(Paths.get(path));
}
public String handleRequest(URI url) throws IOException {
String query = url.getQuery();
if(url.getPath().equals("/add")) {
if(query.startsWith("s=")) {
String toAdd = query.split("=")[1];
this.lines.add(toAdd);
return String.format("%s added, there are now %s lines\n", toAdd, this.lines.size());
}
else {
return "/add requires a query parameter s\n";
}
}
else if(url.getPath().equals("/save")) {
String toSave = String.join("\n", lines) + "\n";
Files.write(Paths.get(this.path), toSave.getBytes());
return "Saved!\n";
}
else if(url.getPath().equals("/search")) {
if(query.startsWith("q=")) {
String toSearch = query.split("=")[1];
String result = "";
for(String s: lines) {
if(s.contains(toSearch)) {
result += s + "\n";
}
}
return result;
}
else {
return "/search requires a query parameter q\n";
}
}
else {
return String.join("\n", lines) + "\n";
}
}
}
class StringServer {
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;
}
if(args.length == 1){
System.out.println("Missing file path! Give a path to a text file as the second argument.");
return;
}
int port = Integer.parseInt(args[0]);
Server.start(port, new StringHandler(args[1]));
}
}