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

The following examples show how to use io.vertx.ext.web.RoutingContext#request() . 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: MainVerticle.java    From okapi with Apache License 2.0 6 votes vote down vote up
/**
 * Simple test to fake a _tenantPermission interface.
 * Captures the body, and reports it in a header.
 *
 * @param ctx routing context
 */
private void myPermissionHandle(RoutingContext ctx) {
  ReadStream<Buffer> content = ctx.request();
  final Buffer incoming = Buffer.buffer();
  content.handler(incoming::appendBuffer);
  ctx.request().endHandler(x -> {
    String body = incoming.toString();
    body = body.replaceAll("\\s+", " "); // remove newlines etc
    ctx.response().putHeader("X-Tenant-Perms-Result", body);
    if (body.length() > 80) {
      body = body.substring(0, 80) + "...";
    }
    logger.info("tenantPermissions: {}", body);
    ctx.response().end();
  });
}
 
Example 2
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 3
Source File: EncryptEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
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 4
Source File: OfficialAccountSubRouter.java    From AlipayWechatPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 更新公众号配置
 * 请求方法:PUT
 * 请求参数:id,name邮箱,appid,appsecret,verify
 * 响应:success或fail
 */
private void updateOfficialAccount(RoutingContext rc) {
    if (forbidAccess(rc, "id", true)) {
        return;
    }
    HttpServerRequest req = rc.request();
    Long id = Long.valueOf(req.getParam("id"));
    String name = req.getParam("name");
    String appid = req.getParam("appid");
    String appsecret = req.getParam("appsecret");
    String verify = req.getParam("verify");
    JsonObject updateAcc = new JsonObject().put(ID, id).put(NAME, name).put(WXAPPID, appid).put(WXAPPSECRET, appsecret).put(VERIFY, verify);
    log.debug("更新公众号配置:{}", updateAcc);
    vertx.eventBus().<Integer>send(ADDR_ACCOUNT_DB.get(), makeMessage(COMMAND_UPDATE_NORMAL, updateAcc), ar -> {
        HttpServerResponse response = rc.response();
        if(ar.succeeded()){
            Integer rows = ar.result().body();
            response.putHeader("content-type", "application/json; charset=utf-8").end(rows > 0 ? "success" : "fail");
        } else {
            log.error("EventBus消息响应错误", ar.cause());
            response.setStatusCode(500).end("EventBus error!");
        }
    });
}
 
Example 5
Source File: AuthHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
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 6
Source File: SummerRouter.java    From Summer with MIT License 6 votes vote down vote up
private Object getContext(RoutingContext routingContext,ArgInfo argInfo){
    Class clz = argInfo.getClazz();
    if (clz ==RoutingContext.class){

        return routingContext;
    }else if (clz == HttpServerRequest.class){
        return routingContext.request();
    }else if (clz == HttpServerResponse.class){
        return routingContext.response();
    }else if (clz == Session.class){
        return routingContext.session();
    }else if (clz == Vertx.class){
        return vertx;
    }
    return null;
}
 
Example 7
Source File: BearerAuthenticationMechanism.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String extractBearerToken(RoutingContext context) {
    final HttpServerRequest request = context.request();
    final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authorization == null) {
        return null;
    }

    int idx = authorization.indexOf(' ');

    if (idx <= 0 || !BEARER.equalsIgnoreCase(authorization.substring(0, idx))) {
        return null;
    }

    return authorization.substring(idx + 1);
}
 
Example 8
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 9
Source File: TestHttpServerRequestUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: RouteState.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
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 11
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * check accept and content-type headers if no - set the request asa not valid and return error to user
 */
private void checkAcceptContentType(JsonArray produces, JsonArray consumes, RoutingContext rc, boolean[] validRequest) {
  /*
   * NOTE that the content type and accept headers will accept a partial match - for example: if the raml indicates a text/plain and an
   * application/json content-type and only one is passed - it will accept it
   */
  // check allowed content types in the raml for this resource + method
  HttpServerRequest request = rc.request();
  if (consumes != null && validRequest[0]) {
    // get the content type passed in the request
    // if this was left out by the client they must add for request to return
    // clean up simple stuff from the clients header - trim the string and remove ';' in case
    // it was put there as a suffix
    String contentType = StringUtils.defaultString(request.getHeader("Content-type")).replaceFirst(";.*", "").trim();
    if (!consumes.contains(removeBoundry(contentType))) {
      endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.ContentTypeError, consumes, contentType),
        validRequest);
    }
  }

  // type of data expected to be returned by the server
  if (produces != null && validRequest[0]) {
    String accept = StringUtils.defaultString(request.getHeader("Accept"));
    if (acceptCheck(produces, accept) == null) {
      // use contains because multiple values may be passed here
      // for example json/application; text/plain mismatch of content type found
      endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.AcceptHeaderError, produces, accept),
        validRequest);
    }
  }
}
 
