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

The following examples show how to use io.vertx.ext.web.RoutingContext#put() . 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
private void handleMethodReturn(RoutingContext routingContext, T returned) {
  final boolean contentTypeSet = routingContext.get(ContentTypeProcessor.BEST_CONTENT_TYPE) != null;
  if (returnHandler != null) {
    returnHandler.accept(routingContext, returned);
  } else if (hasNext && contentTypeSet) {
    // try to set as Payload
    Payload<Object> payload = routingContext.get(Payload.DATA_ATTR);
    if (payload == null) {
      payload = new Payload<>();
      routingContext.put(Payload.DATA_ATTR, payload);
    }
    payload.set(returned);
  } else if (returned instanceof String) {
    routingContext.response().end((String) returned);
  }
}
 
Example 2
@Override
public void handle(RoutingContext ctx) {
  final String tenant = tenantExtractor.apply(ctx);
  final Handler<RoutingContext> handler =
    tenant == null ?
      defaultHandler :
      handlerMap.getOrDefault(tenant, defaultHandler);

  if (handler != null) {
    // there's a handler for this tenant and the name is default it we're
    // falling back to the default handler
    ctx.put(contextKey, handler == defaultHandler ? "default" : tenant);
    // continue as usual
    handler.handle(ctx);
  } else {
    // no handler found, this handle is not applicable
    // continue with the chain
    ctx.next();
  }
}
 
Example 3
protected void onRequest(RoutingContext context) {
  if (transport == null) {
    transport = SCBEngine.getInstance().getTransportManager().findTransport(Const.RESTFUL);
    microserviceMeta = SCBEngine.getInstance().getProducerMicroserviceMeta();
  }
  HttpServletRequestEx requestEx = new VertxServerRequestToHttpServletRequest(context);
  HttpServletResponseEx responseEx = new VertxServerResponseToHttpServletResponse(context.response());

  if (SCBEngine.getInstance().isFilterChainEnabled()) {
    InvocationCreator creator = new RestVertxProducerInvocationCreator(context,
        microserviceMeta, transport.getEndpoint(),
        requestEx, responseEx);
    new RestProducerInvocationFlow(creator, requestEx, responseEx)
        .run();
    return;
  }

  VertxRestInvocation vertxRestInvocation = new VertxRestInvocation();
  context.put(RestConst.REST_PRODUCER_INVOCATION, vertxRestInvocation);
  vertxRestInvocation.invoke(transport, requestEx, responseEx, httpServerFilters);
}
 
Example 4
@Override
protected void validate(final RoutingContext context, final RequestParameter parameter) {
    Application application = context.get(Constants.APPLICATION);
    //appUserId参数
    Long appUserId = parameter.query().getLong(Constants.APP_USER_ID);
    //userId参数
    Long userId = parameter.query().getLong(Constants.USER_ID);
    ApplicationUser user = appUserId != null ? userService.findAppUserById(appUserId) :
            (userId != null && application != null ? userService.findAppUserByAppIdAndUserId(application.getId(), userId) : null);
    if (application == null) {
        throw new ConfigException(ErrorCode.ApplicationNotExists);
    } else if (user == null) {
        throw new ConfigException(ErrorCode.AppUserNotExists);
    } else if (user.getApplication().getId() != application.getId()) {
        throw new ConfigException(ErrorCode.NoPrivilege);
    }
    context.put(Constants.APP_USER, user);

}
 
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: nubes   File: LocaleHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  Locale loc = localeResolverRegistry.resolve(context);
  if (loc != null) {
    context.put(LocaleParamInjector.LOCALE_ATTR, loc.toLanguageTag());
    context.response().headers().add(HttpHeaders.CONTENT_LANGUAGE, loc.toLanguageTag());
  }
  context.next();
}
 
Example 7
Source Project: xyz-hub   File: Api.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the access log object for this request.
 *
 * @param context the routing context.
 * @return the access log object
 */
public static AccessLog getAccessLog(RoutingContext context) {
  if (context == null) {
    return null;
  }
  AccessLog accessLog = context.get(ACCESS_LOG);
  if (accessLog == null) {
    accessLog = new AccessLog();
    context.put(ACCESS_LOG, accessLog);
  }
  return accessLog;
}
 
