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

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

Introduction

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

Prototype

@Nullable
String query();

Source Link

Usage

From source file:de.braintags.netrelay.RequestUtil.java

License:Open Source License

/**
 * Creates a url from the given information for a redirect. If request is not null, then current query parameters are
 * added to the path/* w w  w. j ava  2 s .c  om*/
 * 
 * @param context
 * @param path
 * @param reuseArguments
 *          if true, the query parameters of the current request are reused
 * @return
 */
public static String createRedirectUrl(RoutingContext context, String path, boolean reuseArguments) {
    String tmpPath = path;
    HttpServerRequest request = context.request();
    if (request != null && reuseArguments) {
        String qp = request.query();
        if (qp != null && qp.hashCode() != 0) {
            tmpPath += (path.indexOf('?') < 0 ? "?" : "&") + qp;
        }
    }
    String prePath = context.get(PREPATH_PROPERTY);
    if (prePath != null) {
        tmpPath = prePath + ((prePath.endsWith("/") || tmpPath.startsWith("/")) ? "" : "/") + tmpPath;
    }
    return tmpPath;
}

From source file:io.apiman.rls.vertx.RlsRestVerticle.java

License:Apache License

/**
 * Gets a request query paramter and converts it to the given data type.
 * @param request// w  ww . j a va  2s.  co  m
 * @param paramName
 */
private static <T> T getQueryParam(HttpServerRequest request, String paramName, Class<T> type, T defaultValue) {
    String query = request.query();
    Map<String, String> queryMap = parseQuery(query);
    String paramValue = queryMap.get(paramName);
    if (paramValue == null || paramValue.trim().isEmpty()) {
        return defaultValue;
    }
    try {
        return type.getConstructor(String.class).newInstance(paramValue);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        return defaultValue;
    }
}

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;//from  w  w w . ja  v a 2s.co 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:org.apache.servicecomb.transport.rest.vertx.accesslog.element.impl.QueryStringItem.java

License:Apache License

@Override
public String getFormattedItem(AccessLogParam<RoutingContext> accessLogParam) {
    HttpServerRequest request = accessLogParam.getContextData().request();
    if (null == request) {
        return EMPTY_RESULT;
    }//w w w  . j  a va2s.  c o m

    String query = request.query();
    if (StringUtils.isEmpty(query)) {
        return EMPTY_RESULT;
    }
    return query;
}

From source file:org.sfs.util.HttpServerRequestHeaderToJsonObject.java

License:Apache License

public static JsonObject call(HttpServerRequest httpServerRequest) {
    JsonObject jsonObject = new JsonObject();

    String query = httpServerRequest.query();
    String requestLine = String.format("%s %s%s %s", httpServerRequest.method(), httpServerRequest.path(),
            query != null ? '?' + query : "", httpServerRequest.version().toString());
    jsonObject.put("request_line", requestLine);
    MultiMap headers = httpServerRequest.headers();
    JsonArray jsonHeaders = new JsonArray();
    for (String headerName : headers.names()) {
        List<String> values = headers.getAll(headerName);
        JsonObject jsonHeader = new JsonObject();
        jsonHeader.put(headerName, values);
        jsonHeaders.add(jsonHeader);/*from w  ww.j a  v a  2s.  c  o m*/
    }
    jsonObject.put("headers", jsonHeaders);
    return jsonObject;
}

From source file:org.sfs.util.SfsHttpUtil.java

License:Apache License

public static String getRemoteRequestUrl(HttpServerRequest httpServerRequest) {
    String path = httpServerRequest.path();
    String query = httpServerRequest.query();

    String serviceUrl = getRemoteServiceUrl(httpServerRequest);
    return String.format("%s/%s%s", serviceUrl, path, query != null ? ("?" + query) : "");
}