@Override public void handle(HttpExchange t) throws IOException { String fileId = t.getRequestURI().getPath().replaceFirst("/header/", ""); System.out.println("fileId: " + fileId); InputStream is = new FileInputStream("C:\\Users\\vadim\\Downloads\\15496_1#45.cram"); CramHeader cramHeader = CramIO.readCramHeader(is); t.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, "SAM_HEADER"); t.getResponseHeaders() .add( "CRAM_VERSION", String.format("%d.%d", cramHeader.getMajorVersion(), cramHeader.getMinorVersion())); t.sendResponseHeaders(200, 0); ByteArrayOutputStream headerBodyOS = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(headerBodyOS); new SAMTextHeaderCodec().encode(w, cramHeader.getSamFileHeader()); try { w.close(); } catch (IOException e) { throw new RuntimeException(e); } OutputStream os = t.getResponseBody(); os.write(headerBodyOS.toByteArray()); os.close(); }
@Override public String respond(HttpExchange httpExchange) { String method = httpExchange.getRequestMethod(); String uri = httpExchange.getRequestURI().getPath(); logger.log(method + " " + uri + " " + stringify(httpExchange.getRequestBody())); return NO_CONTENT; }
@Override public void handle(HttpExchange httpExchange) throws IOException { logger.info("Active endpoint Call Start"); // execute query logger.debug("Getting executor..."); Executor ex = this.getExecutor(); logger.debug("Using Executor " + ex.toString()); // ex.execute(new SetOfStatementsImpl(statements), this.getPathId()); ex.execute(new SetOfStatementsImpl(), this.getPathId()); SetOfStatements st = ex.getNextResults(this.getPathId()); StringBuffer sResponse = new StringBuffer(); sResponse.append(HTML_PART1 + generateEvents(st) + "</body></html>"); Headers responseHeaders = httpExchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/html"); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, sResponse.length()); // send back OK response httpExchange.getResponseBody().write(sResponse.toString().getBytes()); httpExchange.getResponseBody().close(); logger.info("PushEndpoint Call End"); }
@Override public void handle(HttpExchange t) throws IOException { LOGGER.debug("root req " + t.getRequestURI()); if (RemoteUtil.deny(t)) { throw new IOException("Access denied"); } if (t.getRequestURI().getPath().contains("favicon")) { RemoteUtil.sendLogo(t); return; } HashMap<String, Object> vars = new HashMap<>(); vars.put("logs", getLogs(true)); if (configuration.getUseCache()) { vars.put( "cache", "http://" + PMS.get().getServer().getHost() + ":" + PMS.get().getServer().getPort() + "/console/home"); } String response = parent.getResources().getTemplate("doc.html").execute(vars); RemoteUtil.respond(t, response, 200, "text/html"); }
@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()); }
private static void writePostReply(HttpExchange msg, byte[] buf) throws Exception { msg.getResponseHeaders().add("Content-Type", "text/xml"); msg.sendResponseHeaders(200, buf.length); OutputStream out = msg.getResponseBody(); out.write(buf); out.close(); }
public void handle(HttpExchange t) throws IOException { String response = "<h3>Happy New Year 2007!--Chinajash</h3>"; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }
@Override public void handle(HttpExchange arg0) throws IOException { byte[] utf8b = org.apache.commons.io.ByteOrderMark.UTF_8.getBytes(); String l = "a\tb\tc\t\nb\th\tj\n"; ByteArrayOutputStream ous = new ByteArrayOutputStream(); ous.write(utf8b); ous.write(l.getBytes("UTF-8")); ous.close(); byte[] k = ous.toByteArray(); Headers hdrs = arg0.getResponseHeaders(); hdrs.set("Content-Type", "application/csv"); hdrs.set("Content-Disposition", "attachment; filename=genome.csv"); hdrs.set("Content-Encoding", "binary"); hdrs.set("Charset", "utf-8"); arg0.sendResponseHeaders(200, k.length); arg0.getResponseBody().write(k); arg0.getResponseBody().close(); }
@Override public void handle(HttpExchange httpExchange) throws IOException { httpExchange.getResponseHeaders().set("Content-Type", "text/html"); httpExchange.sendResponseHeaders(HTTP_OK, content.getBytes().length); httpExchange.getResponseBody().write(content.getBytes()); httpExchange.close(); }
public static void respond( HttpExchange exchange, String redirectUrl, String name, Optional<String> message) throws IOException { LOG.finer( () -> "Redirecting to " + name + " [" + redirectUrl + "]" + message.map(m -> ": " + m).orElse("")); exchange.getResponseHeaders().set("Location", redirectUrl); exchange.sendResponseHeaders(302, 0); if ("HEAD".equals(exchange.getRequestMethod())) return; try (PrintStream out = new PrintStream(exchange.getResponseBody())) { HeaderResponse.send(out, SessionFilter.getSession(exchange), "Redirection to " + name); out.println("<DIV>"); message.ifPresent(m -> out.printf("%s<BR>\n", m)); out.printf("Go to: <A href=\"%s\"><B>%s</B></A>", redirectUrl, name); out.println("</DIV>"); } catch (Exception e) { LOG.log(Level.SEVERE, e, () -> "Failed generating redirection to '" + name + "': "); throw (e); } }
@Override protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException { Compilation compilation = getCompilation(exchange, data, config); if (compilation == null) { return; } if (!compilation.usesModules()) { HttpUtil.writeErrorMessageResponse(exchange, "This configuration does not use modules"); return; } // Get the size of each module. ModuleConfig moduleConfig = config.getModuleConfig(); Map<String, List<String>> invertedDependencyTree = moduleConfig.getInvertedDependencyTree(); Function<String, String> moduleNameToUri = moduleConfig.createModuleNameToUriFunction(); ImmutableMap.Builder<String, Pair<Integer, Integer>> builder = ImmutableMap.builder(); final boolean isDebugMode = false; for (String module : invertedDependencyTree.keySet()) { // The file size is in bytes, assuming UTF-8 input. String compiledCode = compilation.getCodeForModule(module, isDebugMode, moduleNameToUri); int uncompressedSize = compiledCode.getBytes(Charsets.UTF_8).length; int gzippedSize = GzipUtil.getGzipSize(compiledCode); builder.put(module, Pair.of(uncompressedSize, gzippedSize)); } Map<String, Pair<Integer, Integer>> moduleSizes = builder.build(); // Construct the SVG. SetMultimap<Integer, String> moduleDepths = calculateModuleDepths(moduleConfig.getRootModule(), invertedDependencyTree); Map<String, List<JsInput>> moduleToInputs; try { moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest()); } catch (CompilationException e) { throw new RuntimeException(e); } Pair<String, Dimension> svg = generateSvg( config.getId(), moduleDepths, invertedDependencyTree, moduleSizes, moduleToInputs); // Populate Soy template. Dimension svgDimension = svg.getSecond(); SoyMapData mapData = new SoyMapData( ImmutableMap.<String, Object>builder() .put("configId", config.getId()) .put("svg", svg.getFirst()) .put("svgWidth", svgDimension.width) .put("svgHeight", svgDimension.height) .build()); String xhtml = TOFU.newRenderer("org.plovr.modules").setData(mapData).render(); // Write the response. Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/xml"); exchange.sendResponseHeaders(200, xhtml.length()); Writer responseBody = new OutputStreamWriter(exchange.getResponseBody()); responseBody.write(xhtml); responseBody.close(); }
@Override public void handle(HttpExchange exchange) throws IOException { byte[] json = mapper.writeValueAsString(get()).getBytes("UTF-8"); exchange.sendResponseHeaders(200, json.length); try (OutputStream out = exchange.getResponseBody()) { out.write(json); } }
private void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException { Map<String, Object> parameters = new HashMap<String, Object>(); URI requestedUri = exchange.getRequestURI(); String query = requestedUri.getRawQuery(); parseQuery(query, parameters); exchange.setAttribute("parameters", parameters); }
@Override public void handle(HttpExchange httpExchange) throws IOException { String response = respond(httpExchange); httpExchange.sendResponseHeaders(200, response.length()); OutputStream os = httpExchange.getResponseBody(); os.write(response.getBytes()); os.close(); }
public static String getId(String path, HttpExchange t) { String id = "0"; int pos = t.getRequestURI().getPath().indexOf(path); if (pos != -1) { id = t.getRequestURI().getPath().substring(pos + path.length()); } return id; }
public void handle(HttpExchange t) throws IOException { Headers h = t.getResponseHeaders(); h.add("Content-Type", "text/xml"); String response = "This is Response status code test case"; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }
public static void dumpFile(File f, HttpExchange t) throws IOException { LOGGER.debug("file " + f + " " + f.length()); if (!f.exists()) { throw new IOException("no file"); } t.sendResponseHeaders(200, f.length()); dump(new FileInputStream(f), t.getResponseBody()); LOGGER.debug("dump of " + f.getName() + " done"); }
@Override public void handle(HttpExchange httpExchange) throws IOException { // Return a simple text message that says pong. httpExchange.getResponseHeaders().set("Content-Type", "text/plain"); String response = "pong\n"; httpExchange.sendResponseHeaders(HTTP_OK, response.getBytes().length); httpExchange.getResponseBody().write(response.getBytes()); httpExchange.close(); }
public void handlFailure(HttpExchange t, String errorMsg) throws IOException { LOG.error(errorMsg); byte[] data = errorMsg.getBytes(); t.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, data.length); OutputStream os = t.getResponseBody(); os.write(data); os.close(); }
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; }
/** Play Monument Handler for the server */ @Override public void handle(HttpExchange exchange) throws IOException { exchange.getResponseHeaders().set("Content-type", "application/json"); try { int gameID = checkCookie(exchange); if (gameID == -1) { System.err.print("\nInvalid Cookie. Thowing Error"); throw new Exception("INVALID COOKIE!"); } Gson gson = new Gson(); StringWriter writer = new StringWriter(); IOUtils.copy(exchange.getRequestBody(), writer); shared.communication.toServer.moves.Monument_ move = gson.fromJson(writer.toString(), Monument_.class); server.commands.Monument command = new server.commands.Monument(gameID); command.setParams(move); command.execute(server); this.addCommand(command, gameID); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); OutputStreamWriter output = new OutputStreamWriter(exchange.getResponseBody()); output.write(server.getModel(gameID)); output.flush(); exchange.getResponseBody().close(); exchange.close(); } catch (Exception e) { exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1); exchange.getResponseBody().close(); exchange.close(); } }
@Override @Property(MessageContext.PATH_INFO) public String getPathInfo() { URI requestUri = httpExchange.getRequestURI(); String reqPath = requestUri.getPath(); String ctxtPath = httpExchange.getHttpContext().getPath(); if (reqPath.length() > ctxtPath.length()) { return reqPath.substring(ctxtPath.length()); } return null; }
public void handle(HttpExchange t) throws IOException { ++testConnectionCount; Logger.info(this, "testConnectionCountHandler testConnectionCount: " + testConnectionCount); // InputStream is = t.getRequestBody(); // read(is); // .. read the request body String response = getClass().getSimpleName(); t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }
public static void send404(HttpExchange exchange) throws IOException { // SEND 404 String response = "404 (Not Found)\n"; exchange.sendResponseHeaders(404, response.length()); OutputStream os = exchange.getResponseBody(); try { os.write(response.getBytes()); } finally { os.close(); } }
public void handle(HttpExchange xchg) throws IOException { Headers headers = xchg.getRequestHeaders(); Set<Map.Entry<String, List<String>>> entries = headers.entrySet(); StringBuffer response = new StringBuffer(); for (Map.Entry<String, List<String>> entry : entries) response.append(entry.toString() + "\n"); xchg.sendResponseHeaders(200, response.length()); OutputStream os = xchg.getResponseBody(); os.write(response.toString().getBytes()); os.close(); }
@Override public void handle(HttpExchange t) throws IOException { String response = "This is the response"; t.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, "CRAM"); t.sendResponseHeaders(200, 0); System.out.println(t.getRequestURI()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }
public void handle(HttpExchange t) throws IOException { Hazelcast.shutdownAll(); String response = "Shutting down"; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); System.exit(-1); }
@Override protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException { Compilation compilation = getCompilation(exchange, data, config); if (compilation == null) { return; } String configId = config.getId(); List<JsInput> inputs; if (compilation.usesModules()) { ModuleConfig moduleConfig = config.getModuleConfig(); Map<String, List<JsInput>> moduleToInputs; try { moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest()); } catch (CompilationException e) { throw new RuntimeException(e); } String module = data.getParam("module"); inputs = moduleToInputs.get(module); } else { try { inputs = config.getManifest().getInputsInCompilationOrder(); } catch (CompilationException e) { HttpUtil.writeErrorMessageResponse(exchange, e.getMessage()); return; } } // Build up the list of hyperlinks. Function<JsInput, String> converter = InputFileHandler.createInputNameToUriConverter(server, exchange, configId); SoyListData inputData = new SoyListData(); for (JsInput input : inputs) { SoyMapData inputDatum = new SoyMapData(); inputDatum.put("href", converter.apply(input)); inputDatum.put("name", input.getName()); inputData.add(inputDatum); } SoyMapData soyData = new SoyMapData(); soyData.put("inputs", inputData); soyData.put("configId", configId); // Write the response. Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/html"); String html = TOFU.newRenderer("org.plovr.list").setData(soyData).render(); exchange.sendResponseHeaders(200, html.length()); Writer responseBody = new OutputStreamWriter(exchange.getResponseBody()); responseBody.write(html); responseBody.close(); }
@Override public void handle(HttpExchange t) throws IOException { Map<String, String> param = Util.getParam(t); Double interest = Bank.INSTANCE.calculateInterest(Integer.parseInt(param.get("accNum"))); String response = "Your Bank Interest is :" + interest; t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); }
private void parsePostParameters(HttpExchange exchange) throws IOException { if ("post".equalsIgnoreCase(exchange.getRequestMethod())) { @SuppressWarnings("unchecked") Map<String, Object> parameters = (Map<String, Object>) exchange.getAttribute("parameters"); InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "utf-8"); BufferedReader br = new BufferedReader(isr); String query = br.readLine(); parseQuery(query, parameters); br.close(); isr.close(); } }