-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynServ.java
More file actions
68 lines (61 loc) · 2.57 KB
/
SynServ.java
File metadata and controls
68 lines (61 loc) · 2.57 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
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.io.*;
import java.util.Scanner;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class SynServ {
static Thesaurus t;
static final String NO_SUCH_WORD_MESSAGE = "error: one or both of the words entered above is not an English adjective";
static final String NO_PATH_EXISTS_MESSAGE = "No path exists. If you have words in the words to avoid list, try removing some.";
public static void main(String[] args) throws Exception {
t = new Thesaurus("./thesaurus.json");
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/demo", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange ex) throws IOException {
String response = "{'message': 'internal server error'}";
OutputStream os = ex.getResponseBody();
Scanner scan = new Scanner(ex.getRequestBody()).useDelimiter("\\A");
String json = scan.hasNext() ? scan.next() : "";
int code = 200;
try{
JSONObject j = new JSONObject(json);
String start, end;
start = j.getString("origin");
end = j.getString("destination");
JSONArray avoids = new JSONArray();
JSONObject responseJson = new JSONObject();
if(j.has("avoids")){
avoids = j.getJSONArray("avoids");
}
try{
responseJson.put("path", t.synpath(start, end, avoids));
}
catch (Thesaurus.NoSuchWordException e){
responseJson.put("message", NO_SUCH_WORD_MESSAGE);
}
catch (Thesaurus.NoPathExistsException e){
responseJson.put("message", NO_PATH_EXISTS_MESSAGE);
}
response = responseJson.toString();
}
catch (JSONException e) { //doesn't happen
e.printStackTrace();
code = 500;
}
ex.sendResponseHeaders(code, response.length());
os.write(response.getBytes());
os.close();
}
}
}