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

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

Introduction

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

Prototype

String uri();

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 . j a  v a 2s.com*/
    socketMetric.bytesWritten = 0;
    return new HttpMetric(socketMetric, request.method(), request.uri());
}

From source file:com.dinstone.vertx.web.core.AbstractRouteResolver.java

License:Apache License

private static String getMatrixParam(HttpServerRequest request, String paramName) {
    String[] items = request.uri().split(";");
    for (String item : items) {
        String[] nameValue = item.split("=");
        if (nameValue.length == 2 && nameValue[0].equals(paramName)) {
            return nameValue[1];
        }//from   ww w  . j a  v  a  2 s.co  m
    }

    return null;
}

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

License:Open Source License

/**
 * {@inheritDoc}/*from www .  j  ava  2s. 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 URI getAbsoluteURI(HttpServerRequest vertxRequest) {

    URI absoluteUri;//from  ww  w.j a va  2  s . co  m
    String hostAndPort = vertxRequest.headers().get(HttpHeaders.HOST);

    try {
        absoluteUri = URI.create(vertxRequest.absoluteURI());

        if (hostAndPort != null && !hostAndPort.isEmpty()) {
            String[] parts = hostAndPort.split(":");
            String host = parts[0];
            int port = (parts.length > 1 ? Integer.valueOf(parts[1]) : -1);

            if (!host.equalsIgnoreCase(absoluteUri.getHost()) || port != absoluteUri.getPort()) {
                absoluteUri = UriBuilder.fromUri(absoluteUri).host(host).port(port).build();
            }
        }

        return absoluteUri;
    } catch (IllegalArgumentException e) {
        String uri = vertxRequest.uri();

        if (!uri.contains("?")) {
            throw e;
        }

        try {
            logger.warn("Invalid URI: " + uri + ".  Attempting to parse query string.", e);
            QueryStringDecoder decoder = new QueryStringDecoder(uri);

            StringBuilder sb = new StringBuilder(decoder.path() + "?");

            for (Map.Entry<String, List<String>> p : decoder.parameters().entrySet()) {
                for (String value : p.getValue()) {
                    sb.append(p.getKey()).append("=").append(URLEncoder.encode(value, "UTF-8"));
                }
            }

            return URI.create(sb.toString());

        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }

    }

}

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

License:Apache License

@Override
public String getAcceptorHost(HttpServerRequest request) {
    return NetworkUtils.getHostFromURL(request.uri().toString());
}

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

License:Apache License

private void recordParentInfo(SpanRecorder recorder, HttpServerRequest request) {
    String parentApplicationName = request.getHeader(Header.HTTP_PARENT_APPLICATION_NAME.toString());
    if (parentApplicationName != null) {
        final String host = request.getHeader(Header.HTTP_HOST.toString());
        if (host != null) {
            recorder.recordAcceptorHost(host);
        } else {/*w w  w .j  av a 2  s  . c om*/
            recorder.recordAcceptorHost(NetworkUtils.getHostFromURL(request.uri().toString()));
        }
        final String type = request.getHeader(Header.HTTP_PARENT_APPLICATION_TYPE.toString());
        final short parentApplicationType = NumberUtils.parseShort(type, ServiceType.UNDEFINED.getCode());
        recorder.recordParentApplication(parentApplicationName, parentApplicationType);
    }
}

From source file:gribbit.server.GribbitServer.java

License:Open Source License

/**
 * Start the HTTP server./*from  w ww. ja v a 2  s . com*/
 * 
 * @throws IllegalArgumentException
 *             if port is already in use, or the server cannot be started for some other reason.
 */
