private void handleAddProduct(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); SQLConnection conn = routingContext.get("conn"); JsonObject product = routingContext.getBodyAsJson(); conn.updateWithParams("INSERT INTO products (name, price, weight) VALUES (?, ?, ?)", new JsonArray().add(product.getString("name")).add(product.getFloat("price")).add(product.getInteger("weight")), query -> { if (query.failed()) { sendError(500, response); } else { response.end(); } }); }
private void handleListProducts(RoutingContext routingContext) { HttpServerResponse response = routingContext.response(); SQLConnection conn = routingContext.get("conn"); conn.query("SELECT id, name, price, weight FROM products", query -> { if (query.failed()) { sendError(500, response); } else { JsonArray arr = new JsonArray(); query.result().getRows().forEach(arr::add); routingContext.response().putHeader("content-type", "application/json").end(arr.encode()); } }); }
@Override public void handle(RoutingContext rc) { rc.addHeadersEndHandler(v -> { if (rc.get(disableFlag) != null) { return; } String acceptableContentType = rc.getAcceptableContentType(); if (acceptableContentType == null) { return; } MultiMap headers = rc.response().headers(); if (headers.contains(CONTENT_TYPE)) { return; } if (!"0".equals(headers.get(CONTENT_LENGTH))) { headers.add(CONTENT_TYPE, acceptableContentType); } }); rc.next(); } }
private void handleGetProduct(RoutingContext routingContext) { String productID = routingContext.request().getParam("productID"); HttpServerResponse response = routingContext.response(); if (productID == null) { sendError(400, response); } else { SQLConnection conn = routingContext.get("conn"); conn.queryWithParams("SELECT id, name, price, weight FROM products where id = ?", new JsonArray().add(Integer.parseInt(productID)), query -> { if (query.failed()) { sendError(500, response); } else { if (query.result().getNumRows() == 0) { sendError(404, response); } else { response.putHeader("content-type", "application/json").end(query.result().getRows().get(0).encode()); } } }); } }
@Test public void test_remove_data() throws Exception { router.route().handler(event -> { String foo = event.getBodyAsJson().encode(); event.put("foo", foo); String removedFoo = event.remove("foo"); assertEquals(removedFoo, foo); assertNull(event.get("foo")); event.response().end(); }); testRequest(HttpMethod.POST, "/", req -> { req.setChunked(true); req.write(Buffer.buffer("{ \"foo\": \"bar\" }")); }, HttpResponseStatus.OK.code(), HttpResponseStatus.OK.reasonPhrase(), null); }
@Override public void handle(RoutingContext context) { TracingHandler tracingHandler = context.get(TracingHandler.class.getName()); if (tracingHandler != null) { // then we already have a span if (!context.failed()) { // re-routed, so re-attach the end handler context.addHeadersEndHandler(tracingHandler); } context.next(); return; } Span span = serverHandler.handleReceive(extractor, context.request()); TracingHandler handler = new TracingHandler(context, span); context.put(TracingHandler.class.getName(), handler); context.addHeadersEndHandler(handler); try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) { context.next(); } }
RequestParameters params = routingContext.get("parsedParameters");
SQLConnection conn = routingContext.get("conn"); if (conn != null) { conn.close(v -> {
@Override public <T> T get(String key) { return decoratedContext.get(key); }
@Override public <T> T get(String key) { return inner.get(key); }
private AuthProvider getAuthProvider(RoutingContext ctx) { try { AuthProvider provider = ctx.get(AUTH_PROVIDER_CONTEXT_KEY); if (provider != null) { // we're overruling the configured one for this request return provider; } } catch (RuntimeException e) { // bad type, ignore and return default } return authProvider; } }
RequestParameters params = routingContext.get("parsedParameters"); .handler(HTTPRequestValidationHandler.create().addJsonBodySchema("{type: string}")) .handler((routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); JsonObject body = params.body().getJsonObject(); })); RequestParameters params = routingContext.get("parsedParameters"); Integer primeNumber = params.queryParameter("primeNumber").getInteger(); }));
private void failureHandler(RoutingContext context) { LOGGER.error("http server failed.", context.failure()); AbstractRestInvocation restProducerInvocation = context.get(RestConst.REST_PRODUCER_INVOCATION); Throwable e = context.failure(); if (ErrorDataDecoderException.class.isInstance(e)) { Throwable cause = e.getCause(); if (InvocationException.class.isInstance(cause)) { e = cause; } } // only when unexpected exception happens, it will run into here. // the connection should be closed. handleFailureAndClose(context, restProducerInvocation, e); }
@Test public void testMultipleSetHandler() throws Exception { router.get("/path").handler(routingContext -> { routingContext.put("response", "handler1"); routingContext.next(); }).handler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.next(); }).handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.end(routingContext.get("response") + "handler3"); }); testRequest(HttpMethod.GET, "/path", 200, "OK", "handler1handler2handler3"); }
@Test public void testMultipleSetHandlerMultipleRouteObject() throws Exception { router.get("/path").handler(routingContext -> { routingContext.put("response", "handler1"); routingContext.next(); }); router.get("/path").handler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.next(); }).handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.end(routingContext.get("response") + "handler3"); }); testRequest(HttpMethod.GET, "/path", 200, "OK", "handler1handler2handler3"); }
@Test public void testGetPutContextData() throws Exception { SomeObject obj = new SomeObject(); router.route().handler(ctx -> { ctx.put("foo", "bar"); ctx.put("blah", obj); ctx.next(); }); router.route().handler(ctx -> { assertEquals("bar", ctx.get("foo")); assertEquals(obj, ctx.get("blah")); ctx.response().end(); }); testRequest(HttpMethod.GET, "/", 200, "OK"); }
@Test public void testMultipleSetFailureHandler() throws Exception { router.get("/path").handler(routingContext -> routingContext.fail(500)).failureHandler(routingContext -> { routingContext.put("response", "handler1"); routingContext.next(); }).failureHandler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.next(); }).failureHandler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.setStatusMessage("ERROR"); response.setStatusCode(500); response.end(routingContext.get("response") + "handler3"); }); testRequest(HttpMethod.GET, "/path", 500, "ERROR", "handler1handler2handler3"); }
@Override public void handle(RoutingContext context) { HttpServerRequest request = context.request(); if (request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { context.next(); return; } // we need to keep state since we can be called again on reroute Boolean handled = context.get(BODY_HANDLED); if (handled == null || !handled) { BHandler handler = new BHandler(context); request.handler(handler); request.endHandler(v -> handler.end()); context.put(BODY_HANDLED, true); } else { // on reroute we need to re-merge the form params if that was desired if (mergeFormAttributes && request.isExpectMultipart()) { request.params().addAll(request.formAttributes()); } context.next(); } }
@Test public void testMultipleSetFailureHandlerCorrectOrder() throws Exception { router.route().failureHandler(routingContext -> { routingContext.put("response", "handler1"); routingContext.next(); }); router.get("/path").handler(routingContext -> routingContext.fail(500)).failureHandler(routingContext -> { routingContext.put("response", routingContext.get("response") + "handler2"); routingContext.next(); }).failureHandler(routingContext -> { HttpServerResponse response = routingContext.response(); response.setChunked(true); response.setStatusMessage("ERROR"); response.setStatusCode(500); response.end(routingContext.get("response") + "handler3"); }); testRequest(HttpMethod.GET, "/path", 500, "ERROR", "handler1handler2handler3"); }
@Override public void handle(RoutingContext context) { HttpServerRequest request = context.request(); if (request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { context.next(); return; } // we need to keep state since we can be called again on reroute Boolean handled = context.get(BODY_HANDLED); if (handled == null || !handled) { long contentLength = isPreallocateBodyBuffer ? parseContentLengthHeader(request) : -1; BHandler handler = new BHandler(context, contentLength); request.handler(handler); request.endHandler(v -> handler.end()); context.put(BODY_HANDLED, true); } else { // on reroute we need to re-merge the form params if that was desired if (mergeFormAttributes && request.isExpectMultipart()) { request.params().addAll(request.formAttributes()); } context.next(); } }