Example 8
Source Project: xyz-hub   File: Api.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the log marker for the request.
 *
 * @return the marker or null, if no marker was found.
 */
public static JWTPayload getJWT(RoutingContext context) {
  if (context == null) {
    return null;
  }
  JWTPayload payload = context.get(JWT);
  if (payload == null && context.user() != null) {
    payload = Json.mapper.convertValue(context.user().principal(), JWTPayload.class);
    context.put(JWT, payload);
  }

  return payload;
}
 
Example 9
@Override
public void handle(RoutingContext rct) {
	String result = resultFormat.replace("$(val)", Long.toString(System.currentTimeMillis()));
	if (isNext) {
		rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));// 告诉后置处理器当前操作成功执行
		rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(HttpHeaderConstant.CONTENT_TYPE,
				contentType);
		rct.next();
	} else {
		if (!rct.response().ended()) {
			rct.response().putHeader(HttpHeaderConstant.SERVER, VxApiGatewayAttribute.FULL_NAME)
					.putHeader(HttpHeaderConstant.CONTENT_TYPE, contentType).end(result);
		}
	}
}
 
Example 10
Source Project: xyz-hub   File: ApiParam.java    License: Apache License 2.0 5 votes vote down vote up
static Map<String, Object> getAdditionalParams(RoutingContext context, String type) throws Exception{
  Map<String, Object> clusteringParams = context.get(type);

  if (clusteringParams == null) {
    clusteringParams = parseAdditionalParams(context.request().query(), type);
    context.put(type, clusteringParams);
  }
  return clusteringParams;
}
 
Example 11
@Override
protected void validate(final RoutingContext context, final Parameters.RequestParameter parameter) {
    Parameter query = parameter.query();
    String value = query.getString(Constants.APP_ID);
    value = value == null ? query.getString(Constants.APP_CODE) : value;
    value = value == null ? query.getString(Constants.ID) : value;
    Application application = context.get(Constants.APPLICATION);
    if (application != null) {
        //有认证的上下文
        if (application.getCode().equals(value)
                || String.valueOf(application.getId()).equals(value)) {
            //和上下文一致
            return;
        }
        //越权访问
        throw new ConfigException(ErrorCode.NoPrivilege);
    }
    //没有认证上下文场景,通过ID或Code加载应用
    if (Character.isDigit(value.charAt(0))) {
        //可能是ID
        try {
            application = applicationService.findById(Long.parseLong(value));
        } catch (NumberFormatException e) {
        }
    }
    if (application == null) {
        if (Identifier.isIdentifier(value)) {
            //根据code查询
            application = applicationService.findByCode(value);
            if (application == null) {
                throw new ConfigException(ErrorCode.ApplicationNotExists);
            }
        } else {
            throw new ConfigException(ErrorCode.ApplicationNotExists);
        }
    }
    context.put(Constants.APPLICATION, application);
}
 
Example 12
Source Project: nubes   File: DefaultErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void renderViewError(String tpl, RoutingContext context, Throwable cause) {
  HttpServerResponse response = context.response();
  if (tpl != null) {
    context.put("error", cause);
    if (tpl.endsWith(".html")) {
      response.sendFile(tpl);
      return;
    }
    if (config.isDisplayErrors()) {
      context.put("stackTrace", StackTracePrinter.asHtml(new StringBuilder(), cause).toString());
    }

    String fileName = Paths.get(tpl).getFileName().toString();
    String path = tpl.replace(fileName, "");

    templManager.fromViewName(tpl).render(context, fileName, path, res -> {
      if (res.succeeded()) {
        response.end(res.result());
      } else {
        LOG.error("Could not read error template : " + tpl, res.cause());
        response.end(errorMessages.get(500));
      }
    });
  } else {
    response.end(cause.getMessage());
  }
}
 
