Java Code Examples for io.vertx.ext.web.RoutingContext#get()

The following examples show how to use io.vertx.ext.web.RoutingContext#get() . 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: TestVertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerErrorDataWithNormal(@Mocked RoutingContext context) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  Exception e = new Exception();
  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(edde, edde);
      context.response();
      result = response;
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertSame(edde, this.throwable);
  Assert.assertTrue(response.responseClosed);
}
 
Example 2
Source File: QuarkusHttpUser.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the current user from the routing context. If an IPM is provided this method will return the anonymous
 * identity if there is no active user, otherwise the Uni will resolve to null if there is no user.
 */
public static Uni<SecurityIdentity> getSecurityIdentity(RoutingContext routingContext,
        IdentityProviderManager identityProviderManager) {
    Uni<SecurityIdentity> deferred = routingContext.get(DEFERRED_IDENTITY_KEY);
    if (deferred != null) {
        return deferred;
    }
    QuarkusHttpUser existing = (QuarkusHttpUser) routingContext.user();
    if (existing != null) {
        return Uni.createFrom().item(existing.getSecurityIdentity());
    }
    if (identityProviderManager != null) {
        return identityProviderManager.authenticate(AnonymousAuthenticationRequest.INSTANCE);
    }
    return Uni.createFrom().nullItem();
}
 
Example 3
Source File: BodyHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@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();
  }
}
 
Example 4
Source File: TestVertxRestDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerWithNoExceptionAndStatusCodeIsNotSet(@Mocked RoutingContext context) {
  MockHttpServerResponse response = new MockHttpServerResponse();
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = null;
      context.failure();
      returns(null, null);
      context.response();
      result = response;
      context.statusCode();
      result = Status.OK.getStatusCode();
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertThat(response.responseHeader, Matchers.hasEntry(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD));
  Assert.assertThat(response.responseStatusCode, Matchers.is(Status.INTERNAL_SERVER_ERROR.getStatusCode()));
  Assert.assertThat(response.responseStatusMessage, Matchers.is(Status.INTERNAL_SERVER_ERROR.getReasonPhrase()));
  Assert.assertThat(response.responseChunk,
      Matchers.is("{\"message\":\"" + Status.INTERNAL_SERVER_ERROR.getReasonPhrase() + "\"}"));
  Assert.assertTrue(response.responseEnded);
}
 
Example 5
Source File: MemoryBodyHandler.java    From andesite-node with MIT License 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    HttpServerRequest request = context.request();
    if(request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) {
        context.next();
        return;
    }
    if(context.get(BODY_HANDLED) != null) {
        context.next();
    } else {
        ReadHandler h = new ReadHandler(context, maxSize);
        request.handler(h);
        request.endHandler(__ -> h.onEnd());
        context.put(BODY_HANDLED, true);
    }
}
 
Example 6
Source File: BaseTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
static void setCORS(RoutingContext rc) {
  if (rc.get(CorsHandlerImpl.CORS_HANDLED_FLAG) == null || !((boolean)rc.get(CorsHandlerImpl.CORS_HANDLED_FLAG))) {
    HttpServerRequest req = rc.request();
    String origin = req.getHeader(ORIGIN);
    if (origin == null) {
      origin = "*";
    }
    req.response().headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    if ("*".equals(origin)) {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "false");
    } else {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
    String hdr = req.headers().get(ACCESS_CONTROL_REQUEST_HEADERS);
    if (hdr != null) {
      req.response().headers().set(ACCESS_CONTROL_ALLOW_HEADERS, hdr);
    }
  }
}
 
Example 7
Source File: TracingHandler.java    From java-vertx-web with Apache License 2.0 5 votes vote down vote up
protected void handlerFailure(RoutingContext routingContext) {
    Object object = routingContext.get(CURRENT_SPAN);
    if (object instanceof Span) {
        final Span span = (Span)object;
        routingContext.addBodyEndHandler(event -> decorators.forEach(spanDecorator ->
                spanDecorator.onFailure(routingContext.failure(), routingContext.response(), span)));
    }

    routingContext.next();
}
 
Example 8
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private AuthenticationProvider getAuthProvider(RoutingContext ctx) {
  try {
    AuthenticationProvider 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;
}
 
Example 9
Source File: RestBodyHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  HttpServerRequest request = context.request();
  if (request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) {
    context.next();
    return;
  }

  Boolean bypass = context.get(BYPASS_BODY_HANDLER);
  if (Boolean.TRUE.equals(bypass)) {
    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();
  }
}
 
