| 67 | return websocketPort; |
| 68 | } |
| 69 | |
| 70 | public int getPort() { |
| 71 | return port; |
| 72 | } |
| 73 | |
| 74 | |
| 75 | public Server(int port, int websocketPort) throws IOException { |
| 76 | this.port = port; |
| 77 | this.websocketPort = websocketPort; |
| 78 | server = new NanoHTTPD(port) { |
| 79 | @Override |
| 80 | Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { |
| 81 | |
| 82 | Log.log("server", () -> "Serving " + uri); |
| 83 | |
| 84 | Log.log("server", () -> "will check:" + uriHandlers); |
| 85 | |
| 86 | Object id = parms.get("id"); |
| 87 | |
| 88 | if (id == null) { |
| 89 | id = "" + (uniq++); |
| 90 | } |
| 91 | |
| 92 | if (fixedResources.containsKey(uri)) { |
| 93 | String resource = fixedResources.get(uri); |
| 94 | resource = resource.replace("///ID///", "" + id); |
| 95 | resource = resource.replace("///PORT///", "" + port); |
| 96 | resource = resource.replace("///WSPORT///", "" + websocketPort); |
| 97 | return new Response(Response.Status.OK, null, resource); |
| 98 | } |
| 99 | |
| 100 | if (uri.startsWith(FIELD_FILESYSTEM)) { |
| 101 | |
| 102 | String e = uri.substring("/field/filesystem/".length()); |
| 103 | |
| 104 | for (String s : documentRoots) { |
| 105 | File ff = new File(s + "/" + e); |
| 106 | if (ff.exists()) { |
| 107 | //return new Response(Response.Status.OK, null, new BufferedInputStream(new FileInputStream(ff))); |
| 108 | |
| 109 | return serveFile(uri, headers, ff, "application/octet-stream"); |
| 110 | } |
| 111 | } |
| 112 | return new Response(Response.Status.NOT_FOUND, null, "couldn't find " + e); |
| 113 | } |
| 114 | |
| 115 | for (URIHandler u : uriHandlers) { |
| 116 | Response r = u.serve(uri, method, headers, parms, files); |
| 117 | if (r != null) |
| 118 | return r; |
| 119 | } |
| 120 | |
| 121 | return new Response(Response.Status.BAD_REQUEST, null, " couldn't understand request"); |
| 122 | } |
| 123 | }; |
| 124 | |
| 125 | server.start(); |
| 126 | |