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

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

Introduction

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

Prototype

HttpMethod method();

Source Link

Usage

From source file:com.cyngn.vertx.opentsdb.spi.HttpServerMetricsImpl.java

License:Apache License

@Override
public HttpMetric requestBegin(SocketMetric socketMetric, HttpServerRequest request) {
    socketMetric.bytesRead = 0;//from  w w  w.  ja va 2  s.c  o  m
    socketMetric.bytesWritten = 0;
    return new HttpMetric(socketMetric, request.method(), request.uri());
}

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

License:Open Source License

/**
 * {@inheritDoc}/*from w ww  .ja  v a  2  s. c  om*/
 */
@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.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java

License:Open Source License

protected void handle(final HttpServerRequest vertxRequest, final InputStream inputStream) {

    URI uri = getAbsoluteURI(vertxRequest);
    boolean isSecure = "https".equalsIgnoreCase(uri.getScheme());

    UriBuilder baseUriBuilder = UriBuilder.fromUri(uri).replacePath(baseUri.getPath()).replaceQuery(null);

    // Create the jersey request
    final ContainerRequest jerseyRequest = new ContainerRequest(baseUriBuilder.build(), uri,
            vertxRequest.method().name(), new DefaultSecurityContext(isSecure), new MapPropertiesDelegate());

    handle(vertxRequest, inputStream, jerseyRequest);

}

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

License:Open Source License

protected boolean shouldReadData(HttpServerRequest vertxRequest) {

    HttpMethod method = vertxRequest.method();

    // Only read input stream data for post/put methods
    if (!(HttpMethod.POST == method || HttpMethod.PUT == method)) {
        return false;
    }//  ww w  .  j a va  2s.  co  m

    String contentType = vertxRequest.headers().get(HttpHeaders.CONTENT_TYPE);

    if (contentType == null || contentType.isEmpty()) {
        // Special handling for IE8 XDomainRequest where content-type is missing
        // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
        return true;
    }

    MediaType mediaType = MediaType.valueOf(contentType);

    // Allow text/plain
    if (MediaType.TEXT_PLAIN_TYPE.getType().equals(mediaType.getType())
            && MediaType.TEXT_PLAIN_TYPE.getSubtype().equals(mediaType.getSubtype())) {
        return true;
    }

    // Only other media types accepted are application (will check subtypes next)
    String applicationType = MediaType.APPLICATION_FORM_URLENCODED_TYPE.getType();
    if (!applicationType.equalsIgnoreCase(mediaType.getType())) {
        return false;
    }

    // Need to do some special handling for forms:
    // Jersey doesn't properly handle when charset is included
    if (mediaType.getSubtype().equalsIgnoreCase(MediaType.APPLICATION_FORM_URLENCODED_TYPE.getSubtype())) {
        if (!mediaType.getParameters().isEmpty()) {
            vertxRequest.headers().remove(HttpHeaders.CONTENT_TYPE);
            vertxRequest.headers().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
        }
        return true;
    }

    // Also accept json/xml sub types
    return MediaType.APPLICATION_JSON_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype())
            || MediaType.APPLICATION_XML_TYPE.getSubtype().equalsIgnoreCase(mediaType.getSubtype());
}

From source file:com.groupon.vertx.utils.HealthcheckHandler.java

License:Apache License

protected void processHeartBeatResponse(Boolean exists, HttpServerRequest request, long startTime) {
    HttpResponseStatus status;/*from w  w w  .  j  av a  2s  .c  o  m*/
    final boolean includeBody = !request.method().equals(HttpMethod.HEAD);

    if (exists) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.SERVICE_UNAVAILABLE;
    }

    setCommonHttpResponse(request, status);

    String responseBody = status.reasonPhrase();
    if (includeBody) {
        request.response().end(responseBody);
    } else {
        request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length()));
        request.response().end();
    }

    long totalTime = System.currentTimeMillis() - startTime;
    LOG.debug("handle", "healthcheckResponse", new String[] { "method", "status", "totalTime" },
            request.method(), status.code(), totalTime);
}

From source file:com.groupon.vertx.utils.HealthcheckHandler.java

License:Apache License

protected void processExceptionResponse(HttpServerRequest request, Exception ex, long startTime) {
    HttpResponseStatus status = HttpResponseStatus.SERVICE_UNAVAILABLE;
    final boolean includeBody = !request.method().equals(HttpMethod.HEAD);
    String responseBody = status.reasonPhrase() + ": " + ex.getMessage();

    setCommonHttpResponse(request, status);

    if (includeBody) {
        request.response().end(responseBody);
    } else {//from   w w  w  .j a va2s  . co m
        request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length()));
        request.response().end();
    }

    long totalTime = System.currentTimeMillis() - startTime;
    LOG.debug("handle", "healthcheckResponse", new String[] { "method", "status", "totalTime" },
            request.method(), status.code(), totalTime);
}

From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java

License:Open Source License

