io.vertx.ext.web.RoutingContext Java Examples
The following examples show how to use
io.vertx.ext.web.RoutingContext.
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: BasicAuthenticationMechanism.java From quarkus with Apache License 2.0 | 7 votes |
@Override public Uni<ChallengeData> getChallenge(RoutingContext context) { if (silent) { //if this is silent we only send a challenge if the request contained auth headers //otherwise we assume another method will send the challenge String authHeader = context.request().headers().get(HttpHeaderNames.AUTHORIZATION); if (authHeader == null) { return Uni.createFrom().optional(Optional.empty()); } } ChallengeData result = new ChallengeData( HttpResponseStatus.UNAUTHORIZED.code(), HttpHeaderNames.WWW_AUTHENTICATE, challenge); return Uni.createFrom().item(result); }
Example #2
Source File: AuthHandlerImpl.java From vertx-web with Apache License 2.0 | 6 votes |
private boolean handlePreflight(RoutingContext ctx) { final HttpServerRequest request = ctx.request(); // See: https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0 // Preflight requests should not be subject to security due to the reason UAs will remove the Authorization header if (request.method() == HttpMethod.OPTIONS) { // check if there is a access control request header final String accessControlRequestHeader = ctx.request().getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS); if (accessControlRequestHeader != null) { // lookup for the Authorization header for (String ctrlReq : accessControlRequestHeader.split(",")) { if (ctrlReq.equalsIgnoreCase("Authorization")) { // this request has auth in access control, so we can allow preflighs without authentication ctx.next(); return true; } } } } return false; }
Example #3
Source File: ResponseHeaderAttribute.java From quarkus with Apache License 2.0 | 6 votes |
@Override public String readAttribute(final RoutingContext exchange) { List<String> header = exchange.response().headers().getAll(responseHeader); if (header.isEmpty()) { return null; } else if (header.size() == 1) { return header.get(0); } StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < header.size(); ++i) { if (i != 0) { sb.append(", "); } sb.append(header.get(i)); } sb.append("]"); return sb.toString(); }
Example #4
Source File: TemplateEngineManager.java From nubes with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext context) { String tplDir = Utils.removeDots(config.getTplDir()); String tplFile = Utils.normalizePath(ViewResolver.getViewName(context)); TemplateEngine engine = fromViewName(tplDir + tplFile); if (engine == null) { LOG.error("No template handler found for " + tplDir + tplFile); context.fail(500); return; } engine.render(context, tplDir, tplFile, res -> { if (res.succeeded()) { context.response().putHeader(CONTENT_TYPE, "text/html").end(res.result()); } else { context.fail(res.cause()); } }); }
Example #5
Source File: VertxRestInvocationTest.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@Test public void testCreateInvocation() { new MockUp<RestProducerInvocation>() { /** * Mock this method to avoid error */ @Mock void createInvocation() { } }; VertxRestInvocation vertxRestInvocation = new VertxRestInvocation(); VertxServerRequestToHttpServletRequest requestEx = Mockito.mock(VertxServerRequestToHttpServletRequest.class); RoutingContext routingContext = Mockito.mock(RoutingContext.class); Invocation invocation = Mockito.mock(Invocation.class); Deencapsulation.setField( vertxRestInvocation, "requestEx", requestEx); Deencapsulation.setField( vertxRestInvocation, "invocation", invocation); Mockito.when(requestEx.getContext()).thenReturn(routingContext); Deencapsulation.invoke(vertxRestInvocation, "createInvocation"); Mockito.verify(routingContext, Mockito.times(1)).put(RestConst.REST_INVOCATION_CONTEXT, invocation); }
Example #6
Source File: FormBodyProcessorImpl.java From vertx-web with Apache License 2.0 | 6 votes |
@Override public Future<RequestParameter> process(RoutingContext requestContext) { try { MultiMap multiMap = requestContext.request().formAttributes(); JsonObject object = new JsonObject(); for (String key : multiMap.names()) { List<String> serialized = multiMap.getAll(key); Map.Entry<String, Object> parsed = parseField(key, serialized); if (parsed != null) object.put(parsed.getKey(), parsed.getValue()); } return valueValidator.validate(object).recover(err -> Future.failedFuture( BodyProcessorException.createValidationError(requestContext.parsedHeaders().contentType().value(), err) )); } catch (MalformedValueException e) { return Future.failedFuture(BodyProcessorException.createParsingError(requestContext.request().getHeader(HttpHeaders.CONTENT_TYPE), e)); } }
Example #7
Source File: TenantLoadingTest.java From raml-module-builder with Apache License 2.0 | 6 votes |
private void fakeHttpServerHandler(RoutingContext ctx) { ctx.response().setChunked(true); Buffer buffer = Buffer.buffer(); ctx.request().handler(buffer::appendBuffer); ctx.request().endHandler(x -> { if (ctx.request().method() == HttpMethod.PUT) { String path = ctx.request().path(); int idx = path.lastIndexOf('/'); if (idx != -1) { try { String id = URLDecoder.decode(path.substring(idx + 1), "UTF-8"); ids.add(id); } catch (UnsupportedEncodingException ex) { ctx.response().setStatusCode(400); return; } } ctx.response().setStatusCode(putStatus); } else if (ctx.request().method() == HttpMethod.POST) { ctx.response().setStatusCode(postStatus); } else { ctx.response().setStatusCode(405); } ctx.response().end(); }); }
Example #8
Source File: OidcIdentityProvider.java From quarkus with Apache License 2.0 | 6 votes |
@Override public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request, AuthenticationRequestContext context) { ContextAwareTokenCredential credential = (ContextAwareTokenCredential) request.getToken(); RoutingContext vertxContext = credential.getContext(); return Uni.createFrom().deferred(new Supplier<Uni<SecurityIdentity>>() { @Override public Uni<SecurityIdentity> get() { if (tenantResolver.isBlocking(vertxContext)) { return context.runBlocking(new Supplier<SecurityIdentity>() { @Override public SecurityIdentity get() { return authenticate(request, vertxContext).await().indefinitely(); } }); } return authenticate(request, vertxContext); } }); }
Example #9
Source File: ErrorHandlerImpl.java From vertx-web with Apache License 2.0 | 6 votes |
@Override public void handle(RoutingContext context) { HttpServerResponse response = context.response(); Throwable failure = context.failure(); int errorCode = context.statusCode(); String errorMessage = null; if (errorCode != -1) { context.response().setStatusCode(errorCode); errorMessage = context.response().getStatusMessage(); } else { errorCode = 500; if (displayExceptionDetails) { errorMessage = failure.getMessage(); } if (errorMessage == null) { errorMessage = "Internal Server Error"; } // no new lines are allowed in the status message response.setStatusMessage(errorMessage.replaceAll("\\r|\\n", " ")); } answerWithError(context, errorCode, errorMessage); }
Example #10
Source File: RequestHeaderAttribute.java From quarkus with Apache License 2.0 | 6 votes |
@Override public String readAttribute(final RoutingContext exchange) { List<String> header = exchange.request().headers().getAll(requestHeader); if (header.isEmpty()) { return null; } else if (header.size() == 1) { return header.get(0); } StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < header.size(); ++i) { if (i != 0) { sb.append(", "); } sb.append(header.get(i)); } sb.append("]"); return sb.toString(); }
Example #11
Source File: DelegatingDeviceManagementHttpEndpoint.java From hono with Eclipse Public License 2.0 | 6 votes |
private void doUpdateDevice(final RoutingContext ctx) { final Span span = TracingHelper.buildServerChildSpan( tracer, TracingHandler.serverSpanContext(ctx), SPAN_NAME_UPDATE_DEVICE, getClass().getSimpleName() ).start(); final Future<String> tenantId = getRequestParameter(ctx, PARAM_TENANT_ID, getPredicate(config.getTenantIdPattern(), false)); final Future<String> deviceId = getRequestParameter(ctx, PARAM_DEVICE_ID, getPredicate(config.getDeviceIdPattern(), false)); final Future<Device> device = fromPayload(ctx); CompositeFuture.all(tenantId, deviceId, device) .compose(ok -> { logger.debug("updating device [tenant: {}, device-id: {}]", tenantId.result(), deviceId.result()); final Optional<String> resourceVersion = Optional.ofNullable(ctx.get(KEY_RESOURCE_VERSION)); return getService().updateDevice(tenantId.result(), deviceId.result(), device.result(), resourceVersion, span); }) .onSuccess(operationResult -> writeResponse(ctx, operationResult, span)) .onFailure(t -> failRequest(ctx, t, span)) .onComplete(s -> span.finish()); }
Example #12
Source File: RestDeployModuleHandler.java From vertx-deploy-tools with Apache License 2.0 | 6 votes |
@Override public void handle(final RoutingContext context) { context.request().bodyHandler(buffer -> { DeployApplicationRequest deployRequest = HttpUtils.readPostData(buffer, DeployApplicationRequest.class, LogConstants.DEPLOY_REQUEST); if (deployRequest == null) { HttpUtils.respondBadRequest(context.request()); return; } LOG.info("[{} - {}]: Received deploy module {}", LogConstants.DEPLOY_REQUEST, deployRequest.getId().toString(), deployRequest.toString()); service.deployAsync(deployRequest) .doOnCompleted(() -> HttpUtils.respondOk(context.request())) .doOnError(t -> HttpUtils.respondFailed(context.request())); }); }
Example #13
Source File: RouteStateInterceptor.java From skywalking with Apache License 2.0 | 6 votes |
@Override @SuppressWarnings("unchecked") public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { RoutingContextImplBase routingContext = (RoutingContextImplBase) allArguments[0]; List<Handler<RoutingContext>> contextHandlers = (List<Handler<RoutingContext>>) objInst.getSkyWalkingDynamicField(); AtomicInteger currentContextIndex = (AtomicInteger) ((EnhancedInstance) routingContext).getSkyWalkingDynamicField(); int handlerContextIndex = currentContextIndex.get(); if (VertxContext.VERTX_VERSION >= 35 && contextHandlers.size() > 1) { currentContextIndex.getAndIncrement(); //3.5+ has possibility for multiple handlers } String contextName = contextHandlers.get(handlerContextIndex).getClass().getCanonicalName(); int lambdaOffset = contextName.indexOf("$$Lambda$"); if (lambdaOffset > 0) contextName = contextName.substring(0, lambdaOffset + 9); AbstractSpan span = ContextManager.createLocalSpan(String.format("%s.handle(RoutingContext)", contextName)); Object connection = ((EnhancedInstance) routingContext.request()).getSkyWalkingDynamicField(); VertxContext vertxContext = (VertxContext) ((EnhancedInstance) connection).getSkyWalkingDynamicField(); ContextManager.continued(vertxContext.getContextSnapshot()); span.setComponent(ComponentsDefine.VERTX); SpanLayer.asHttp(span); }
Example #14
Source File: ActionsHandler.java From hawkular-alerts with Apache License 2.0 | 6 votes |
@DocPath(method = GET, path = "/plugin/{actionPlugin}", name = "Find all action ids of an specific action plugin.") @DocParameters(value = { @DocParameter(name = "actionPlugin", required = true, path = true, description = "Action plugin to filter query for action ids.") }) @DocResponses(value = { @DocResponse(code = 200, message = "Successfully fetched list of action ids.", response = ApiDeleted.class), @DocResponse(code = 500, message = "Internal server error.", response = ApiError.class) }) public void findActionIdsByPlugin(RoutingContext routing) { routing.vertx() .executeBlocking(future -> { String tenantId = ResponseUtil.checkTenant(routing); String actionPlugin = routing.request().getParam("actionPlugin"); try { Collection<String> actions = definitionsService.getActionDefinitionIds(tenantId, actionPlugin); log.debugf("Actions: %s", actions); future.complete(actions); } catch (Exception e) { log.errorf("Error querying actions ids for tenantId %s and actionPlugin %s. Reason: %s", tenantId, actionPlugin, e.toString()); throw new ResponseUtil.InternalServerException(e.toString()); } }, res -> ResponseUtil.result(routing, res)); }
Example #15
Source File: BaseTransport.java From vertx-web with Apache License 2.0 | 6 votes |
static Handler<RoutingContext> createCORSOptionsHandler(SockJSHandlerOptions options, String methods) { return rc -> { if (log.isTraceEnabled()) log.trace("In CORS options handler"); rc.response().putHeader(CACHE_CONTROL, "public,max-age=31536000"); long oneYearSeconds = 365 * 24 * 60 * 60; long oneYearms = oneYearSeconds * 1000; String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(System.currentTimeMillis() + oneYearms)); rc.response() .putHeader(EXPIRES, expires) .putHeader(ACCESS_CONTROL_ALLOW_METHODS, methods) .putHeader(ACCESS_CONTROL_MAX_AGE, String.valueOf(oneYearSeconds)); setCORS(rc); setJSESSIONID(options, rc); rc.response().setStatusCode(204); rc.response().end(); }; }
Example #16
Source File: WebHelper.java From nassh-relay with GNU General Public License v2.0 | 6 votes |
public static AuthSession validateCookie(final RoutingContext context) { final Cookie cookie = context.getCookie(Constants.SESSIONCOOKIE); if (cookie == null) { return null; } final UUID sessioncookie = UUID.fromString(cookie.getValue()); final AuthSession session = AuthSessionManager.getSession(sessioncookie); if (session == null) { return null; } final String id = session.get("id"); if (id != null) { return session; } return null; }
Example #17
Source File: LoraProtocolAdapterTest.java From hono with Eclipse Public License 2.0 | 5 votes |
private LoraProvider getLoraProviderMock(final LoraMessage message) { final LoraProvider provider = mock(LoraProvider.class); when(provider.getProviderName()).thenReturn(TEST_PROVIDER); when(provider.pathPrefix()).thenReturn("/bumlux"); when(provider.getMessage(any(RoutingContext.class))).thenReturn(message); return provider; }
Example #18
Source File: ProbeHandlers.java From weld-vertx with Apache License 2.0 | 5 votes |
static void handleResource(RoutingContext ctx, String resourceName) { String contentType = detectContentType(resourceName); setHeaders(ctx.response(), contentType); if (isCachableContentType(contentType)) { // Set Cache-Control header - 24 hours ctx.response().putHeader("Cache-Control", "max-age=86400"); } if (isTextBasedContenType(contentType)) { String content = IOUtils.getResourceAsString(resourceName); if (content == null) { ctx.response().setStatusCode(404).end(); return; } content = content.replace("${contextPath}", BASE + "/"); ctx.response().end(content); } else { Buffer buffer = Buffer.buffer(); if (IOUtils.writeResource(resourceName, buffer)) { ctx.response().end(buffer); } else { ctx.response().setStatusCode(404).end(); } } }
Example #19
Source File: AdminApi.java From xyz-hub with Apache License 2.0 | 5 votes |
private void onMessage(final RoutingContext context) { try { AdminAuthorization.authorizeAdminMessaging(context); messageBroker.receiveRawMessage(context.getBody().getBytes()); context.response().setStatusCode(NO_CONTENT.code()) .putHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON) .end(); } catch (Exception e) { sendErrorResponse(context, e); } }
Example #20
Source File: RouterFactoryIntegrationTest.java From vertx-web with Apache License 2.0 | 5 votes |
private Future<Void> startSecuredFileServer(Vertx vertx, VertxTestContext testContext) { Router router = Router.router(vertx); router.route() .handler((RoutingContext ctx) -> { if (ctx.request().getHeader("Authorization") == null) ctx.fail(HttpResponseStatus.FORBIDDEN.code()); else ctx.next(); }) .handler(StaticHandler.create("src/test/resources")); return testContext.assertComplete( vertx.createHttpServer() .requestHandler(router) .listen(9001) .mapEmpty() ); }
Example #21
Source File: TransactionFactory.java From ethsigner with Apache License 2.0 | 5 votes |
public Transaction createTransaction(final RoutingContext context, final JsonRpcRequest request) { final String method = request.getMethod().toLowerCase(); final VertxNonceRequestTransmitter nonceRequestTransmitter = nonceRequestTransmitterFactory.create(context.request().headers()); switch (method) { case "eth_sendtransaction": return createEthTransaction(request, nonceRequestTransmitter); case "eea_sendtransaction": return createEeaTransaction(request, nonceRequestTransmitter); default: throw new IllegalStateException("Unknown send transaction method " + method); } }
Example #22
Source File: StaticHandlerImpl.java From vertx-web with Apache License 2.0 | 5 votes |
private void sendDirectory(RoutingContext context, String path, String file) { // in order to keep caches in a valid state we need to assert that // the user is requesting a directory (ends with /) if (!path.endsWith("/")) { context.response() .putHeader(HttpHeaders.LOCATION, path + "/") .setStatusCode(301) .end(); return; } if (directoryListing) { sendDirectoryListing(file, context); } else if (indexPage != null) { // send index page String indexPath; if (indexPage.startsWith("/")) { indexPath = path + indexPage.substring(1); } else { indexPath = path + indexPage; } // recursive call sendStatic(context, indexPath); } else { // Directory listing denied context.fail(FORBIDDEN.code()); } }
Example #23
Source File: FormParameterExtractor.java From vertx-swagger with Apache License 2.0 | 5 votes |
@Override public Object extract(String name, Parameter parameter, RoutingContext context) { FormParameter formParam = (FormParameter) parameter; if ("file".equals(formParam.getType())) { for (FileUpload file : context.fileUploads()) { if (file.name().equals(name)) { return file.uploadedFileName(); } } if(formParam.getRequired()) throw new IllegalArgumentException("Missing required parameter: " + name); return null; } else return this.extract(name, parameter, context.request().formAttributes()); }
Example #24
Source File: RestHandler.java From vxms with Apache License 2.0 | 5 votes |
/** * The constructor initialize the Rest handler * * @param methodId the method identifier * @param context the vertx routing context * @param vxmsShared the vxmsShared instance, containing the Vertx instance and other shared * objects per instance * @param failure the failure thrown while task execution or messaging * @param errorMethodHandler the error-method handler */ public RestHandler( String methodId, RoutingContext context, VxmsShared vxmsShared, Throwable failure, Consumer<Throwable> errorMethodHandler) { this.methodId = methodId; this.context = context; this.vxmsShared = vxmsShared; this.failure = failure; this.errorMethodHandler = errorMethodHandler; }
Example #25
Source File: RouterFactorySecurityTest.java From vertx-web with Apache License 2.0 | 5 votes |
private AuthenticationHandler mockFailingAuthHandler(Handler<RoutingContext> mockHandler) { return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) { @Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) { mockHandler.handle(context); handler.handle(Future.failedFuture(new HttpStatusException(401))); } }; }
Example #26
Source File: FeatureTask.java From xyz-hub with Apache License 2.0 | 5 votes |
private FeatureTask(T event, RoutingContext context, ApiResponseType responseType, boolean skipCache) { super(event, context, responseType, skipCache); event.setStreamId(getMarker().getName()); if (context.pathParam(ApiParam.Path.SPACE_ID) != null) { event.setSpace(context.pathParam(ApiParam.Path.SPACE_ID)); } }
Example #27
Source File: SockJSPushHandler.java From vertx-vaadin with MIT License | 5 votes |
private void initSocket(SockJSSocket sockJSSocket, RoutingContext routingContext, PushSocket socket) { sockJSSocket.handler(data -> sessionHandler.handle( new SockJSRoutingContext(routingContext, rc -> onMessage(new PushEvent(socket, rc, data))) )); sockJSSocket.endHandler(unused -> sessionHandler.handle( new SockJSRoutingContext(routingContext, rc -> onDisconnect(new PushEvent(socket, rc, null))) )); sockJSSocket.exceptionHandler(t -> sessionHandler.handle( new SockJSRoutingContext(routingContext, rc -> onError(new PushEvent(socket, routingContext, null), t)) )); }
Example #28
Source File: GaeAuthHandler.java From gae with MIT License | 5 votes |
@Override public void handle(RoutingContext ctx) { GaeException e = doAuth(ctx); if (null != e) { ctx.put(ContextConst.EXCEPTION, e); ctx.fail(401); } }
Example #29
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 #30
Source File: RouteAuthorizationTest.java From rest.vertx with Apache License 2.0 | 5 votes |
private static Handler<RoutingContext> getUserHandler() { return context -> { // read header ... if present ... create user with given value String token = context.request().getHeader("X-Token"); // set user ... if (token != null) { context.setUser(new SimulatedUser(token)); } context.next(); }; }