Example 13
@Override
protected void validate(RoutingContext context, Parameters.RequestParameter parameter) {
    Parameter header = parameter.header();
    String appCode = header.getString(Constants.APPLICATION);
    if (appCode == null || appCode.isEmpty()) {
        throw new ConfigException(ErrorCode.BadRequest, "请求头没有应用代码");
    }
    Application application = applicationService.findByCode(appCode);
    if (application == null) {
        throw new ConfigException(ErrorCode.ApplicationNotExists);
    }
    context.put(Constants.APPLICATION, application);
}
 
Example 14
Source Project: nubes   File: ViewResolver.java    License: Apache License 2.0 4 votes vote down vote up
static void resolve(RoutingContext context, String viewName) {
  context.put(CONTEXT_TPL_NAME, viewName);
}
 
Example 15
Source Project: vertx-web   File: BaseValidationHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
  try {
    RequestParametersImpl parsedParameters = new RequestParametersImpl();

    parsedParameters.setPathParameters(validatePathParams(routingContext));
    parsedParameters.setQueryParameters(validateQueryParams(routingContext));
    parsedParameters.setHeaderParameters(validateHeaderParams(routingContext));
    parsedParameters.setCookieParameters(validateCookieParams(routingContext));

    //Run custom validators
    for (CustomValidator customValidator : customValidators) {
      customValidator.validate(routingContext);
    }

    String contentType = routingContext.request().getHeader(HttpHeaders.CONTENT_TYPE);
    if (contentType != null && contentType.length() != 0) {
      boolean isMultipart = contentType.contains("multipart/form-data");

      if (multipartFileRules.size() != 0 && !isMultipart) {
        throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType,
          "multipart/form-data");
      }
      if (contentType.contains("application/x-www-form-urlencoded")) {
        parsedParameters.setFormParameters(validateFormParams(routingContext));
      } else if (isMultipart) {
        parsedParameters.setFormParameters(validateFormParams(routingContext));
        validateFileUpload(routingContext);
      } else if (Utils.isJsonContentType(contentType) || Utils.isXMLContentType(contentType)) {
        parsedParameters.setBody(validateEntireBody(routingContext));
      } else if (bodyRequired && !checkContentType(contentType)) {
        throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType, null);
      } // If content type is valid or body is not required, do nothing!
    } else if (bodyRequired) {
      throw ValidationException.ValidationExceptionFactory.generateWrongContentTypeExpected(contentType, null);
    }

    if (routingContext.data().containsKey("parsedParameters")) {
      ((RequestParametersImpl)routingContext.get("parsedParameters")).merge(parsedParameters);
    } else {
      routingContext.put("parsedParameters", parsedParameters);
    }
    routingContext.next();

  } catch (ValidationException e) {
    routingContext.fail(400, e);
  }
}
 
Example 16
Source Project: joyqueue   File: GetLoginUserHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    context.put(Command.RESULT, Responses.success(context.get(Constants.USER_KEY)));
    LocalSession.getSession().setUser(context.get(Constants.USER_KEY));
    context.next();
}
 
Example 17
Source Project: nubes   File: FileResolver.java    License: Apache License 2.0 4 votes vote down vote up
static void resolve(RoutingContext context, String fileName) {
  context.put(CONTEXT_FILE_NAME, fileName);
}
 
