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

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

Introduction

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

Prototype

@Nullable
String path();

Source Link

Usage

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

License:Apache License

@Override
public String getRpcName(HttpServerRequest request) {
    return request.path();
}

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

License:Apache License

private Trace createTrace(final HttpServerRequest request) {
    final String requestURI = request.path();
    if (requestURI != null && excludeUrlFilter.filter(requestURI)) {
        // skip request.
        if (isTrace) {
            logger.trace("filter requestURI:{}", requestURI);
        }/*from  w  w w . jav a 2  s . c  om*/
        return null;
    }

    final boolean sampling = samplingEnable(request);
    if (!sampling) {
        final Trace trace = traceContext.disableSampling();
        if (isDebug) {
            logger.debug("Remote call sampling flag found. skip trace requestUrl:{}, remoteAddr:{}",
                    request.path(), request.remoteAddress());
        }
        if (!initScope(trace)) {
            // invalid scope.
            deleteTrace(trace);
            return null;
        }

        return trace;
    }

    final TraceId traceId = populateTraceIdFromRequest(request);
    if (traceId != null) {
        final Trace trace = traceContext.continueAsyncTraceObject(traceId);
        if (trace.canSampled()) {
            final SpanRecorder recorder = trace.getSpanRecorder();
            recordRootSpan(recorder, request);
            if (isDebug) {
                logger.debug("TraceID exist. continue trace. traceId:{}, requestUrl:{}, remoteAddr:{}", traceId,
                        request.path(), request.remoteAddress());
            }
        } else {
            if (isDebug) {
                logger.debug(
                        "TraceID exist. camSampled is false. skip trace. traceId:{}, requestUrl:{}, remoteAddr:{}",
                        traceId, request.path(), request.remoteAddress());
            }
        }
        if (!initScope(trace)) {
            // invalid scope.
            deleteTrace(trace);
            return null;
        }

        return trace;
    } else {
        // make asynchronous trace.
        final Trace trace = traceContext.newAsyncTraceObject();
        if (trace.canSampled()) {
            final SpanRecorder recorder = trace.getSpanRecorder();
            recordRootSpan(recorder, request);
            if (isDebug) {
                logger.debug("TraceID not exist. start new trace. requestUrl:{}, remoteAddr:{}", request.path(),
                        request.remoteAddress());
            }
        } else {
            if (isDebug) {
                logger.debug("TraceID not exist. camSampled is false. skip trace. requestUrl:{}, remoteAddr:{}",
                        request.path(), request.remoteAddress());
            }
        }

        if (!initScope(trace)) {
            // invalid scope.
            deleteTrace(trace);
            return null;
        }

        return trace;
    }
}

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

License:Apache License

private void recordRootSpan(final SpanRecorder recorder, final HttpServerRequest request) {
    // root/*from   www  .j  a v a  2  s  .  c  om*/
    recorder.recordServiceType(VertxConstants.VERTX_HTTP_SERVER);
    final String requestURL = request.path();
    if (requestURL != null) {
        recorder.recordRpcName(requestURL);
    }

    if (request.localAddress() != null) {
        final int port = request.localAddress().port();
        if (port <= 0) {
            recorder.recordEndPoint(request.host());
        } else {
            recorder.recordEndPoint(request.host() + ":" + port);
        }
    }

    final String remoteAddr = remoteAddressResolver.resolve(request);
    recorder.recordRemoteAddress(remoteAddr);

    if (!recorder.isRoot()) {
        recordParentInfo(recorder, request);
    }
    recorder.recordApi(VERTX_HTTP_SERVER_METHOD_DESCRIPTOR);

    // record proxy HTTP header.
    this.proxyHttpHeaderRecorder.record(recorder, new ProxyHttpHeaderHandler() {
        @Override
        public String read(String name) {
            return request.getHeader(name);
        }
    });
}

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

License:Apache License

/**
 * Starts the server to listen on the configured port.
 *///from   w  w w.j  a v a 2 s. c o m