Example 12
Source File: OpenApiHandler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext event) {
    if (event.request().method().equals(HttpMethod.OPTIONS)) {
        addCorsResponseHeaders(event.response());
        event.response().headers().set("Allow", ALLOWED_METHODS);
    } else {
        HttpServerRequest req = event.request();
        HttpServerResponse resp = event.response();
        String accept = req.headers().get("Accept");

        List<String> formatParams = event.queryParam(QUERY_PARAM_FORMAT);
        String formatParam = formatParams.isEmpty() ? null : formatParams.get(0);

        // Default content type is YAML
        Format format = Format.YAML;

        // Check Accept, then query parameter "format" for JSON; else use YAML.
        if ((accept != null && accept.contains(Format.JSON.getMimeType())) ||
                ("JSON".equalsIgnoreCase(formatParam))) {
            format = Format.JSON;
        }

        addCorsResponseHeaders(resp);
        resp.headers().set("Content-Type", format.getMimeType() + ";charset=UTF-8");
        ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
        try (InputStream in = cl.getResourceAsStream(BASE_NAME + format)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int r;
            byte[] buf = new byte[1024];
            while ((r = in.read(buf)) > 0) {
                out.write(buf, 0, r);
            }
            resp.end(Buffer.buffer(out.toByteArray()));
        } catch (IOException e) {
            event.fail(e);
        }

    }
}
 
Example 13
Source File: WriteHandler.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    if (request.params().contains("sid") && request.params().contains("wcnt") && request.params().contains("data")) {
        final UUID sid = UUID.fromString(request.params().get("sid"));
        final byte[] data = Base64.getUrlDecoder().decode(request.params().get("data"));
        response.setStatusCode(200);
        final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS);
        final Session session = map.get(sid.toString());
        if (session == null) {
            response.setStatusCode(410);
            response.end();
            return;
        }
        session.setWrite_count(Integer.parseInt(request.params().get("wcnt")));
        final Buffer message = Buffer.buffer();
        message.appendBytes(data);
        vertx.eventBus().publish(session.getHandler(), message);
        response.end();
    } else {
        response.setStatusCode(410);
        response.end();
    }
}
 
Example 14
Source File: MethodOverrideHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
  HttpServerRequest request = context.request();

  HttpMethod from = request.method();
  HttpMethod to = methodFromHeader(request);

  if (to != null && from != to && canOverride(from, to)) {
    context.reroute(to, request.path());
  } else {
    context.next();
  }
}
 
Example 15
Source File: HTTPAuthorizationHandler.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected final void parseAuthorization(RoutingContext ctx, boolean optional, Handler<AsyncResult<String>> handler) {

    final HttpServerRequest request = ctx.request();
    final String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);

    if (authorization == null) {
      if (optional) {
        // this is allowed
        handler.handle(Future.succeededFuture());
      } else {
        handler.handle(Future.failedFuture(UNAUTHORIZED));
      }
      return;
    }

    try {
      int idx = authorization.indexOf(' ');

      if (idx <= 0) {
        handler.handle(Future.failedFuture(BAD_REQUEST));
        return;
      }

      if (!type.is(authorization.substring(0, idx))) {
        handler.handle(Future.failedFuture(UNAUTHORIZED));
        return;
      }

      handler.handle(Future.succeededFuture(authorization.substring(idx + 1)));
    } catch (RuntimeException e) {
      handler.handle(Future.failedFuture(e));
    }
  }
 
Example 16
Source File: ProxyService.java    From okapi with Apache License 2.0 4 votes vote down vote up
/**
 * Routing context hander (handling all requests for Okapi).
 * @param ctx routing context
 */
