Debian Codegraph @

current/server/SimpleHttpServer.java

raw symbols SCIP
1 package server;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.net.InetSocketAddress;
6 import java.util.HashMap;
7 import java.util.Map;
8
9 import com.sun.net.httpserver.Headers;
10 import com.sun.net.httpserver.HttpExchange;
11 import com.sun.net.httpserver.HttpHandler;
12 import com.sun.net.httpserver.HttpServer;
13
14 import shared.Tools;
15
16 /**
17 * @author Shijie Yao
18 * @date Dec 13, 2016
19 *
20 */
21 public class SimpleHttpServer {
22 public static int port = 8321;
23
24 public static void main(String[] args) throws Exception {
25 HttpServer server = HttpServer.create(new InetSocketAddress(SimpleHttpServer.port), 0);
26 server.createContext("/", new GetHandler());
27 server.setExecutor(null); // creates a default executor
28 server.start();
29 }
30
31 static class GetHandler implements HttpHandler {
32 @Override
33 public void handle(HttpExchange t) throws IOException {
34 Headers h = t.getResponseHeaders();
35 h.add("Content-Type", "application/json");
36 //String query = t.getRequestURI().getQuery(); //the KEY=VAL&KEY=VAL params in URL
37 String rparam = t.getRequestURI().toString(); //restful style params, KEY/VAL in URL
38 if (rparam.startsWith("/")){
39 rparam = rparam.substring(1);
40 }
41 if (rparam.endsWith("/")){
42 rparam = rparam.substring(rparam.length()-1);
43 }
44 System.out.println(rparam);
45
46
47
48 String[] params = rparam.split("/");
49 Map<String,String> map = new HashMap<String,String>(); //should be <String, Object>
50
51 if (params.length == 2){
52 map.put(params[0], params[1]);
53 // fill in other data here
54
55 map.put("tax_id", "654321");
56 map.put("organism", "e. coli");
57
58
59 } else {
60 map.put("error", "need restful-style param like gi/123456");
61 }
62
63 String response = "{";
64
65 for (Map.Entry<String, String> entry : map.entrySet()){
66 response+=Tools.format("\"%s\":\"%s\"", entry.getKey(), entry.getValue());
67 }
68 response+="}";
69
70 //String response = "{\"name\": \"a json string\"}";
71 t.sendResponseHeaders(200, response.length());
72 OutputStream os = t.getResponseBody();
73 os.write(response.getBytes());
74 os.close();
75 }
76 }
77 }