public void start() {
    if (vertx == null) {
        vertx = Vertx.vertx();
    }

    srvVertx = vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
        public void handle(HttpServerRequest pRequest) {
            String sPath = pRequest.path();

            if (sPath.equals(sServicePath)) {
                handleService(pRequest);
            } else if (sPath.equals(sUploadPath)) {
                handleUpload(pRequest);
            } else if (sPath.equals(sDownloadPath)) {
                handleDownload(pRequest);
            } else {
                pRequest.response().sendFile(sWebContentPath + pRequest.path());
            }
        }
    });

    srvVertx.listen(iPort, sInterface);
}

From source file:io.advantageous.qbit.vertx.http.server.VertxServerUtils.java

License:Apache License

public HttpRequest createRequest(final HttpServerRequest request, final Supplier<Buffer> buffer,
        final Map<String, Object> data, final CopyOnWriteArrayList<HttpResponseDecorator> decorators,
        final HttpResponseCreator httpResponseCreator) {

    final MultiMap<String, String> headers = request.headers().size() == 0 ? MultiMap.empty()
            : new MultiMapWrapper(request.headers());
    final String contentType = request.headers().get("Content-Type");

    final String contentLengthHeaderValue = request.headers().get("Content-Length");
    final int contentLength = contentLengthHeaderValue == null ? 0 : Integer.parseInt(contentLengthHeaderValue);
    final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder();
    buildParams(httpRequestBuilder, request, contentType);
    final MultiMap<String, String> params = httpRequestBuilder.getParams();
    final String requestPath = request.path();

    httpRequestBuilder.setId(requestId.incrementAndGet()).setContentLength(contentLength).setData(data)
            .setUri(requestPath).setMethod(request.method().toString())
            .setBodySupplier(() -> buffer == null ? null : buffer.get().getBytes())
            .setRemoteAddress(request.remoteAddress().toString())
            .setResponse(createResponse(requestPath, request.method().toString(), headers, params,
                    request.response(), decorators, httpResponseCreator))
            .setTimestamp(time == 0L ? Timer.timer().now() : time).setHeaders(headers);

    return httpRequestBuilder.build();
}

From source file:io.apiman.gateway.platforms.vertx3.http.HttpApiFactory.java

License:Apache License

private static void parsePath(HttpServerRequest request, ApiRequest apimanRequest) {
    // NB: The apiman version of the headers has already been parsed, so the headers have already been filtered/modified.
    // Therefore we wrap the original inbound headers (just get) to efficiently access the necessary data.
    ApiRequestPathInfo parsedPath = requestPathParser.parseEndpoint(request.path(),
            wrapMultiMap(request.headers()));
    apimanRequest.setApiOrgId(parsedPath.orgId);
    apimanRequest.setApiId(parsedPath.apiId);
    apimanRequest.setApiVersion(parsedPath.apiVersion);
    apimanRequest.setUrl(request.absoluteURI());
    apimanRequest.setDestination(parsedPath.resource);
}

From source file:io.apiman.gateway.platforms.vertx3.http.HttpServiceFactory.java

License:Apache License

private static void mungePath(HttpServerRequest request, VertxServiceRequest apimanRequest) {
    ServiceRequestPathInfo parsedPath = ApimanPathUtils.parseServiceRequestPath(
            request.getHeader(ApimanPathUtils.X_API_VERSION_HEADER),
            request.getHeader(ApimanPathUtils.ACCEPT_HEADER), request.path());

    apimanRequest.setServiceOrgId(parsedPath.orgId);
    apimanRequest.setServiceId(parsedPath.serviceId);
    apimanRequest.setServiceVersion(parsedPath.serviceVersion);
    apimanRequest.setUrl(request.absoluteURI());
    apimanRequest.setDestination(parsedPath.resource);

    if (apimanRequest.getServiceOrgId() == null) {
        throw new IllegalArgumentException("Invalid endpoint provided: " + request.path());
    }//from   w w w  .  j  a  v a 2 s .com
}

From source file:io.gravitee.am.gateway.handler.vertx.auth.handler.impl.RedirectAuthHandlerImpl.java

License:Apache License