public void proxy(RoutingContext ctx) {
  ctx.request().pause();
  ReadStream<Buffer> stream = ctx.request();
  // Pause the request data stream before doing any slow ops, otherwise
  // it will get read into a buffer somewhere.

  ProxyContext pc = new ProxyContext(ctx, waitMs);

  // It would be nice to pass the request-id to the client, so it knows what
  // to look for in Okapi logs. But that breaks the schemas, and RMB-based
  // modules will not accept the response. Maybe later...
  String tenantId = tenantHeader(pc);
  if (tenantId == null) {
    stream.resume();
    return; // Error code already set in ctx
  }

  final MultiMap headers = ctx.request().headers();
  sanitizeAuthHeaders(headers);
  tenantManager.get(tenantId, gres -> {
    if (gres.failed()) {
      stream.resume();
      pc.responseError(400, messages.getMessage("10106", tenantId));
      return;
    }
    Tenant tenant = gres.result();
    moduleManager.getEnabledModules(tenant, mres -> {
      if (mres.failed()) {
        stream.resume();
        pc.responseError(mres.getType(), mres.cause());
        return;
      }
      List<ModuleDescriptor> enabledModules = mres.result();

      String metricKey = "proxy." + tenantId + "."
          + ctx.request().method() + "." + ctx.normalisedPath();
      DropwizardHelper.markEvent(metricKey);

      List<ModuleInstance> l = getModulesForRequest(pc, enabledModules);
      if (l == null) {
        stream.resume();
        return; // ctx already set up
      }

      // check delegate CORS and reroute if necessary
      if (CorsHelper.checkCorsDelegate(ctx, l)) {
        stream.resume();
        ctx.reroute(ctx.request().path());
        return;
      }

      pc.setModList(l);

      pc.logRequest(ctx, tenantId);

      headers.set(XOkapiHeaders.URL, okapiUrl);
      headers.remove(XOkapiHeaders.MODULE_ID);
      headers.set(XOkapiHeaders.REQUEST_IP, ctx.request().remoteAddress().host());
      headers.set(XOkapiHeaders.REQUEST_TIMESTAMP, "" + System.currentTimeMillis());
      headers.set(XOkapiHeaders.REQUEST_METHOD, ctx.request().rawMethod());

      resolveUrls(l.iterator(), res -> {
        if (res.failed()) {
          stream.resume();
          pc.responseError(res.getType(), res.cause());
        } else {
          List<HttpClientRequest> clientRequest = new LinkedList<>();
          proxyR(l.iterator(), pc, stream, null, clientRequest);
        }
      });
    });

  });
}
 
Example 17
Source File: AuctionRequestFactory.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
private static String accountErrorMessage(String message, RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    return String.format("%s, Url: %s and Referer: %s", message, request.absoluteURI(),
            request.headers().get(HttpUtil.REFERER_HEADER));
}
 
Example 18
Source File: VertxVaadinRequest.java    From vertx-vaadin with MIT License 4 votes vote down vote up
public VertxVaadinRequest(VertxVaadinService service, RoutingContext routingContext) {
    this.service = service;
    this.routingContext = routingContext;
    this.request = routingContext.request();

}
 
Example 19
Source File: VertxServerRequestToHttpServletRequest.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public VertxServerRequestToHttpServletRequest(RoutingContext context) {
  this.context = context;
  this.vertxRequest = context.request();
  this.socketAddress = this.vertxRequest.remoteAddress();
  super.setBodyBuffer(context.getBody());
}
 
Example 20
Source File: CookieHandler.java    From nassh-relay with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(final RoutingContext context) {
    logger.debug("got request");
    final HttpServerRequest request = context.request();
    final HttpServerResponse response = context.response();
    response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
    response.putHeader("Pragma", "no-cache");
    if (request.params().contains("ext") && request.params().contains("path")) {
        final String ext = request.params().get("ext");
        final String path = request.params().get("path");
        if (!authentication) {
            response.putHeader("location", "chrome-extension://" + ext + "/" + path + "#anonymous@" + RequestHelper.getHost(request));
            response.setStatusCode(302);
            response.end();
            return;
        }
        final AuthSession authSession = WebHelper.validateCookie(context);
        if (authSession != null) {
            final String gplusid = authSession.get("id");
            response.putHeader("location", "chrome-extension://" + ext + "/" + path + "#" + gplusid + "@" + RequestHelper.getHost(request));
            response.setStatusCode(302);
            response.end();
        } else {
            response.setStatusCode(200);
            final String state = new BigInteger(130, new SecureRandom()).toString(32);
            final AuthSession session = AuthSessionManager.createSession(sessionTTL);
            session.put("state", state);
            final Cookie sessionCookie = Cookie
                .cookie(Constants.SESSIONCOOKIE, session.getId().toString())
                .setHttpOnly(true);
            if (secureCookie) {
                sessionCookie
                    .setSameSite(CookieSameSite.NONE)
                    .setSecure(true);
            }
            response.addCookie(sessionCookie);
            final String auth_html = new Scanner(this.getClass().getResourceAsStream(STATIC_FILE), "UTF-8")
                .useDelimiter("\\A").next()
                .replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", auth.getString("client-id"))
                .replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
                .replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", auth.getString("title"));
            response.end(auth_html);
        }
    } else {
        response.setStatusCode(401);
        response.end("unauthorized");
    }
}