io.vertx.core.http.HttpServerRequest Java Examples
The following examples show how to use
io.vertx.core.http.HttpServerRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CheckTokenHandler.java From nubes with Apache License 2.0 | 6 votes |
private String parseApiToken(HttpServerRequest request) throws BadRequestException { String authorization = request.headers().get(HttpHeaders.AUTHORIZATION); if (authorization != null) { String[] parts = authorization.split(" "); String sscheme = parts[0]; if (!"token".equals(sscheme)) { throw new BadRequestException(); } if (parts.length < 2) { throw new BadRequestException(); } return parts[1]; } else { return request.getParam("access_token"); } }
Example #2
Source File: SmallRyeGraphQLExecutionHandler.java From quarkus with Apache License 2.0 | 6 votes |
private void doHandle(final RoutingContext ctx) { if (currentIdentityAssociation != null) { currentIdentityAssociation.setIdentity(QuarkusHttpUser.getSecurityIdentity(ctx, null)); } HttpServerRequest request = ctx.request(); HttpServerResponse response = ctx.response(); response.headers().set(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); switch (request.method()) { case OPTIONS: handleOptions(response); break; case POST: handlePost(response, ctx); break; case GET: handleGet(response, ctx); break; default: response.setStatusCode(405).end(); break; } }
Example #3
Source File: BaseDl4JVerticalTest.java From konduit-serving with Apache License 2.0 | 6 votes |
@Override public Handler<HttpServerRequest> getRequest() { return req -> { req.bodyHandler(body -> { try { ClassifierOutput classifierOutput = ObjectMappers.json().readValue(body.toString(), ClassifierOutput.class); assertEquals(1, classifierOutput.getDecisions()[0]); } catch (IOException e) { e.printStackTrace(); } System.out.println("Finish body" + body); }); req.exceptionHandler(Throwable::printStackTrace); }; }
Example #4
Source File: Jukebox.java From vertx-in-action with MIT License | 6 votes |
private void downloadFile(AsyncFile file, HttpServerRequest request) { HttpServerResponse response = request.response(); response.setStatusCode(200) .putHeader("Content-Type", "audio/mpeg") .setChunked(true); file.handler(buffer -> { response.write(buffer); if (response.writeQueueFull()) { file.pause(); response.drainHandler(v -> file.resume()); } }); file.endHandler(v -> response.end()); }
Example #5
Source File: EncryptEdgeDispatcher.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
protected void onRequest(RoutingContext context) { HttpServerRequest httpServerRequest = context.request(); // queryUserId always success CompletableFuture<String> userIdFuture = queryUserId(httpServerRequest); queryHcr(httpServerRequest).thenCombine(userIdFuture, (hcr, userId) -> { // hcr and userId all success routeToBackend(context, hcr, userId); return null; }).whenComplete((v, e) -> { // failed to query hcr if (e != null) { context.response().end("failed to query hcr: " + e.getMessage()); return; } }); }
Example #6
Source File: X509AuthHandlerTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the handler returns the status code conveyed in a * failed Tenant service invocation in the response. * * @throws SSLPeerUnverifiedException if the client certificate cannot be validated. */ @Test public void testHandleFailsWithStatusCodeFromAuthProvider() throws SSLPeerUnverifiedException { // GIVEN an auth handler configured with an auth provider that // fails with a 503 error code during authentication final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE); when(clientAuth.validateClientCertificate(any(Certificate[].class), (SpanContext) any())).thenReturn(Future.failedFuture(error)); // WHEN trying to authenticate a request that contains a client certificate final EmptyCertificate clientCert = new EmptyCertificate("CN=device", "CN=tenant"); final SSLSession sslSession = mock(SSLSession.class); when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { clientCert }); final HttpServerRequest req = mock(HttpServerRequest.class); when(req.isSSL()).thenReturn(true); when(req.sslSession()).thenReturn(sslSession); final HttpServerResponse resp = mock(HttpServerResponse.class); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.get(TracingHandler.CURRENT_SPAN)).thenReturn(mock(Span.class)); when(ctx.request()).thenReturn(req); when(ctx.response()).thenReturn(resp); authHandler.handle(ctx); // THEN the request context is failed with the 503 error code verify(ctx).fail(error); }
Example #7
Source File: DefaultFailureHandlerTest.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the handler sets an empty response body for * a context that has failed with an exception that does not contain * a detail message. */ @Test public void testHandlerSucceedsForExceptionsWithoutMessage() { final HttpServerRequest request = mock(HttpServerRequest.class, Mockito.RETURNS_MOCKS); final HttpServerResponse response = mock(HttpServerResponse.class); when(response.ended()).thenReturn(false); final RoutingContext ctx = mock(RoutingContext.class); when(ctx.request()).thenReturn(request); when(ctx.response()).thenReturn(response); when(ctx.failed()).thenReturn(true); when(ctx.failure()).thenReturn(new IllegalStateException()); // no detail message final DefaultFailureHandler handler = new DefaultFailureHandler(); handler.handle(ctx); verify(response).setStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); verify(response, never()).write(any(Buffer.class)); verify(response).end(); }
Example #8
Source File: UrlPathItemTest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Before public void initStrBuilder() { accessLogEvent = new ServerAccessLogEvent(); routingContext = Mockito.mock(RoutingContext.class); finishEvent = Mockito.mock(InvocationFinishEvent.class); invocation = Mockito.mock(Invocation.class); serverRequest = Mockito.mock(HttpServerRequest.class); operationMeta = Mockito.mock(OperationMeta.class); schemaMeta = Mockito.mock(SchemaMeta.class); swagger = Mockito.mock(Swagger.class); restClientRequest = Mockito.mock(RestClientRequestImpl.class); clientRequest = Mockito.mock(HttpClientRequest.class); accessLogEvent.setRoutingContext(routingContext); strBuilder = new StringBuilder(); }
Example #9
Source File: LocalHostItemTest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Before public void initStrBuilder() { accessLogEvent = new ServerAccessLogEvent(); routingContext = Mockito.mock(RoutingContext.class); finishEvent = Mockito.mock(InvocationFinishEvent.class); serverRequest = Mockito.mock(HttpServerRequest.class); socketAddress = Mockito.mock(SocketAddress.class); invocation = Mockito.mock(Invocation.class); restClientRequest = Mockito.mock(RestClientRequestImpl.class); clientRequest = Mockito.mock(HttpClientRequest.class); connection = Mockito.mock(HttpConnection.class); Map<String, Object> handlerMap = new HashMap<>(); handlerMap.put(RestConst.INVOCATION_HANDLER_REQUESTCLIENT, restClientRequest); when(finishEvent.getInvocation()).thenReturn(invocation); when(invocation.getHandlerContext()).thenReturn(handlerMap); accessLogEvent.setRoutingContext(routingContext); strBuilder = new StringBuilder(); }
Example #10
Source File: WebSocketService.java From besu with Apache License 2.0 | 6 votes |
private Handler<HttpServerRequest> httpHandler() { final Router router = Router.router(vertx); // Verify Host header to avoid rebind attack. router.route().handler(checkAllowlistHostHeader()); if (authenticationService.isPresent()) { router.route("/login").handler(BodyHandler.create()); router .post("/login") .produces(APPLICATION_JSON) .handler(authenticationService.get()::handleLogin); } else { router .post("/login") .produces(APPLICATION_JSON) .handler(AuthenticationService::handleDisabledLogin); } router.route().handler(WebSocketService::handleHttpNotSupported); return router; }
Example #11
Source File: ContextFromVertx.java From wisdom with Apache License 2.0 | 6 votes |
/** * Creates a new context. * * @param accessor a structure containing the used services. * @param req the incoming HTTP Request. */ public ContextFromVertx(Vertx vertx, io.vertx.core.Context vertxContext, ServiceAccessor accessor, HttpServerRequest req) { id = ids.getAndIncrement(); services = accessor; request = new RequestFromVertx(req); this.vertx = vertx; flash = new FlashCookieImpl(accessor.getConfiguration()); session = new SessionCookieImpl(accessor.getCrypto(), accessor.getConfiguration()); flash.init(this); session.init(this); if (vertxContext == null) { throw new IllegalArgumentException("Creating a context from vert.x outside of an event loop"); } else { this.vertxContext = vertxContext; } }
Example #12
Source File: GossipApp.java From incubator-tuweni with Apache License 2.0 | 6 votes |
private void handleRPCRequest(HttpServerRequest httpServerRequest) { if (HttpMethod.POST.equals(httpServerRequest.method())) { if ("/publish".equals(httpServerRequest.path())) { httpServerRequest.bodyHandler(body -> { Bytes message = Bytes.wrapBuffer(body); outStream.println("Message to publish " + message.toHexString()); publish(message); httpServerRequest.response().setStatusCode(200).end(); }); } else { httpServerRequest.response().setStatusCode(404).end(); } } else { httpServerRequest.response().setStatusCode(405).end(); } }
Example #13
Source File: RequestProtocolAccessItem.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) { HttpServerRequest request = accessLogEvent.getRoutingContext().request(); if (null == request || null == request.version()) { builder.append(EMPTY_RESULT); return; } builder.append(getStringVersion(request.version())); }
Example #14
Source File: CorsHandlerImpl.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public void handle(RoutingContext context) { HttpServerRequest request = context.request(); HttpServerResponse response = context.response(); String origin = context.request().headers().get(ORIGIN); if (origin == null) { // Not a CORS request - we don't set any headers and just call the next handler context.next(); } else if (isValidOrigin(origin)) { String accessControlRequestMethod = request.headers().get(ACCESS_CONTROL_REQUEST_METHOD); if (request.method() == HttpMethod.OPTIONS && accessControlRequestMethod != null) { // Pre-flight request addCredentialsAndOriginHeader(response, origin); if (allowedMethodsString != null) { response.putHeader(ACCESS_CONTROL_ALLOW_METHODS, allowedMethodsString); } if (allowedHeadersString != null) { response.putHeader(ACCESS_CONTROL_ALLOW_HEADERS, allowedHeadersString); } if (maxAgeSeconds != null) { response.putHeader(ACCESS_CONTROL_MAX_AGE, maxAgeSeconds); } // according to MDC although the is no body the response should be OK response.setStatusCode(200).end(); } else { addCredentialsAndOriginHeader(response, origin); if (exposedHeadersString != null) { response.putHeader(ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString); } context.put(CORS_HANDLED_FLAG, true); context.next(); } } else { context .response() .setStatusMessage("CORS Rejected - Invalid origin"); context .fail(403); } }
Example #15
Source File: VertxVaadinServiceUT.java From vertx-vaadin with MIT License | 5 votes |
private String testLocation(String mountPoint, String pathInfo) { VertxVaadinService service = mock(VertxVaadinService.class); HttpServerRequest httpServerRequest = mock(HttpServerRequest.class); RoutingContext routingContext = mock(RoutingContext.class); when(routingContext.mountPoint()).thenReturn(mountPoint); when(routingContext.request()).thenReturn(httpServerRequest); VaadinRequest req = new VertxVaadinRequest(service, routingContext); when(httpServerRequest.path()).thenReturn(Optional.ofNullable(mountPoint).orElse("") + pathInfo); return VertxVaadinService.getContextRootRelativePath(req); }
Example #16
Source File: Jukebox.java From vertx-in-action with MIT License | 5 votes |
private void downloadFilePipe(AsyncFile file, HttpServerRequest request) { HttpServerResponse response = request.response(); response.setStatusCode(200) .putHeader("Content-Type", "audio/mpeg") .setChunked(true); file.pipeTo(response); }
Example #17
Source File: VertxUtil.java From quarkus with Apache License 2.0 | 5 votes |
public static MultivaluedMap<String, String> extractRequestHeaders(HttpServerRequest request) { Headers<String> requestHeaders = new Headers<String>(); for (Map.Entry<String, String> header : request.headers()) { requestHeaders.add(header.getKey(), header.getValue()); } return requestHeaders; }
Example #18
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Verifies that the adapter does not wait for a telemetry message being settled and accepted * by a downstream peer before responding with a 202 status to the device. */ @SuppressWarnings("unchecked") @Test public void testUploadTelemetryDoesNotWaitForAcceptedOutcome() { // GIVEN an adapter with a downstream telemetry consumer attached final Future<ProtonDelivery> outcome = Future.succeededFuture(mock(ProtonDelivery.class)); givenATelemetrySenderForOutcome(outcome); final HttpServer server = getHttpServer(false); final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes a telemetry message final Buffer payload = Buffer.buffer("some payload"); final HttpServerResponse response = mock(HttpServerResponse.class); final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class), response); when(ctx.addBodyEndHandler(any(Handler.class))).thenAnswer(invocation -> { final Handler<Void> handler = invocation.getArgument(0); handler.handle(null); return 0; }); adapter.uploadTelemetryMessage(ctx, "tenant", "device"); // THEN the device receives a 202 response immediately verify(response).setStatusCode(202); verify(response).end(); // and the message has been reported as processed verify(metrics).reportTelemetry( eq(MetricsTags.EndpointType.TELEMETRY), eq("tenant"), any(), eq(MetricsTags.ProcessingOutcome.FORWARDED), eq(MetricsTags.QoS.AT_MOST_ONCE), eq(payload.length()), eq(MetricsTags.TtdStatus.NONE), any()); }
Example #19
Source File: VertxReactorHandler.java From gravitee-gateway with Apache License 2.0 | 5 votes |
@Override public void handle(HttpServerRequest httpServerRequest) { Request request = new VertxHttpServerRequest(httpServerRequest); Response response = new VertxHttpServerResponse(httpServerRequest, request.metrics()); route(request, response); }
Example #20
Source File: AuthInterceptorTest.java From enmasse with Apache License 2.0 | 5 votes |
@Test public void testCertAuthorization() { SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("me", true); TokenReview tokenReview = new TokenReview("me", "", Collections.singleton("system:authenticated"), Map.of("custom-header", Collections.singletonList("customvalue")), true); when(mockAuthApi.performSubjectAccessReviewResource(eq(tokenReview), any(), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); when(mockRequestContext.getHeaderString("X-Remote-User")).thenReturn("me"); when(mockRequestContext.getHeaderString("X-Remote-Group")).thenReturn("system:authenticated"); MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); map.put("X-Remote-Extra-Custom-Header", Collections.singletonList("customvalue")); when(mockRequestContext.getHeaders()).thenReturn(map); HttpServerRequest request = mock(HttpServerRequest.class); HttpConnection connection = mock(HttpConnection.class); when(request.isSSL()).thenReturn(true); when(request.connection()).thenReturn(connection); handler.setRequest(request); handler.filter(mockRequestContext); ArgumentCaptor<SecurityContext> contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); SecurityContext context = contextCaptor.getValue(); assertThat(context.getAuthenticationScheme(), is("RBAC")); RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("me")); assertTrue(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "addressspaces", "enmasse.io"))); }
Example #21
Source File: RouterImpl.java From vertx-web with Apache License 2.0 | 5 votes |
@Override public void handle(HttpServerRequest request) { if (log.isTraceEnabled()) { log.trace("Router: " + System.identityHashCode(this) + " accepting request " + request.method() + " " + request.absoluteURI()); } new RoutingContextImpl(null, this, request, state.getRoutes()).next(); }
Example #22
Source File: TestHttpServerRequestUtils.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void testVertxServerRequestToHttpServletRequest(@Mocked RoutingContext context, @Mocked HttpServerRequest request) { HttpServerRequestWrapper wrapper = new HttpServerRequestWrapper(request); new Expectations() { { context.request(); result = wrapper; } }; VertxServerRequestToHttpServletRequest reqEx = new VertxServerRequestToHttpServletRequest(context, "abc"); Assert.assertEquals("abc", reqEx.getRequestURI()); }
Example #23
Source File: NewTokenProvider.java From rest.vertx with Apache License 2.0 | 5 votes |
@Override public Token provide(HttpServerRequest request) { String token = request.getHeader("X-Token"); if (token != null) { return new Token("***" + token + "***"); } return null; }
Example #24
Source File: Jukebox.java From vertx-in-action with MIT License | 5 votes |
private void httpHandler(HttpServerRequest request) { logger.info("{} '{}' {}", request.method(), request.path(), request.remoteAddress()); if ("/".equals(request.path())) { openAudioStream(request); return; } if (request.path().startsWith("/download/")) { String sanitizedPath = request.path().substring(10).replaceAll("/", ""); download(sanitizedPath, request); return; } request.response().setStatusCode(404).end(); }
Example #25
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
/** * Verifies that the adapter accepts a command response message with an empty body. */ @SuppressWarnings("unchecked") @Test public void testUploadEmptyCommandResponseSucceeds() { // GIVEN an adapter with a downstream application attached final CommandResponseSender sender = mock(CommandResponseSender.class); when(sender.sendCommandResponse(any(CommandResponse.class), (SpanContext) any())).thenReturn(Future.succeededFuture(mock(ProtonDelivery.class))); when(commandConsumerFactory.getCommandResponseSender(anyString(), anyString())).thenReturn(Future.succeededFuture(sender)); final HttpServer server = getHttpServer(false); final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes a command response with an empty payload final Buffer payload = null; final HttpServerResponse response = mock(HttpServerResponse.class); final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class), response); when(ctx.addBodyEndHandler(any(Handler.class))).thenAnswer(invocation -> { final Handler<Void> handler = invocation.getArgument(0); handler.handle(null); return 0; }); adapter.uploadCommandResponseMessage(ctx, "tenant", "device", CMD_REQ_ID, 200); // then it is forwarded successfully verify(response).setStatusCode(202); verify(response).end(); verify(metrics).reportCommand( eq(Direction.RESPONSE), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(0), any()); }
Example #26
Source File: RequestHelper.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
public static String getRemoteHost(final HttpServerRequest request) { if (request.headers().contains("X-Real-IP")) { return request.headers().get("X-Real-IP"); } else { return request.remoteAddress().host(); } }
Example #27
Source File: EchoServerVertx.java From apiman with Apache License 2.0 | 5 votes |
private String normaliseResource(HttpServerRequest req) { if (req.query() != null) { String[] normalisedQueryString = req.query().split("&"); Arrays.sort(normalisedQueryString); return req.path() + "?" + SimpleStringUtils.join("&", normalisedQueryString); } else { return req.path(); } }
Example #28
Source File: RouteState.java From vertx-web with Apache License 2.0 | 5 votes |
private void addPathParam(RoutingContext context, String name, String value) { HttpServerRequest request = context.request(); final String decodedValue = URIDecoder.decodeURIComponent(value, false); if (!request.params().contains(name)) { request.params().add(name, decodedValue); } context.pathParams().put(name, decodedValue); }
Example #29
Source File: HttpApiFactory.java From apiman with Apache License 2.0 | 5 votes |
public static ApiRequest buildRequest(HttpServerRequest req, boolean isTransportSecure) { ApiRequest apimanRequest = new ApiRequest(); apimanRequest.setApiKey(parseApiKey(req)); apimanRequest.setRemoteAddr(req.remoteAddress().host()); apimanRequest.setType(req.method().toString()); apimanRequest.setTransportSecure(isTransportSecure); multimapToMap(apimanRequest.getHeaders(), req.headers(), IGNORESET); multimapToMap(apimanRequest.getQueryParams(), req.params(), Collections.<String>emptySet()); parsePath(req, apimanRequest); return apimanRequest; }
Example #30
Source File: RestKiqrServerVerticle.java From kiqr with Apache License 2.0 | 5 votes |
private void addRouteForSessionQueries(Router router) { router.route(RestKiqrServerVerticle.BASE_ROUTE_SESSION + "/:key").handler(routingContext -> { HttpServerRequest request = routingContext.request(); String keySerde = request.getParam("keySerde"); String valueSerde = request.getParam("valueSerde"); String store = request.getParam("store"); byte[] key = Base64.getDecoder().decode(request.getParam("key")); if (keySerde == null || valueSerde == null) { routingContext.fail(400); } else { KeyBasedQuery query = new KeyBasedQuery(store, keySerde, key, valueSerde); vertx.eventBus().send(Config.SESSION_QUERY_FACADE_ADDRESS, query, new DeliveryOptions().setSendTimeout(TIMEOUT), reply -> { if (reply.succeeded()) { SessionQueryResponse body = (SessionQueryResponse) reply.result().body(); HttpServerResponse response = routingContext.response(); response .putHeader("content-type", "application/json") .end(Json.encode(body)); } else { forwardErrorCode(routingContext, reply); } }); } }); }