@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
    Session session = context.session();
    if (session != null) {
        try {/*from   w  w w  . j a  v  a  2 s. c  om*/
            // Save current request in session - we'll get redirected back here after successful login
            HttpServerRequest request = context.request();
            session.put(returnURLParam,
                    UriBuilderRequest
                            .resolveProxyRequest(new io.vertx.reactivex.core.http.HttpServerRequest(request),
                                    request.path(),
                                    request.params().entries().stream()
                                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)),
                                    true, false));

            // Now redirect to the login url
            String uri = UriBuilderRequest.resolveProxyRequest(
                    new io.vertx.reactivex.core.http.HttpServerRequest(request), loginRedirectURL,
                    Collections.singletonMap(OAuth2Constants.CLIENT_ID,
                            request.getParam(OAuth2Constants.CLIENT_ID)),
                    false, false);

            handler.handle(Future.failedFuture(new HttpStatusException(302, uri)));
        } catch (Exception e) {
            logger.warn("Failed to decode login redirect url", e);
            handler.handle(Future.failedFuture(new HttpStatusException(302, loginRedirectURL)));
        }
    } else {
        handler.handle(Future.failedFuture("No session - did you forget to include a SessionHandler?"));
    }
}

From source file:io.nitor.api.backend.lambda.LambdaHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    final String path = normalizePath(sreq.path(), routeLength);
    if (path == null) {
        ctx.response().setStatusCode(NOT_FOUND.code()).end();
        return;//  w  w  w  . ja  v a  2s . c o m
    }
    HttpServerResponse sres = ctx.response();
    PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path);
    final String lambdaFunction, qualifier;
    if (matchRes == null) {
        logger.error("No matching path template");
        sres.setStatusCode(BAD_GATEWAY.code());
        return;
    } else {
        lambdaFunction = matchRes.getValue().getKey();
        qualifier = matchRes.getValue().getValue();
    }
    sreq.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer event) {
            byte[] body = event.getBytes();
            APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent();
            /*
            * Handle body
            */
            String bodyObjStr = null;
            boolean isBase64Encoded = true;
            if (body != null && body.length > 0) {
                String ct = sreq.getHeader("content-type").toLowerCase();
                if (ct.startsWith("text/") || ct.startsWith("application/json")
                        || (ct.indexOf("charset=") > 0)) {
                    String charset = "utf-8";
                    if (ct.indexOf("charset=") > 0) {
                        charset = getCharsetFromContentType(ct);
                    }
                    try {
                        bodyObjStr = Charset.forName(charset).newDecoder()
                                .onMalformedInput(CodingErrorAction.REPORT)
                                .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body))
                                .toString();
                        isBase64Encoded = false;
                    } catch (CharacterCodingException e) {
                        logger.error("Decoding body failed", e);
                    }
                }
                if (bodyObjStr == null) {
                    bodyObjStr = Base64.getEncoder().encodeToString(body);
                }
                reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded);
            }
            Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey())));
            Map<String, String> headerValue = sreq.headers().entries().stream()
                    .collect(toMap(Entry::getKey, Entry::getValue));

            /*
            * Handle request context
            */
            RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx))
                    .withUserAgent(sreq.getHeader(USER_AGENT));
            if (ctx.user() != null) {
                reqId.withUser(ctx.user().principal().toString());
            }
            ProxyRequestContext reqCtx = new ProxyRequestContext()
                    .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString())
                    .withIdentity(reqId);
            reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue)
                    .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path)
                    .withQueryStringParameters(splitQuery(sreq.query()))
                    .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query()))
                    .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx);
            String reqStr = JsonObject.mapFrom(reqObj).toString();
            byte[] sendBody = reqStr.getBytes(UTF_8);
            InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE)
                    .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody))
                    .build();
            logger.info("Calling lambda " + lambdaFunction + ":" + qualifier);
            logger.debug("Payload: " + reqStr);
            CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req);
            respFuture.whenComplete((iresp, err) -> {
                if (iresp != null) {
                    try {
                        String payload = iresp.payload().asString(UTF_8);
                        JsonObject resp = new JsonObject(payload);
                        int statusCode = resp.getInteger("statusCode");
                        sres.setStatusCode(statusCode);
                        for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) {
                            sres.putHeader(next.getKey(), next.getValue().toString());
                        }
                        String respBody = resp.getString("body");
                        byte[] bodyArr = new byte[0];
                        if (body != null && !respBody.isEmpty()) {
                            if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) {
                                bodyArr = Base64.getDecoder().decode(body);
                            } else {
                                bodyArr = respBody.getBytes(UTF_8);
                            }
                        }
                        sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length));
                        Buffer buffer = Buffer.buffer(bodyArr);
                        tryToCacheContent(ctx, buffer);
                        sres.write(buffer);
                    } catch (Throwable t) {
                        logger.error("Error processing lambda request", t);
                        if (!sres.headWritten()) {
                            sres.setStatusCode(BAD_GATEWAY.code());
                            sres.putHeader(CONTENT_TYPE, "application/json");
                            Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString());
                            sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                            sres.write(response);
                        }
                    } finally {
                        sres.end();
                    }
                } else {
                    logger.error("Error processing lambda request", err);
                    sres.setStatusCode(BAD_GATEWAY.code());
                    sres.putHeader(CONTENT_TYPE, "application/json");
                    Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString());
                    sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length()));
                    sres.end(response);
                }
            });
        }
    });
}