public GribbitServer start() {
    if (port == null) {
        port = useTLS ? 8443 : 8080;
    }
    if (!portAvailable(port)) {
        throw new IllegalArgumentException("Port " + port + " is not available -- is server already running?");
    }

    String domainAndPort = domain + ((!useTLS && port == 80) || (useTLS && port == 443) ? "" : ":" + port);
    try {
        uri = new URI((useTLS ? "https" : "http") + "://" + domainAndPort);
        wsUri = new URI((useTLS ? "wss" : "ws") + "://" + domainAndPort);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HttpServerOptions serverOptions = new HttpServerOptions() //
            .setIdleTimeout(IDLE_TIMEOUT_SECONDS) //
            .setHandle100ContinueAutomatically(true) //
            .setSsl(useTLS);
    server = vertx.createHttpServer(serverOptions);
    router = Router.router(vertx);

    // Automatically serve files in "webroot/static/*" (relative to current directory, or in classpath).
    // Handles range requests automatically, and if files are in a jar in the classpath, they are
    // transparently extracted to a temporary cache directory on disk. Also handles Content-Range requests.
    StaticHandler staticHandler = StaticHandler.create() //
            .setWebRoot("webroot") //
            .setIncludeHidden(false) //
            .setDirectoryListing(false);
    router.route("/static/*").handler(staticHandler);

    // TODO: switch to clustered session store in clustered environment
    SessionStore store = LocalSessionStore.create(vertx, basePackageName, SESSION_REAPER_TIMEOUT_MILLIS);
    router.route().handler(CookieHandler.create()); // SessionHandler requires CookieHandler
    router.route().handler(SessionHandler.create(store));

    router.route().handler(routingContext -> {
        // Execute all requests on worker threads, so that they can block
        vertx.executeBlocking(future -> {
            Response response = null;
            HttpServerRequest request = routingContext.request();
            ParsedURL reqURL = new ParsedURL(request.uri());
            try {
                // RequestURL reqURL = new RequestURL(request.absoluteURI());  // TODO
                boolean isWSUpgrade = false;
                //                    if (webSocketHandlers != null) {
                //                        for (WebSocketHandler handler : webSocketHandlers) {
                //                            if (handler.isWebSocketUpgradeURL(request.absoluteURI())) {
                //                                isWSUpgrade = true;
                //                                ServerWebSocket websocket = request.upgrade();
                //                                throw new RuntimeException("TODO"); // TODO
                //                            }
                //                        }
                //                    }
                if (!isWSUpgrade) {
                    // Try each route in turn
                    for (Route route : siteResources.getAllRoutes()) {
                        if (route.matches(reqURL)) {
                            response = route.callHandler(routingContext, reqURL);
                            if (response != null) {
                                // Stop calling handlers after the first response
                                break;
                            }
                        }
                    }
                    if (response == null) {
                        // No route matched => 404
                        response = new NotFoundException().generateErrorResponse(routingContext, siteResources);
                    }
                }
            } catch (Exception e) {
                // Convert Exception to InternalServerErrorException if it's not already a ResponseException 
                ResponseException responseException;
                if (e instanceof ResponseException) {
                    responseException = (ResponseException) e;
                } else {
                    responseException = new InternalServerErrorException(e);
                }
                try {
                    // Otherwise, use the default response for this error type
                    response = responseException.generateErrorResponse(routingContext, siteResources);
                } catch (Exception e2) {
                    // Generate a generic InternalServerErrorException response if an exception was thrown
                    // while generating a response
                    response = new InternalServerErrorException(
                            "Exception in error handler while handling exception " + e.getMessage(), e2)
                                    .generateErrorResponse(routingContext, siteResources);
                }
            }
            try {
                // Send response
                response.send(routingContext);

            } catch (Exception e) {
                // Failure while sending response, connection was probably closed
            }
            future.complete();
        },
                // From the docs:
                // "By default, if executeBlocking is called several times from the same context (e.g. the
                // same verticle instance) then the different executeBlocking are executed serially (i.e.
                // one after another). If you dont care about ordering you can call executeBlocking
                // specifying false as the argument to ordered. In this case any executeBlocking may be
                // executed in parallel on the worker pool."
                /* ordered = */ false,

                //
                // Async result handler
                res -> {
                    if (res.failed()) {
                        // An uncaught exception was thrown from the blocking handler
                        routingContext.fail(res.cause());
                    }
                });
    });

    server.requestHandler(router::accept);

    Log.info("Starting " + SERVER_IDENTIFIER + " on port " + port);
    server.listen(port);
    Log.info(SERVER_IDENTIFIER + " started at " + uri + "/");
    return this;
}

From source file:gribbit.util.Log.java

License:Open Source License

/** Produce log line in Common Log Format -- https://en.wikipedia.org/wiki/Common_Log_Format */
private static String produceLogLine(HttpServerRequest request, Response response) {
    StringBuilder buf = new StringBuilder();
    buf.append(request == null ? "-" : request.remoteAddress());
    buf.append(" - - [");
    buf.append(ZonedDateTime.now().format(LOG_TIME_FORMATTER));
    buf.append("] \"");
    buf.append(request == null ? "-" : request.method());
    buf.append(' ');
    buf.append(request == null ? "-" : request.uri());
    buf.append(' ');
    buf.append('-'); // Not sure how to read HTTP version from vertx request
    buf.append("\" ");
    buf.append(response == null ? "-" : Integer.toString(response.getStatus().code()));
    buf.append(' ');
    buf.append("-"); // Content-Length is calculated by Vert.x, so is unknown here
    return buf.toString();
}

From source file:gribbit.util.Log.java

License:Open Source License

public static void request(HttpServerRequest request, Response response) {
    // Don't log favicon requests
    if (!FAVICON_PATTERN.matcher(request.uri()).matches()) {
        String msg = produceLogLine(request, response);
        logger.log(Level.INFO, msg);
    }/*w w  w  .j  a v a2  s.c om*/
}

From source file:gribbit.util.Log.java

License:Open Source License

public static void request(HttpServerRequest request, Response response, Exception exception) {
    // Don't log favicon requests
    if (!FAVICON_PATTERN.matcher(request.uri()).matches()) {
        String msg = produceLogLine(request, response);
        logger.log(Level.INFO, msg, exception);
    }//from   w w w . java2s.  c o m
}