@Override
public void handle(RoutingContext context) {
    HttpServerRequest request = context.request();
    if (request.method() != HttpMethod.GET && request.method() != HttpMethod.HEAD) {
        if (log.isTraceEnabled())
            log.trace("Not GET or HEAD so ignoring request");
        context.next();//from  ww  w  . ja  v a2  s  . c  o  m
    } else {
        String path = context.normalisedPath();
        // if the normalized path is null it cannot be resolved
        if (path == null) {
            log.warn("Invalid path: " + context.request().path() + " so returning 404");
            context.fail(NOT_FOUND.code());
            return;
        }

        // only root is known for sure to be a directory. all other directories must be identified as such.
        if (!directoryListing && "/".equals(path)) {
            path = indexPage;
        }

        // can be called recursive for index pages
        sendStatic(context, path);

    }
}

From source file:com.klwork.spring.vertx.render.MyStaticHandlerImpl.java

License:Open Source License

private void sendFile(RoutingContext context, String file, FileProps fileProps) {
    HttpServerRequest request = context.request();

    Long offset = null;/*from   w ww  .ja  v  a 2 s.  com*/
    Long end = null;
    MultiMap headers = null;

    if (rangeSupport) {
        // check if the client is making a range request
        String range = request.getHeader("Range");
        // end byte is length - 1
        end = fileProps.size() - 1;

        if (range != null) {
            Matcher m = RANGE.matcher(range);
            if (m.matches()) {
                try {
                    String part = m.group(1);
                    // offset cannot be empty
                    offset = Long.parseLong(part);
                    // offset must fall inside the limits of the file
                    if (offset < 0 || offset >= fileProps.size()) {
                        throw new IndexOutOfBoundsException();
                    }
                    // length can be empty
                    part = m.group(2);
                    if (part != null && part.length() > 0) {
                        // ranges are inclusive
                        end = Long.parseLong(part);
                        // offset must fall inside the limits of the file
                        if (end < offset || end >= fileProps.size()) {
                            throw new IndexOutOfBoundsException();
                        }
                    }
                } catch (NumberFormatException | IndexOutOfBoundsException e) {
                    context.fail(REQUESTED_RANGE_NOT_SATISFIABLE.code());
                    return;
                }
            }
        }

        // notify client we support range requests
        headers = request.response().headers();
        headers.set("Accept-Ranges", "bytes");
        // send the content length even for HEAD requests
        headers.set("Content-Length", Long.toString(end + 1 - (offset == null ? 0 : offset)));
    }

    writeCacheHeaders(request, fileProps);

    if (request.method() == HttpMethod.HEAD) {
        request.response().end();
    } else {
        if (rangeSupport && offset != null) {
            // must return content range
            headers.set("Content-Range", "bytes " + offset + "-" + end + "/" + fileProps.size());
            // return a partial response
            request.response().setStatusCode(PARTIAL_CONTENT.code());

            // Wrap the sendFile operation into a TCCL switch, so the file resolver would find the file from the set
            // classloader (if any).
            final Long finalOffset = offset;
            final Long finalEnd = end;
            wrapInTCCLSwitch(() -> request.response().sendFile(file, finalOffset, finalEnd + 1, res2 -> {
                if (res2.failed()) {
                    context.fail(res2.cause());
                }
            }), null);
        } else {
            // Wrap the sendFile operation into a TCCL switch, so the file resolver would find the file from the set
            // classloader (if any).
            wrapInTCCLSwitch(() -> request.response().sendFile(file, res2 -> {
                if (res2.failed()) {
                    context.fail(res2.cause());
                }
            }), null);
        }
    }
}

From source file:com.navercorp.pinpoint.plugin.vertx.interceptor.ServerConnectionHandleRequestInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }//from   www.  j a  v a2  s.  c  o  m

    final Trace trace = traceContext.currentRawTraceObject();
    if (trace == null) {
        return;
    }

    if (!hasScope(trace)) {
        // not vertx trace.
        return;
    }

    if (!leaveScope(trace)) {
        if (logger.isInfoEnabled()) {
            logger.info("Failed to leave scope. trace={}, sampled={}", trace, trace.canSampled());
        }
        // delete unstable trace.
        deleteTrace(trace);
        return;
    }

    if (!isEndScope(trace)) {
        // ignored recursive call.
        return;
    }

    if (!trace.canSampled()) {
        deleteTrace(trace);
        return;
    }

    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(descriptor);
        recorder.recordException(throwable);
        if (validate(args)) {
            if (this.isTraceRequestParam) {
                final HttpServerRequest request = (HttpServerRequest) args[0];
                if (!excludeProfileMethodFilter.filter(request.method().toString())) {
                    final String parameters = getRequestParameter(request, 64, 512);
                    if (parameters != null && !parameters.isEmpty()) {
                        recorder.recordAttribute(AnnotationKey.HTTP_PARAM, parameters);
                    }
                }
            }
        }
    } catch (Throwable t) {
        if (logger.isWarnEnabled()) {
            logger.warn("AFTER. Caused:{}", t.getMessage(), t);
        }
    } finally {
        trace.traceBlockEnd();
        deleteTrace(trace);
    }
}

From source file:com.navercorp.pinpoint.plugin.vertx.MethodFilterExtractor.java

License:Apache License

@Override
public String extractParameter(HttpServerRequest httpServletRequest) {
    if (excludeProfileMethodFilter.filter(httpServletRequest.method().toString())) {
        return null;
    }/*from  w  ww . ja v a2 s  .  com*/
    return delegate.extractParameter(httpServletRequest);
}