Example 10
Source File: HttpOpenApiOperation.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
protected String logResponseMessage(RoutingContext routingContext) {
    int requestId = routingContext.get("request-id");
    StringBuilder sb = new StringBuilder();
    if (log.isInfoEnabled()) {
        sb.append("[").append(requestId).append("] ").append(operationId.name())
            .append(" Response: ")
            .append(" statusCode = ").append(routingContext.response().getStatusCode())
            .append(", message = ").append(routingContext.response().getStatusMessage());

        if (log.isDebugEnabled()) {
            sb.append(", headers = ").append(routingContext.response().headers());
        }
    }
    return sb.toString();
}
 
Example 11
Source File: RouteToEBServiceHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private JsonObject buildPayload(RoutingContext context) {
  JsonObject params = context.get("parsedParameters") != null ? ((RequestParameters)context.get("parsedParameters")).toJson() : null;
  return new JsonObject().put("context", new ServiceRequest(
    params,
    context.request().headers(),
    (context.user() != null) ? context.user().principal() : null,
    (this.extraPayloadMapper != null) ? this.extraPayloadMapper.apply(context) : null
  ).toJson());
}
 
Example 12
Source File: PropertiesRender.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void render(final RoutingContext context) {
    //获取结果
    Response result = context.get(Command.RESULT);
    HttpServerResponse response = context.response();
    response.putHeader(CONTENT_TYPE, APPLICATION_PROPERTIES);
    if (result != null && result.getCode() != Response.HTTP_OK) {
        //异常
        response.setStatusCode(result.getStatus()).end(result.getMessage());
    } else {
        response.end();
    }
}
 
Example 13
Source File: OperatorBinder.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public boolean bind(final Context context) throws ReflectionException {
    if (context == null) {
        return false;
    }
    Object obj = context.getSource();
    if (!(obj instanceof RoutingContext)) {
        return false;
    }
    RoutingContext ctx = (RoutingContext) obj;
    Application application = ctx.get(Constants.APPLICATION);
    User session = ctx.get(Constants.USER_KEY);
    Identity identity = session != null ? new Identity(session) : (application != null ? application.getOwner() : null);
    return context.bind(identity);
}
 
Example 14
Source File: ApiParam.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the parsed tags parameter
 */
static PropertiesQuery getPropertiesQuery(RoutingContext context) {
  PropertiesQuery propertyQuery = context.get("propertyQuery");
  if (propertyQuery == null) {
    propertyQuery = parsePropertiesQuery(context.request().query());
    context.put("propertyQuery", propertyQuery);
  }
  return propertyQuery;
}
 
Example 15
Source File: TracingHandler.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Handles a failed HTTP request.
 *
 * @param routingContext The routing context for the request.
 */
protected void handlerFailure(final RoutingContext routingContext) {
    final Object object = routingContext.get(CURRENT_SPAN);
    if (object instanceof Span) {
        final Span span = (Span) object;
        routingContext.addBodyEndHandler(event -> decorators.forEach(spanDecorator ->
                spanDecorator.onFailure(routingContext.failure(), routingContext.response(), span)));
    }

    routingContext.next();
}
 
Example 16
Source File: DefaultErrorHandler.java    From nubes with Apache License 2.0 5 votes vote down vote up
private void handleHttpError(RoutingContext context, HttpServerResponse response, PayloadMarshaller marshaller) {
  final int status = context.statusCode();
  response.setStatusCode(status);
  String msg = errorMessages.getOrDefault(status, "Internal server error");
  if (context.get(ERROR_DETAILS) != null) {
    msg = context.get(ERROR_DETAILS);
  }
  if (marshaller != null) {
    response.end(marshaller.marshallHttpStatus(status, msg));
  } else {
    if (!response.ended()) {
      response.end(msg);
    }
  }
}
 
Example 17
Source File: GaeBidHandler.java    From gae with MIT License 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
    BidRequest request = ctx.get(ContextConst.REQUEST);
    long start = System.currentTimeMillis();

    List<Future> futList = buildAsyncTask(ctx, request);
    composeResultAndResponse(ctx, request, futList, start);
}
 
Example 18
Source File: FileResolver.java    From nubes with Apache License 2.0 4 votes vote down vote up
static String getFileName(RoutingContext context) {
  return context.get(CONTEXT_FILE_NAME);
}
 
Example 19
Source File: ContentTypeProcessor.java    From nubes with Apache License 2.0 4 votes vote down vote up
public static String getContentType(RoutingContext context) {
  return context.get(BEST_CONTENT_TYPE);
}
 
Example 20
Source File: AbstractVertxBasedHttpProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Span getRootSpan(final RoutingContext ctx) {
    final Object rootSpanObject = ctx.get(TracingHandler.CURRENT_SPAN);
    return rootSpanObject instanceof Span ? (Span) rootSpanObject : null;
}