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

The following examples show how to use io.vertx.ext.web.RoutingContext#get() . These examples are extracted from open source projects. 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 Project: vertx-web   File: BaseTransport.java    License: 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 2
@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 3
Source Project: andesite-node   File: MemoryBodyHandler.java    License: 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 4
@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 Project: vertx-web   File: BodyHandlerImpl.java    License: 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 6
Source Project: quarkus   File: QuarkusHttpUser.java    License: 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 7
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 8
Source Project: gae   File: GaeBidHandler.java    License: 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 9
Source Project: hono   File: TracingHandler.java    License: 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 10
Source Project: xyz-hub   File: ApiParam.java    License: 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 11
Source Project: java-vertx-web   File: TracingHandler.java    License: 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 12
Source Project: vertx-web   File: AuthHandlerImpl.java    License: 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 13
@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 14
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 15
Source Project: joyqueue   File: PropertiesRender.java    License: 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 16
Source Project: joyqueue   File: OperatorBinder.java    License: 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 17
Source Project: nubes   File: DefaultErrorHandler.java    License: 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 18
Source Project: nubes   File: ContentTypeProcessor.java    License: Apache License 2.0 4 votes vote down vote up
public static String getContentType(RoutingContext context) {
  return context.get(BEST_CONTENT_TYPE);
}
 
Example 19
Source Project: nubes   File: FileResolver.java    License: Apache License 2.0 4 votes vote down vote up
static String getFileName(RoutingContext context) {
  return context.get(CONTEXT_FILE_NAME);
}
 
Example 20
private Span getRootSpan(final RoutingContext ctx) {
    final Object rootSpanObject = ctx.get(TracingHandler.CURRENT_SPAN);
    return rootSpanObject instanceof Span ? (Span) rootSpanObject : null;
}