Example usage for io.vertx.core.http HttpServerRequest handler

List of usage examples for io.vertx.core.http HttpServerRequest handler

Introduction

In this page you can find the example usage for io.vertx.core.http HttpServerRequest handler.

Prototype

@Override
    HttpServerRequest handler(Handler<Buffer> handler);

Source Link

Usage

From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java

License:Open Source License

/**
 * {@inheritDoc}//from   w  ww .j  a v a  2  s .  c o  m
 */
@Override
public void handle(final HttpServerRequest vertxRequest) {

    // Wait for the body for jersey to handle form/json/xml params
    if (shouldReadData(vertxRequest)) {
        if (logger.isDebugEnabled()) {
            logger.debug("DefaultJerseyHandler - handle request and read body: " + vertxRequest.method() + " "
                    + vertxRequest.uri());
        }
        final Buffer body = Buffer.buffer();

        vertxRequest.handler(buffer -> {
            body.appendBuffer(buffer);
            if (body.length() > maxBodySize) {
                throw new RuntimeException(
                        "The input stream has exceeded the max allowed body size " + maxBodySize + ".");
            }
        });
        vertxRequest.endHandler(aVoid -> {
            InputStream inputStream = new ByteArrayInputStream(body.getBytes());
            DefaultJerseyHandler.this.handle(vertxRequest, inputStream);
        });

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("DefaultJerseyHandler - handle request: " + vertxRequest.method() + " "
                    + vertxRequest.uri());
        }
        DefaultJerseyHandler.this.handle(vertxRequest, null);
    }

}

From source file:com.sibvisions.vertx.HttpServer.java

License:Apache License

/**
 * Handles a service/server request.//  w ww.j  ava  2s .com
 * 
 * @param pRequest the request
 */
private void handleService(HttpServerRequest pRequest) {
    AbstractDataHandler dataHandler = new HttpDataHandler(srvJVx, pRequest.response());

    pRequest.handler(dataHandler);
    pRequest.endHandler(new StopHandler(dataHandler));
    pRequest.exceptionHandler(new ExceptionHandler(dataHandler));
}

From source file:com.sibvisions.vertx.HttpServer.java

License:Apache License

/**
 * Handles an upload request./*  w  ww .  j a v a 2s.  c  om*/
 * 
 * @param pRequest the request
 */
private void handleUpload(final HttpServerRequest pRequest) {
    pRequest.handler(new Handler<Buffer>() {
        private OutputStream os;

        public void handle(Buffer event) {
            try {
                if (os == null) {
                    String sFileName = getFileName(pRequest.headers().get("Content-Disposition"));

                    if (sFileName == null) {
                        pRequest.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code());
                        pRequest.response().end();

                        return;
                    }

                    RemoteFileHandle rfh = new RemoteFileHandle(sFileName, pRequest.params().get("KEY"));
                    os = rfh.getOutputStream();
                }

                os.write(event.getBytes());
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }
    });

    pRequest.exceptionHandler(new Handler<Throwable>() {
        public void handle(Throwable event) {
            pRequest.response().end();
        }
    });

    pRequest.endHandler(new Handler<Void>() {
        public void handle(Void event) {
            pRequest.response().end();
        }
    });
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example9(HttpServerRequest request) {

    request.handler(buffer -> {
        System.out.println("I have received a chunk of the body of length " + buffer.length());
    });/*ww w. j  a  v  a 2 s  .  co m*/
}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example10(HttpServerRequest request) {

    // Create an empty buffer
    Buffer totalBuffer = Buffer.buffer();

    request.handler(buffer -> {
        System.out.println("I have received a chunk of the body of length " + buffer.length());
        totalBuffer.appendBuffer(buffer);
    });//from   w w  w  .  j  a va  2 s  .c o  m

    request.endHandler(v -> {
        System.out.println("Full body received, length = " + totalBuffer.length());
    });
}

From source file:io.servicecomb.transport.rest.vertx.RestBodyHandler.java

License:Apache License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest request = context.request();
    // we need to keep state since we can be called again on reroute
    Boolean handled = context.get(BODY_HANDLED);
    if (handled == null || !handled) {
        BHandler handler = new BHandler(context);
        request.handler(handler);
        request.endHandler(v -> handler.end());
        context.put(BODY_HANDLED, true);
    } else {//  w w  w . j  a  v  a 2s .c om
        // 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();
    }
}

From source file:org.wisdom.framework.vertx.HttpHandler.java

License:Apache License

/**
 * Handles a new HTTP request./*from  ww w . j  av  a2s  .c o  m*/
 * 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);
            }
        });
    }
}

From source file:org.workspace7.k8s.auth.proxy.K8sWebProxyVerticle.java

License:Apache License

/**
 *
 *
 * @param routingContext/*from  ww w .j av a2s .co  m*/
 */
protected void handleApiPath(RoutingContext routingContext) {

    HttpServerRequest request = routingContext.request();
    HttpServerResponse response = routingContext.response();

    JsonObject userPrincipal = routingContext.user().principal();
    _logger.trace("User Principal:{}" + userPrincipal);

    final String accessToken = userPrincipal.getString("id_token");
    final String authHeader = String.format(BEARER_FORMAT, accessToken);

    _logger.debug("API: Proxying Request to K8s Master :{} with method {}", request.uri(), request.method());

    //Proxying request to Kubernetes Master
    HttpClientRequest k8sClientRequest = k8HttpClient.request(request.method(), request.uri());

    k8sClientRequest.handler(k8sApiResp -> {

        k8sApiResp.exceptionHandler(event -> {
            _logger.error("Error while calling Kubernetes :", event.getCause());
            //TODO clear headers for security
            response.setStatusCode(503).end();
            k8sClientRequest.end();
        });

        response.setChunked(true);
        response.setStatusCode(k8sApiResp.statusCode());
        //TODO clear headers for security
        response.headers().setAll(k8sApiResp.headers());

        k8sApiResp.handler(data -> {
            _logger.debug("Proxying Resp Body:{}", data.toString());
            response.write(data);
        });

        k8sApiResp.endHandler((v) -> {
            response.end();
            k8sClientRequest.end();
        });
    });

    k8sClientRequest.setChunked(true);
    //Add Required Headers to k8s
    k8sClientRequest.headers().set(AUTHORIZATION_HEADER, authHeader);

    request.handler(data -> k8sClientRequest.write(data));

    k8sClientRequest.exceptionHandler(ex -> {
        _logger.error("Error while calling Kubernetes API", ex);
        //TODO clear headers for security
        response.setStatusCode(503).end();
    });

}