Java Code Examples for io.vertx.core.http.HttpServerRequest#endHandler()

The following examples show how to use io.vertx.core.http.HttpServerRequest#endHandler() . 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: 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 2
Source File: NexusHttpProxy.java    From nexus-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Proxies the specified HTTP request, enriching its headers with authentication information.
 *
 * @param userId  the ID of the user making the request.
 * @param origReq the original request (i.e., {@link RoutingContext#request()}.
 * @param origRes the original response (i.e., {@link RoutingContext#request()}.
 */
public void proxyUserRequest(final String userId,
                             final HttpServerRequest origReq,
                             final HttpServerResponse origRes) {
    final Handler<HttpClientResponse> proxiedResHandler = proxiedRes -> {
        origRes.setChunked(true);
        origRes.setStatusCode(proxiedRes.statusCode());
        origRes.headers().setAll(proxiedRes.headers());
        proxiedRes.handler(origRes::write);
        proxiedRes.endHandler(v -> origRes.end());
    };

    final HttpClientRequest proxiedReq;
    proxiedReq = httpClient.request(origReq.method(), port, host, origReq.uri(), proxiedResHandler);
    if(origReq.method() == HttpMethod.OTHER) {
        proxiedReq.setRawMethod(origReq.rawMethod());
    }
    proxiedReq.setChunked(true);
    proxiedReq.headers().add(X_FORWARDED_PROTO, getHeader(origReq, X_FORWARDED_PROTO, origReq.scheme()));
    proxiedReq.headers().add(X_FORWARDED_FOR, getHeader(origReq, X_FORWARDED_FOR, origReq.remoteAddress().host()));
    proxiedReq.headers().addAll(origReq.headers());
    injectRutHeader(proxiedReq, userId);
    origReq.handler(proxiedReq::write);
    origReq.endHandler(v -> proxiedReq.end());
}
 
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: 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 5
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
/**
 * @param method2Run
 * @param rc
 * @param request
 * @param okapiHeaders
 * @param tenantId
 * @param instance
 * @param uploadParamPosition
 * @param paramArray
 * @param validRequest
 * @param start
 */
private void handleInputStreamUpload(Method method2Run, RoutingContext rc, HttpServerRequest request,
    Object instance, String[] tenantId, Map<String, String> okapiHeaders,
    int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest, long start) {

  final Buffer content = Buffer.buffer();

  request.handler(new Handler<Buffer>() {
    @Override
    public void handle(Buffer buff) {
      content.appendBuffer(buff);
    }
  });
  request.endHandler( e -> {
    paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(content.getBytes());
    try {
      invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> {
        LogUtil.formatLogMessage(className, "start", " invoking " + method2Run);
        sendResponse(rc, v, start, tenantId[0]);
      });
    } catch (Exception e1) {
      log.error(e1.getMessage(), e1);
      rc.response().end();
    }
  });

  request.exceptionHandler(new Handler<Throwable>(){
    @Override
    public void handle(Throwable event) {
      endRequestWithError(rc, 400, true, event.getMessage(), validRequest);
    }
  });

}
 
Example 6
Source File: HttpHandler.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a new HTTP request.
 * The actual reading of the request is delegated to the {@link org.wisdom.framework.vertx.ContextFromVertx} and
 * {@link org.wisdom.framework.vertx.RequestFromVertx} classes. However, the close handler is set here and
 * trigger the request dispatch (i.e. Wisdom processing).
 *
 * @param request the request
 */
@Override
public void handle(final HttpServerRequest request) {
    LOGGER.debug("A request has arrived on the server : {} {}", request.method(), request.path());
    final ContextFromVertx context = new ContextFromVertx(vertx, vertx.getOrCreateContext(), accessor, request);

    if (!server.accept(request.path())) {
        LOGGER.warn("Request on {} denied by {}", request.path(), server.name());
        writeResponse(context, (RequestFromVertx) context.request(),
                server.getOnDeniedResult(),
                false,
                true);
    } else {
        Buffer raw = Buffer.buffer(0);
        RequestFromVertx req = (RequestFromVertx) context.request();
        AtomicBoolean error = new AtomicBoolean();
        if (HttpUtils.isPostOrPut(request)) {
            request.setExpectMultipart(true);
            request.uploadHandler(upload -> req.getFiles().add(new MixedFileUpload(context.vertx(), upload,
                    accessor.getConfiguration().getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE),
                    accessor.getConfiguration().getLongWithDefault("http.upload.max", -1L),
                    r -> {
                        request.uploadHandler(null);
                        request.handler(null);
                        error.set(true);
                        writeResponse(context, req, r, false, true);
                    })
            ));
        }

        int maxBodySize =
                accessor.getConfiguration().getIntegerWithDefault("request.body.max.size", 100 * 1024);
        request.handler(event -> {
            if (event == null) {
                return;
            }

            // To avoid we run out of memory we cut the read body to 100Kb. This can be configured using the
            // "request.body.max.size" property.
            boolean exceeded = raw.length() >= maxBodySize;

            // We may have the content in different HTTP message, check if we already have a content.
            // Issue #257.
            if (!exceeded) {
                raw.appendBuffer(event);
            } else {
                // Remove the handler as we stop reading the request.
                request.handler(null);
                error.set(true);
                writeResponse(context, req, new Result(Status.PAYLOAD_TOO_LARGE)
                        .render("Body size exceeded - request cancelled")
                                .as(MimeTypes.TEXT),
                        false, true);
            }
        });

        request.endHandler(event -> {
            if (error.get()) {
                // Error already written.
                return;
            }
            req.setRawBody(raw);
            // Notifies the context that the request has been read, we start the dispatching.
            if (context.ready()) {
                // Dispatch.
                dispatch(context, (RequestFromVertx) context.request());
            } else {
                writeResponse(context, req,
                        Results.badRequest("Request processing failed"), false, true);
            }
        });
    }
}