/** * Called by HttpServer when there is a matching request for the context */ public void handle(HttpExchange msg) { try { if (fineTraceEnabled) { LOGGER.log(Level.FINE, "Received HTTP request:{0}", msg.getRequestURI()); } if (executor != null) { // Use application's Executor to handle request. Application may // have set an executor using Endpoint.setExecutor(). executor.execute(new HttpHandlerRunnable(msg)); } else { handleExchange(msg); } } catch(Throwable e) { // Dont't propagate the exception otherwise it kills the httpserver } }
@Override public void handle(HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); byte[] ba = new byte[BUFFER_SIZE]; int read; long count = 0L; while((read = is.read(ba)) != -1) { count += read; } is.close(); check(count == expected, "Expected: " + expected + ", received " + count); debug("Received " + count + " bytes"); t.sendResponseHeaders(200, -1); t.close(); }
public void handle(HttpExchange arg0) throws IOException { try { InputStream is = arg0.getRequestBody(); OutputStream os = arg0.getResponseBody(); DataInputStream dis = new DataInputStream(is); short input = dis.readShort(); while (dis.read() != -1) ; dis.close(); DataOutputStream dos = new DataOutputStream(os); arg0.sendResponseHeaders(200, 0); dos.writeShort(input); dos.flush(); dos.close(); } catch (IOException e) { e.printStackTrace(); error = true; } }
@Override public void handle(HttpExchange t) throws IOException { Headers reqHeaders = t.getRequestHeaders(); // some small sanity check List<String> cookies = reqHeaders.get("Cookie"); for (String cookie : cookies) { if (!cookie.contains("JSESSIONID") || !cookie.contains("WILE_E_COYOTE")) t.sendResponseHeaders(400, -1); } // return some cookies so we can check getHeaderField(s) Headers respHeaders = t.getResponseHeaders(); List<String> values = new ArrayList<>(); values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH); values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path=" + URI_PATH +"; HttpOnly"); values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH); respHeaders.put("Set-Cookie", values); values = new ArrayList<>(); values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH); respHeaders.put("Set-Cookie2", values); values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100) + "; version=1; Path=" + URI_PATH +"; HttpOnly"); respHeaders.put("Set-Cookie2", values); t.sendResponseHeaders(200, -1); t.close(); }
@Override public void doFilter(HttpExchange he, Chain chain) throws IOException { try { System.out.println(type + ": Got " + he.getRequestMethod() + ": " + he.getRequestURI() + "\n" + HTTPTestServer.toString(he.getRequestHeaders())); if (!isAuthentified(he)) { try { requestAuthentication(he); he.sendResponseHeaders(getUnauthorizedCode(), 0); System.out.println(type + ": Sent back " + getUnauthorizedCode()); } finally { he.close(); } } else { accept(he, chain); } } catch (RuntimeException | Error | IOException t) { System.err.println(type + ": Unexpected exception while handling request: " + t); t.printStackTrace(System.err); he.close(); throw t; } }
public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); System.out.println(requestMethod + " /post"); if (requestMethod.equalsIgnoreCase("POST")) { String body = new BufferedReader( new InputStreamReader( exchange.getRequestBody() ) ).lines().collect(Collectors.joining("\n")); String[] parts = body.split("="); String name = null; if (parts.length > 1) { name = parts[1]; } exchange.getResponseHeaders().set(Constants.CONTENTTYPE, Constants.TEXTHTML); exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); responseBody.write(Constants.getIndexHTML(name)); responseBody.close(); } else { new NotImplementedHandler().handle(exchange); } }
public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); System.out.println(requestMethod + " /json"); if (requestMethod.equalsIgnoreCase("POST")) { String body = new BufferedReader( new InputStreamReader( exchange.getRequestBody() ) ).lines().collect(Collectors.joining("\n")); exchange.getResponseHeaders().set(Constants.CONTENTTYPE, Constants.APPLICATIONJSON); exchange.sendResponseHeaders(200, 0); OutputStream responseBody = exchange.getResponseBody(); responseBody.write(addPerson(body).getBytes()); responseBody.close(); } else { new NotImplementedHandler().handle(exchange); } }
@Override public void handle(HttpExchange he) throws IOException { String method = he.getRequestMethod(); InputStream is = he.getRequestBody(); if (method.equalsIgnoreCase("POST")) { String requestBody = new String(is.readAllBytes(), US_ASCII); if (!requestBody.equals(POST_BODY)) { he.sendResponseHeaders(500, -1); ok = false; } else { he.sendResponseHeaders(200, -1); ok = true; } } else { // GET he.sendResponseHeaders(200, RESPONSE.length()); OutputStream os = he.getResponseBody(); os.write(RESPONSE.getBytes(US_ASCII)); os.close(); ok = true; } }
@Override public void handleGet(HttpExchange t) { if (!isAuthenticated(t)) { Commons.writeDTO(t, new UnauthorizedDTO(), 401); return; } User user = getUser(t); List<EventMessage> messages = user.getEvents(); Collections.reverse(messages); if (messages.size() >= 10){ messages = messages.subList(0, 10); } UserEventDTO dto = new UserEventDTO(messages); Commons.writeDTO(t, dto, 200); }
@Override public void handlePost(HttpExchange t) { if (!isAuthenticated(t)) { Commons.writeDTO(t, new UnauthorizedDTO(), 401); return; } User user = getUser(t); if (InstanceManagerService.getService().hasRegisteredInstance(user)) { Commons.writeDTO(t, new ErrorDTO(false, "Bot already running."), 500); return; } InstanceManagerService.getService().start(user); Commons.writeDTO(t, new StartControllerSuccessDTO(InstanceManagerService.getService().hasRegisteredInstance(user)), 200); }
@Override public void handle(HttpExchange exchange) throws IOException { count++; try { switch(count) { case 0: AuthenticationHandler.errorReply(exchange, "Basic realm=\"realm2\""); break; case 1: t1Cond1.await(); t1cond1latch.countDown(); t1cond2latch.await(); AuthenticationHandler.okReply(exchange); break; default: System.out.println ("Unexpected request"); } } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } }
protected int getIntParameterValue(HttpExchange exchange, String param, int defaultValue) { int ival = defaultValue; final String sval = getParameterValue(exchange, param); if( sval != null && sval.length() > 0 ) { try { ival = Integer.parseInt(sval); } catch( NumberFormatException e ) { // ignore } } return ival; }
@Override public synchronized void handle (HttpExchange t) throws IOException { byte[] buf = new byte[2048]; try (InputStream is = t.getRequestBody()) { while (is.read(buf) != -1) ; } Headers map = t.getResponseHeaders(); String redirect = root + "/foo/" + Integer.toString(count); increment(); map.add("Location", redirect); t.sendResponseHeaders(301, -1); t.close(); }
@Override public void handle(HttpExchange exchange) throws IOException { count++; switch(count) { case 0: AuthenticationHandler.proxyReply(exchange, "Basic realm=\"proxy\""); break; case 1: t3cond1.countDown(); AuthenticationHandler.errorReply(exchange, "Basic realm=\"realm4\""); break; case 2: AuthenticationHandler.okReply(exchange); break; default: System.out.println ("Unexpected request"); } }
@Override public void handle(HttpExchange exchange) throws IOException { count++; switch(count) { case 0: AuthenticationHandler.errorReply(exchange, "Basic realm=\"realm2\""); try { t1Cond2.await(); } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } t1cond2latch.countDown(); break; case 1: AuthenticationHandler.okReply(exchange); break; default: System.out.println ("Unexpected request"); } }
public void handlePut(HttpExchange t) { if (!isAuthenticated(t)) { Commons.writeDTO(t, new UnauthorizedDTO(), 401); } User user = getUser(t); Reader reader = new InputStreamReader(t.getRequestBody()); SettingsInputDTO inputDTO = new Gson().fromJson(reader, SettingsInputDTO.class); if (!inputDTO.isValid()) { Commons.writeDTO(t, new BadRequestDTO(), 400); return; } GlobalConfig config = inputDTO.toGlobalConfig(user); user.setConfig(config); Database.getStore().save(user); Commons.writeDTO(t, new SettingsPutResponseDTO(), 200); }
private void handleExchange(HttpExchange msg) throws IOException { WSHTTPConnection con = new ServerConnectionImpl(adapter,msg); try { if (fineTraceEnabled) { LOGGER.log(Level.FINE, "Received HTTP request:{0}", msg.getRequestURI()); } String method = msg.getRequestMethod(); if(method.equals(GET_METHOD) || method.equals(POST_METHOD) || method.equals(HEAD_METHOD) || method.equals(PUT_METHOD) || method.equals(DELETE_METHOD)) { adapter.handle(con); } else { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning(HttpserverMessages.UNEXPECTED_HTTP_METHOD(method)); } } } finally { msg.close(); } }
@Override public void handle(HttpExchange exchange) throws IOException { count++; switch(count) { case 0: AuthenticationHandler.errorReply(exchange, "Basic realm=\"realm3\""); break; case 1: AuthenticationHandler.okReply(exchange); break; default: System.out.println ("Unexpected request"); } }
protected void writeResponse(HttpExchange he) throws IOException { if (delegate == null) { he.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); he.getResponseBody().write(he.getRequestBody().readAllBytes()); } else { delegate.handle(he); } }
public static void sendOk(HttpExchange event) throws IOException { try { event.sendResponseHeaders(200, 0); } finally { event.close(); } }
/** * * @param httpExchange * @return true if the <em>Origin</em> header contains an allowed origin or if it is empty. If the * origin header is not empty and that origin is allowed, the method adds the <em>Access-Control-Allow-Origin</em> header with that value. */ private static boolean accessControlAllowOrigin(HttpExchange httpExchange){ String allowOrigin = null; if (!httpExchange.getRequestHeaders().containsKey("Origin")) return true; List<String> origins = httpExchange.getRequestHeaders().get("Origin"); if (origins.size() != 1) return true; allowOrigin = origins.get(0); boolean allowed = allowedOrigin(allowOrigin); if (allowed) httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", allowOrigin); return allowed; }
@Override public void handleGet(HttpExchange t) { String versionNumber = getClass().getPackage().getImplementationVersion(); if (versionNumber == null) { versionNumber = "LIVE"; } Commons.writeDTO(t, new VersionInfoDTO(versionNumber), 200); }
public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); try { server.setExecutor(Executors.newFixedThreadPool(1)); server.createContext(someContext, new HttpHandler() { @Override public void handle(HttpExchange msg) { try { try { msg.sendResponseHeaders(noMsgCode, -1); } catch(IOException ioe) { ioe.printStackTrace(); } } finally { msg.close(); } } }); server.start(); System.out.println("Server started at port " + server.getAddress().getPort()); runRawSocketHttpClient("localhost", server.getAddress().getPort()); } finally { ((ExecutorService)server.getExecutor()).shutdown(); server.stop(0); } System.out.println("Server finished."); }
private static void respondMetrics(CollectorRegistry registry, HttpExchange httpExchange) throws IOException { StringWriter respBodyWriter = new StringWriter(); respBodyWriter.write("# Metrics will become visible when they are updated for the first time.\n"); TextFormat.write004(respBodyWriter, registry.metricFamilySamples()); byte[] respBody = respBodyWriter.toString().getBytes("UTF-8"); httpExchange.getResponseHeaders().put("Context-Type", Collections.singletonList("text/plain; charset=UTF-8")); httpExchange.sendResponseHeaders(200, respBody.length); httpExchange.getResponseBody().write(respBody); httpExchange.getResponseBody().close(); }
public static WebRequest fromExchange(HttpExchange exchange) { HttpMethod method = HttpMethod.valueOf(exchange.getRequestMethod()); return new WebRequest(exchange.getRequestURI().getPath(), method, Parameters.fromString(exchange.getRequestURI().getQuery()), method == HttpMethod.POST ? Parameters.fromInputStream(exchange.getRequestBody()) : Parameters.empty(), exchange.getRequestHeaders() ); }
public void handle(HttpExchange exchange) throws IOException { WebResponse response = this.process(WebRequest.fromExchange(exchange)); exchange.getResponseHeaders().putAll(response.getHeaders()); exchange.sendResponseHeaders(response.getStatus(), 0); if (null != response.getBody()) { response.getBody().write(exchange.getResponseBody(), this.renderer); } exchange.getResponseBody().flush(); exchange.getResponseBody().close(); }
public void handle(HttpExchange r) throws IOException { synchronized (DeafServer.this) { while (! wakeup) { try { DeafServer.this.wait(); } catch (InterruptedException e) { // just wait again } } } }
private void handleIniStore(String uriPath, HttpExchange exchange, Boolean hasPassword) { if (!hasPassword) { sendHTMLError(403, "Access Denied", exchange); return; } String iniStore = uriPath.substring(10); iniStore = iniStore.replace(".ini", ""); String[] sections = Quorrabot.instance().getDataStore().GetCategoryList(iniStore); String outputString = ""; for (String section : sections) { if (section != null && !section.equals("")) { outputString += "\r\n\r\n[" + section + "]"; } String[] keys = Quorrabot.instance().getDataStore().GetKeyList(iniStore, section); for (String key : keys) { String value = Quorrabot.instance().getDataStore().GetString(iniStore, section, key); outputString += "\r\n" + key + "=" + value; } } sendData("text/text", outputString, exchange); }
@Override public void handle(HttpExchange t) throws IOException { // retrieve the request json data InputStream is = t.getRequestBody(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len; while ((len = is.read(buffer))>0) { bos.write(buffer, 0, len); } bos.close(); String data = new String(bos.toByteArray(), Charset.forName("UTF-8")); logit("Request: \n " + data); // pass the data to the handler and receive a response String response = handler.handleRequest(data); logit(" " + response); // format and return the response to the user t.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length); // t.getResponseHeaders().set("Content-Type", "application/json"); t.getResponseHeaders().set("Content-Type", "application/json, charset=UTF-8"); OutputStream os = t.getResponseBody(); os.write(response.getBytes(Charset.forName("UTF-8"))); os.close(); }
private void testPut(int status) throws MalformedURLException, ParseException { //Util.enableHttpClientTracing(); int numDataPoints = 10; ArrayList<DataPoint> dataPoints = createDataPoints(numDataPoints); URL apiEndPoint = httpServer.getUrl(status); ApptuitPutClient client = new ApptuitPutClient(MockServer.token, globalTags, apiEndPoint); client.put(dataPoints); List<HttpExchange> exchanges = httpServer.getExchanges(); List<String> requestBodies = httpServer.getRequestBodies(); HttpExchange exchange = exchanges.get(0); assertEquals("POST", exchange.getRequestMethod()); assertEquals(MockServer.path, exchange.getRequestURI().getPath()); Headers headers = exchange.getRequestHeaders(); assertEquals("gzip", headers.getFirst("Content-Encoding")); assertEquals("application/json", headers.getFirst("Content-Type")); assertEquals("Bearer " + MockServer.token, headers.getFirst("Authorization")); DataPoint[] unmarshalledDPs = Util.jsonToDataPoints(requestBodies.get(0)); assertEquals(numDataPoints, unmarshalledDPs.length); for (int i = 0; i < numDataPoints; i++) { assertEquals(getExpectedDataPoint(dataPoints.get(i), globalTags), unmarshalledDPs[i]); } }
private int getResponseType(HttpExchange exchange) { URI uri = exchange.getRequestURI(); String rawQuery = uri.getRawQuery(); if (rawQuery == null) { return HttpURLConnection.HTTP_OK; } if ("status=400".equals(rawQuery)) { return HttpURLConnection.HTTP_BAD_REQUEST; } return HttpURLConnection.HTTP_OK; }
public static void createInstanceThroughScheduler(HttpExchange t, BigInteger rank, String numeroFatorizar, int identifier) { ExecutorService service = Executors.newCachedThreadPool(); InstanceObject instanceCreated = AutoScaling.startInstance(ec2); System.out.println("Instance created with id : " + instanceCreated.getInstance().getInstanceId()); lockListOfActiveInstances.lock(); listOfActiveInstances.add(instanceCreated); //atualizamos este pedido como um que instancia que acabou de ser criada esta a tratar Request request = new Request(t, rank, numeroFatorizar); CompletableFuture.runAsync(()->listOfActiveInstances.get(listOfActiveInstances.indexOf(instanceCreated)).addRequestToRequestProcessingList(request),service); lockListOfActiveInstances.unlock(); //metodo responsavel por iniciar os health checks e a verificacao de CPU da nova instancia criada //e tambem de reinicializar a verificacao de CPU da instancia que ultrapassou o threshold de utilizacao de CPU CompletableFuture.runAsync(()->AutoScaling.setupChecksNewInstance(instanceCreated),service); //antes de enviarmos o pedido para a instancia temos que dar tempo para a instancia comecar try { Thread.sleep(AutoScaling.GRACE_PERIOD); if(identifier == 1) //serve para identificar quem chamou este metodo e consoante aplicamos condicoes diferenteswa { lockCreateInstances.lock(); instanceBeingCreated = false; //instancias ja podem ser criadas lockCreateInstances.unlock(); } } catch (InterruptedException e) {} CompletableFuture.runAsync(()->sendToInstance(instanceCreated, numeroFatorizar, t),service); }
@Override public void handle(HttpExchange he, InputStream req, OutputStream res, String[] path) throws Exception { StringBuilder sb = new StringBuilder(); sb.append("\"nestId\",\"family\",\"longitude\",\"latitude\",\"createDate\",\"lastUpdate\",\"notes\"\n"); Connection con = DatabaseConnection.getConnection(); try (PreparedStatement stmt = con.prepareStatement("SELECT `nestId`, `family`, `longitude`, `latitude`, `createDate`, `lastUpdate`, `notes` FROM nest WHERE `visible` = 1 LIMIT 9999")) { try (ResultSet rs = stmt.executeQuery()) { boolean looped = false; while (rs.next()) { if (looped) { sb.append("\n"); } sb.append("\"").append(rs.getString(1)).append("\"").append(","); sb.append("\"").append(rs.getString(2)).append("\"").append(","); sb.append("\"").append(rs.getDouble(3)).append("\"").append(","); sb.append("\"").append(rs.getDouble(4)).append("\"").append(","); sb.append("\"").append(rs.getString(5)).append("\"").append(","); sb.append("\"").append(rs.getString(6)).append("\"").append(","); sb.append("\"").append(rs.getString(7).replace("\"", "\"\"")).append("\""); looped = true; } } } catch (Exception e) { e.printStackTrace(); } sendResponse(he, 200, sb.toString()); }
@Override public synchronized void handle(HttpExchange t) throws IOException { String reply = "Hello world"; int len = reply.length(); Headers h = t.getRequestHeaders(); checkHeader(h); System.out.printf("Sending response 200\n"); t.sendResponseHeaders(200, len); OutputStream o = t.getResponseBody(); o.write(reply.getBytes()); t.close(); }
@Override public void handle(final HttpExchange t) throws IOException { final byte [] response = healthyMsg.getBytes(); t.sendResponseHeaders(200, response.length); final OutputStream os = t.getResponseBody(); os.write(response); os.close(); }
void moved(HttpExchange t) throws IOException { Headers req = t.getRequestHeaders(); Headers map = t.getResponseHeaders(); URI uri = t.getRequestURI(); String host = req.getFirst("Host"); String location = "http://" + host + uri.getPath() + "/"; map.set("Content-Type", "text/html"); map.set("Location", location); t.sendResponseHeaders(301, -1); t.close(); }
public void upload(HttpExchange exchange) throws IOException { final Map<String, Pair<String, File>> streams = getMultipartStreams(exchange); final Pair<String, File> file = streams.get("file"); //$NON-NLS-1$ if( file != null ) { String filename = file.getFirst(); if( Utils.VERSION_EXTRACT.matcher(filename).matches() ) { File vf = config.getUpdatesDir(); Files.move(file.getSecond(), new File(vf, filename)); } } HttpExchangeUtils.respondRedirect(exchange, "/pages/"); //$NON-NLS-1$ }