Example 18
Source Project: vertx-web   File: CSRFHandlerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {

  if (nagHttps) {
    String uri = ctx.request().absoluteURI();
    if (uri != null && !uri.startsWith("https:")) {
      log.trace("Using session cookies without https could make you susceptible to session hijacking: " + uri);
    }
  }

  HttpMethod method = ctx.request().method();
  Session session = ctx.session();

  // if we're being strict with the origin
  // ensure that they are always valid
  if (!isValidOrigin(ctx)) {
    ctx.fail(403);
    return;
  }

  switch (method.name()) {
    case "GET":
      final String token;

      if (session == null) {
        // if there's no session to store values, tokens are issued on every request
        token = generateAndStoreToken(ctx);
      } else {
        // get the token from the session, this also considers the fact
        // that the token might be invalid as it was issued for a previous session id
        // session id's change on session upgrades (unauthenticated -> authenticated; role change; etc...)
        String sessionToken = getTokenFromSession(ctx);
        // when there's no token in the session, then we behave just like when there is no session
        // create a new token, but we also store it in the session for the next runs
        if (sessionToken == null) {
          token = generateAndStoreToken(ctx);
          // storing will include the session id too. The reason is that if a session is upgraded
          // we don't want to allow the token to be valid anymore
          session.put(headerName, session.id() + "/" + token);
        } else {
          String[] parts = sessionToken.split("\\.");
          final long ts = parseLong(parts[1]);

          if (ts == -1) {
            // fallback as the token is expired
            token = generateAndStoreToken(ctx);
          } else {
            if (!(System.currentTimeMillis() > ts + timeout)) {
              // we're still on the same session, no need to regenerate the token
              // also note that the token isn't expired, so it can be reused
              token = sessionToken;
              // in this case specifically we don't issue the token as it is unchanged
              // the user agent still has it from the previous interaction.
            } else {
              // fallback as the token is expired
              token = generateAndStoreToken(ctx);
            }
          }
        }
      }
      // put the token in the context for users who prefer to render the token directly on the HTML
      ctx.put(headerName, token);
      ctx.next();
      break;
    case "POST":
    case "PUT":
    case "DELETE":
    case "PATCH":
      if (isValidRequest(ctx)) {
        // it matches, so refresh the token to avoid replay attacks
        token = generateAndStoreToken(ctx);
        // put the token in the context for users who prefer to
        // render the token directly on the HTML
        ctx.put(headerName, token);
        ctx.next();
      } else {
        ctx.fail(403);
      }
      break;
    default:
      // ignore other methods
      ctx.next();
      break;
  }
}
 
Example 19
Source Project: quarkus   File: HttpAuthorizer.java    License: Apache License 2.0 4 votes vote down vote up
private void doPermissionCheck(RoutingContext routingContext,
        Uni<SecurityIdentity> identity, int index,
        SecurityIdentity augmentedIdentity,
        List<HttpSecurityPolicy> permissionCheckers) {
    if (index == permissionCheckers.size()) {
        QuarkusHttpUser currentUser = (QuarkusHttpUser) routingContext.user();
        if (augmentedIdentity != null) {
            if (!augmentedIdentity.isAnonymous()
                    && (currentUser == null || currentUser.getSecurityIdentity() != augmentedIdentity)) {
                routingContext.setUser(new QuarkusHttpUser(augmentedIdentity));
                routingContext.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, Uni.createFrom().item(augmentedIdentity));
            }
        }
        routingContext.next();
        return;
    }
    //get the current checker
    HttpSecurityPolicy res = permissionCheckers.get(index);
    res.checkPermission(routingContext, identity, CONTEXT)
            .subscribe().with(new Consumer<HttpSecurityPolicy.CheckResult>() {
                @Override
                public void accept(HttpSecurityPolicy.CheckResult checkResult) {
                    if (!checkResult.isPermitted()) {
                        doDeny(identity, routingContext);
                    } else {
                        if (checkResult.getAugmentedIdentity() != null) {
                            doPermissionCheck(routingContext, Uni.createFrom().item(checkResult.getAugmentedIdentity()),
                                    index + 1, checkResult.getAugmentedIdentity(), permissionCheckers);
                        } else {
                            //attempt to run the next checker
                            doPermissionCheck(routingContext, identity, index + 1, augmentedIdentity, permissionCheckers);
                        }
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    routingContext.fail(throwable);
                }
            });
}
 
Example 20
/**
 * Check the ETags values from the HTTP if-Match header if they exist,
 * and extract the values if this check was successful
 * <p>
 * The HTTP header "If-Match"is parsed and the values are put to the routingContext ctx with the
 * key {@link #KEY_RESOURCE_VERSION}.
 *
 * @param ctx The routing context of the request.
 */
protected void extractIfMatchVersionParam(final RoutingContext ctx) {
    final String ifMatchHeader = ctx.request().getHeader(HttpHeaders.IF_MATCH);
    if (! Strings.isNullOrEmpty(ifMatchHeader)) {
            ctx.put(KEY_RESOURCE_VERSION, ifMatchHeader);
    }
    ctx.next();
}