forked from ucsd-cse15l-f22/wavelet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchEngine.java
More file actions
73 lines (62 loc) · 2.44 KB
/
SearchEngine.java
File metadata and controls
73 lines (62 loc) · 2.44 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
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
class Handler implements URLHandler {
// The one bit of state on the server: a number that will be manipulated by
// various requests.
ArrayList<String> dictionary = new ArrayList<String>();
public String handleRequest(URI url) {
if (url.getPath().equals("/")) {
return String.format("Welcome to the search engine! There are currently %d items stored.", dictionary.size());
} else if (url.getPath().contains("/add")) {
String[] parameters = url.getQuery().split("=");
if (parameters[0].equals("s")) {
if (parameters.length == 1) {
return "Please specify a word to add!";
}
dictionary.add(parameters[1]);
return String.format("%s added to the dictionary!", parameters[1]);
}
} else if (url.getPath().contains("/search")) {
String[] parameters = url.getQuery().split("=");
if (parameters[0].equals("s")) {
String searchTerm = "";
if (parameters.length != 1) {
searchTerm = parameters[1];
}
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < dictionary.size(); i ++) {
if (dictionary.get(i).contains(searchTerm)) {
temp.add(dictionary.get(i));
}
}
return this.formatArrayList(temp);
}
}
return "404 Not Found!";
}
public String formatArrayList(ArrayList array) {
// Formats the search array for the Handler class into readable text.
if (array.size() == 0) {
return "No matches found!";
}
String str = "Matches: ";
for (int i = 0; i < array.size(); i ++) {
str += array.get(i);
if (i < array.size() - 1) {
str += ", ";
}
}
return str;
}
}
class SearchEngine {
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());
}
}