@Override protected void wrappedHandle(HttpExchange t, String[] path, LinkedHashMap<String, String> query) throws Exception { l.info( "GET " + t.getRequestURI() + " " + t.getRemoteAddress()); // TODO - create a special logger for this! String[] longestMatch = getLongestMatch(path); LazyInstantiator<SafeHttpHandler> handler = handlers.get(longestMatch); if (handler == null) { String failMessage = "No handler found for: " + Arrays.toString(path); l.info(failMessage); sendText(t, failMessage); return; } TimedLogRecordStart start = new TimedLogRecordStart("calling " + handler); l.log(start); int startIndex = longestMatch.length; String[] truncatedPath = Arrays.copyOfRange(path, startIndex, path.length); handler.cachedInstance().wrappedHandle(t, truncatedPath, query); l.log(start.finishedNow()); }
public static WebRender matchRenderer(String user, HttpExchange t) { int browser = WebRender.getBrowser(t.getRequestHeaders().getFirst("User-agent")); String confName = WebRender.getBrowserName(browser); RendererConfiguration r = RendererConfiguration.find(confName, t.getRemoteAddress().getAddress()); return ((r instanceof WebRender) && (StringUtils.isBlank(user) || user.equals(((WebRender) r).getUser()))) ? (WebRender) r : null; }
protected void handleGet(HttpExchange exchange) throws IOException { try { InputStream in = exchange.getRequestBody(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { bout.write(buf, 0, read); } in.close(); InetSocketAddress source = exchange.getRemoteAddress(); byte[] raw = source.getHostName().getBytes(); exchange.sendResponseHeaders(200, raw.length); exchange.getResponseBody().write(raw); exchange.close(); } catch (Exception e) { e.printStackTrace(); exchange.sendResponseHeaders(400, 0); exchange.close(); } }
@Override public void handle(HttpExchange t) throws IOException { try { Thread.currentThread() .setName("Cmd Thread " + Thread.currentThread().getId() + " " + t.getRemoteAddress()); s_logger.info("CmdHandler " + t.getRequestURI()); doHandle(t); } catch (Exception e) { s_logger.error(e.toString(), e); String response = "Not found"; t.sendResponseHeaders(404, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } catch (OutOfMemoryError e) { s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched"); System.exit(1); } catch (Throwable e) { s_logger.error(e.toString(), e); } finally { t.close(); } }
public void associate(HttpExchange t, WebRender webRenderer) { webRenderer.associateIP(t.getRemoteAddress().getAddress()); webRenderer.associatePort(t.getRemoteAddress().getPort()); }
public RootFolder getRoot(String user, boolean create, HttpExchange t) { String groupTag = getTag(user); String cookie = RemoteUtil.getCookie("UMS", t); RootFolder root; synchronized (roots) { root = roots.get(cookie); if (root == null) { // Double-check for cookie errors WebRender valid = RemoteUtil.matchRenderer(user, t); if (valid != null) { // A browser of the same type and user is already connected at // this ip but for some reason we didn't get a cookie match. RootFolder validRoot = valid.getRootFolder(); // Do a reverse lookup to see if it's been registered for (Map.Entry<String, RootFolder> entry : roots.entrySet()) { if (entry.getValue() == validRoot) { // Found root = validRoot; cookie = entry.getKey(); LOGGER.debug( "Allowing browser connection without cookie match: {}: {}", valid.getRendererName(), t.getRemoteAddress().getAddress()); break; } } } } if (!create || (root != null)) { t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/"); return root; } ArrayList<String> tag = new ArrayList<>(); tag.add(user); if (!groupTag.equals(user)) { tag.add(groupTag); } tag.add(t.getRemoteAddress().getHostString()); tag.add("web"); root = new RootFolder(tag); try { WebRender render = new WebRender(user); root.setDefaultRenderer(render); render.setRootFolder(root); render.associateIP(t.getRemoteAddress().getAddress()); render.associatePort(t.getRemoteAddress().getPort()); if (configuration.useWebSubLang()) { render.setSubLang(StringUtils.join(RemoteUtil.getLangs(t), ",")); } // render.setUA(t.getRequestHeaders().getFirst("User-agent")); render.setBrowserInfo( RemoteUtil.getCookie("UMSINFO", t), t.getRequestHeaders().getFirst("User-agent")); PMS.get().setRendererFound(render); } catch (ConfigurationException e) { root.setDefaultRenderer(RendererConfiguration.getDefaultConf()); } // root.setDefaultRenderer(RendererConfiguration.getRendererConfigurationByName("web")); root.discoverChildren(); cookie = UUID.randomUUID().toString(); t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/"); roots.put(cookie, root); } return root; }
public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); if (requestMethod.equalsIgnoreCase("GET")) { Headers responseHeaders = exchange.getResponseHeaders(); InetSocketAddress cIP = exchange.getRemoteAddress(); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); Set<String> keySet = requestHeaders.keySet(); URI path = exchange.getRequestURI(); System.out.println("GET " + path.toString() + " " + cIP.toString()); String urlParts[] = path.toString().split("/"); String response = ""; // System.out.println(urlParts.length); if (urlParts.length == 8) { String[] clrt = StringUtils.split(urlParts[7], "."); if (clrt[1].equalsIgnoreCase("json") || clrt[1].equalsIgnoreCase("xml") || clrt[1].equalsIgnoreCase("plain")) { HTTPCassandra CassInterface = new HTTPCassandra(); String res[] = CassInterface.handleGET(urlParts); if (res[0].equals("200")) { response = res[1]; responseHeaders.set("Content-Type", res[2]); exchange.sendResponseHeaders(200, response.length()); } else { responseHeaders.set("Content-Type", "text/html"); response = "<h1>" + res[1] + "</h1>"; exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length()); } } else { responseHeaders.set("Content-Type", "text/html"); response = "<h1>Unsupported Media Type</h1>"; exchange.sendResponseHeaders(415, response.length()); } } else if (urlParts.length == 0) { if (path.toString().equals("/")) { String str, page = ""; try { Process p = Runtime.getRuntime().exec("pwd"); String s = null; BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } BufferedReader in = new BufferedReader(new FileReader("../html/test.htm")); while ((str = in.readLine()) != null) { page = page + str; } in.close(); } catch (IOException e) { System.out.println("Failed to read in file"); } response = page; responseHeaders.set("Content-Type", "text/html"); exchange.sendResponseHeaders(200, response.length()); } else { responseHeaders.set("Content-Type", "text/html"); response = "<H1>RESTandra - 400 Bad Request</H1>"; exchange.sendResponseHeaders(400, response.length()); } } else { responseHeaders.set("Content-Type", "text/html"); String error[] = lengthError(urlParts.length); response = error[1]; exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length()); } responseBody.write(response.getBytes()); responseBody.close(); } else if (requestMethod.equalsIgnoreCase("POST")) { Headers responseHeaders = exchange.getResponseHeaders(); InetSocketAddress cIP = exchange.getRemoteAddress(); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); URI path = exchange.getRequestURI(); BufferedReader in = null; in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String reqBody = ""; String response = ""; // Log Request System.out.println("POST Request from: " + cIP.toString() + " Path: " + path.toString()); // Read POST variables/Request body String urlParts[] = path.toString().split("/"); reqBody = in.readLine(); if (reqBody != null) { if (urlParts.length == 8) { HTTPCassandra CassInterface = new HTTPCassandra(); // todo: url decode String[] vars = reqBody.toString().split("&"); String res[] = CassInterface.handlePOST(urlParts, vars); if (res[0].equals("201")) { response = res[1]; responseHeaders.set("Content-Type", "text/html"); exchange.sendResponseHeaders(201, response.length()); } else { responseHeaders.set("Content-Type", "text/html"); response = "<h1>" + res[1] + "</h1>"; exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length()); } } else { responseHeaders.set("Content-Type", "text/html"); String error[] = lengthError(urlParts.length); response = error[1]; System.out.println(response + " " + response.length()); exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length()); } } else { System.out.println("Empty POST request"); responseHeaders.set("Content-Type", "text/html"); response = "<H1>Empty POST Request</H1> "; exchange.sendResponseHeaders(400, 0); } responseBody.write(response.getBytes()); responseBody.close(); } else if (requestMethod.equalsIgnoreCase("PUT")) { Headers responseHeaders = exchange.getResponseHeaders(); InetSocketAddress cIP = exchange.getRemoteAddress(); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); URI path = exchange.getRequestURI(); BufferedReader in = null; in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String reqBody = ""; String response = ""; // Log Request System.out.println("POST Request from: " + cIP.toString() + " Path: " + path.toString()); // Read POST variables/Request body String urlParts[] = path.toString().split("/"); reqBody = in.readLine(); if (reqBody != null) { if (urlParts.length == 8) { HTTPCassandra CassInterface = new HTTPCassandra(); // todo: url decode String[] vars = reqBody.toString().split("&"); String res[] = CassInterface.handlePOST(urlParts, vars); if (res[0].equals("201")) { response = res[1]; responseHeaders.set("Content-Type", "text/html"); exchange.sendResponseHeaders(201, response.length()); } else { responseHeaders.set("Content-Type", "text/html"); response = "<h1>" + res[1] + "</h1>"; exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length()); } } else { responseHeaders.set("Content-Type", "text/html"); String error[] = lengthError(urlParts.length); response = error[1]; System.out.println(response + " " + response.length()); exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length()); } } else { System.out.println("Empty PUT request"); responseHeaders.set("Content-Type", "text/html"); response = "<H1>Empty PUT Request</H1> "; exchange.sendResponseHeaders(400, 0); } responseBody.write(response.getBytes()); responseBody.close(); } else if (requestMethod.equalsIgnoreCase("DELETE")) { Headers responseHeaders = exchange.getResponseHeaders(); InetSocketAddress cIP = exchange.getRemoteAddress(); OutputStream responseBody = exchange.getResponseBody(); Headers requestHeaders = exchange.getRequestHeaders(); URI path = exchange.getRequestURI(); BufferedReader in = null; in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String reqBody = ""; String response = ""; String urlParts[] = path.toString().split("/"); // Log Request System.out.println("DELETE Request from: " + cIP.toString() + " Path: " + path.toString()); HTTPCassandra CassInterface = new HTTPCassandra(); String res[] = CassInterface.handleDELETE(urlParts); System.out.println(res[1]); responseHeaders.set("Content-Type", "text/html"); String testResponse = "<H1>DELETE</H1>"; exchange.sendResponseHeaders(200, 0); responseBody.write(testResponse.getBytes()); responseBody.close(); } }
@Override public void handle(HttpExchange httpExchange) throws IOException { // Set common response headers httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); // Get sentence. Properties props; Annotation ann; StanfordCoreNLP.OutputFormat of; log("[" + httpExchange.getRemoteAddress() + "] Received message"); try { props = getProperties(httpExchange); ann = getDocument(props, httpExchange); of = StanfordCoreNLP.OutputFormat.valueOf( props.getProperty("outputFormat", "json").toUpperCase()); // Handle direct browser connections (i.e., not a POST request). if (ann.get(CoreAnnotations.TextAnnotation.class).length() == 0) { log("[" + httpExchange.getRemoteAddress() + "] Interactive connection"); staticPageHandle.handle(httpExchange); return; } log("[" + httpExchange.getRemoteAddress() + "] API call"); } catch (Exception e) { // Return error message. e.printStackTrace(); String response = e.getMessage(); httpExchange.getResponseHeaders().add("Content-Type", "text/plain"); httpExchange.sendResponseHeaders(HTTP_BAD_INPUT, response.length()); httpExchange.getResponseBody().write(response.getBytes()); httpExchange.close(); return; } try { // Annotate StanfordCoreNLP pipeline = mkStanfordCoreNLP(props); Future<Annotation> completedAnnotationFuture = corenlpExecutor.submit( () -> { pipeline.annotate(ann); return ann; }); Annotation completedAnnotation = completedAnnotationFuture.get(5, TimeUnit.SECONDS); // Get output ByteArrayOutputStream os = new ByteArrayOutputStream(); StanfordCoreNLP.createOutputter(props, AnnotationOutputter.getOptions(pipeline)) .accept(completedAnnotation, os); os.close(); byte[] response = os.toByteArray(); httpExchange.getResponseHeaders().add("Content-Type", getContentType(props, of)); httpExchange.getResponseHeaders().add("Content-Length", Integer.toString(response.length)); httpExchange.sendResponseHeaders(HTTP_OK, response.length); httpExchange.getResponseBody().write(response); httpExchange.close(); } catch (TimeoutException e) { respondError("CoreNLP request timed out", httpExchange); } catch (Exception e) { // Return error message. respondError(e.getClass().getName() + ": " + e.getMessage(), httpExchange); } }
@Override public void handle(HttpExchange he) throws IOException { try { String uri = he.getRequestURI().getPath(); if (uri != null && uri.startsWith("/")) { // For the time being, the URI is split up this way: /* /s/play/My%20Song.mp3 = /s = context (1) /play = command (2) /100 = song id in internal db (3) /My%20Song.mp3 (4) // friendly name for players that can't read extended M3u info */ String[] cmdargs = uri.split("/", 4); String context = cmdargs[1]; // TODO - should we do anything with this? String cmdStr = cmdargs[2]; path = ""; if (cmdargs.length > 3) { StringBuilder sb = new StringBuilder(); for (int x = 3; x < cmdargs.length; x++) sb.append(cmdargs[x]); path = sb.toString(); } if (cmdStr != null) { hr = he.getRequestHeaders(); String remotehost = he.getRemoteAddress().getHostString(); FilterAction fa = clientlist.filterActionFor(remotehost); action = clientlist.getDefaultAction(); options = null; if (fa != null) { action = fa.getAction(); options = fa.getOptions(); } stats.countStat("CLIENT_ACTION", action.toString()); stats.countStat("CLIENT", remotehost); final AbstractCommand cmd; if (allowedCommands != null) { Command.Type cmdStrType = Command.Type.get(cmdStr); if (Arrays.asList(allowedCommands).contains(cmdStrType)) { cmd = factory.create(cmdStrType, he, rootdir); handleAccess(he, cmd); } else { throw new IllegalArgumentException( "This type of handler doesn't support the '" + cmdStr + "' command"); } } } } } catch (Exception e) { LOG.log(Level.SEVERE, "Problem handling request", e); } finally { he.close(); } }
public static boolean bumpAllowed(HttpExchange t) { if (bumpFilter == null) { bumpFilter = new IpFilter(PMS.getConfiguration().getBumpAllowedIps()); } return bumpFilter.allowed(t.getRemoteAddress().getAddress()); }
public static boolean deny(HttpExchange t) { return !PMS.getConfiguration().getIpFiltering().allowed(t.getRemoteAddress().getAddress()) || !PMS.isReady(); }