From source file:io.nitor.api.backend.msgraph.GraphQueryHandler.java

License:Apache License

@Override
public void handle(RoutingContext ctx) {
    HttpServerRequest sreq = ctx.request();
    String path = sreq.path();
    path = path.substring(routeLength);//  w ww  . j av  a2  s  . c  o  m
    if (!path.startsWith("/")) {
        path = '/' + path;
    }
    path = baseUrl + path + paramsOf(ctx.request().absoluteURI());

    Map<String, String> data = sessionHandler.getSessionData(ctx);
    String refreshToken = data.get(GRAPH_ACCESS_TOKEN_KEY);
    Future<TokenData> tokenFuture = tokenCache.getAccessToken(refreshToken);

    HttpServerResponse sres = ctx.response();
    String finalPath = path;
    tokenFuture.setHandler(tokenResult -> {
        if (tokenResult.failed()) {
            sessionHandler.removeCookie(ctx);
            String err = tokenResult.cause().toString();
            logger.error(err);
            sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).end(err);
            return;
        }
        TokenData token = tokenResult.result();
        if (!refreshToken.equals(token.refreshToken)) {
            Map<String, String> newData = new HashMap<>(data);
            newData.put(GRAPH_ACCESS_TOKEN_KEY, token.refreshToken);
            sessionHandler.setSessionData(ctx, newData);
        }
        String clientRequestId = UUID.randomUUID().toString();
        logger.info("Querying " + sreq.method() + " " + finalPath + " [" + clientRequestId + "]");
        HttpClientRequest creq = httpClient.requestAbs(sreq.method(), finalPath)
                .putHeader(AUTHORIZATION, "Bearer " + token.accessToken).putHeader(ACCEPT, APPLICATION_JSON)
                .putHeader("client-request-id", clientRequestId).setTimeout(SECONDS.toMillis(20))
                .exceptionHandler(err -> {
                    logger.error("Graph query failed [" + clientRequestId + "]", err);
                    if (!sres.ended()) {
                        sres.setStatusCode(INTERNAL_SERVER_ERROR.code()).write("Graph query failed: " + err)
                                .end();
                    }
                });

        for (String header : allowedRequestHeaders) {
            ofNullable(sreq.getHeader(header)).ifPresent(value -> creq.putHeader(header, value));
        }
        if (sres.headers().getAll("transfer-encoding").stream().anyMatch(v -> v.equals("chunked"))) {
            creq.setChunked(true);
        }

        sres.closeHandler(close -> creq.connection().close());
        creq.handler(cres -> mapResponse(cres, sres, clientRequestId));

        if (sreq.isEnded()) {
            creq.end();
        } else {
            sreq.endHandler(v -> {
                try {
                    creq.end();
                } catch (IllegalStateException ex) {
                    // ignore - nothing can be done - the request is already complete/closed - TODO log?
                }
            });
            Pump resPump = Pump.pump(sreq, creq);
            resPump.start();
        }
    });
}