Example usage for io.netty.handler.codec.http QueryStringDecoder decodeComponent

List of usage examples for io.netty.handler.codec.http QueryStringDecoder decodeComponent

Introduction

In this page you can find the example usage for io.netty.handler.codec.http QueryStringDecoder decodeComponent.

Prototype

public static String decodeComponent(final String s) 

Source Link

Document

Decodes a bit of a URL encoded by a browser.

Usage

From source file:com.buildria.mocking.stub.Call.java

License:Open Source License

public static Call fromRequest(HttpRequest req) {
    Objects.requireNonNull(req);/*from w ww. j a v a  2s .c om*/
    Call call = new Call();

    call.method = req.getMethod().name();
    QueryStringDecoder decoder = new QueryStringDecoder(req.getUri());
    call.path = QueryStringDecoder.decodeComponent(decoder.path());

    Map<String, List<String>> params = decoder.parameters();
    for (String name : params.keySet()) {
        List<String> values = params.get(name);
        for (String value : values) {
            call.parameters.add(new Pair(name, value));
        }
    }

    HttpHeaders headers = req.headers();
    for (String name : headers.names()) {
        List<String> values = headers.getAll(name);
        for (String value : values) {
            call.headers.add(new Pair(name, value));
        }
        if (CONTENT_TYPE.equalsIgnoreCase(name)) {
            call.contentType = MediaType.parse(headers.get(CONTENT_TYPE));
        }
    }

    if (req instanceof ByteBufHolder) {
        ByteBuf buf = ((ByteBufHolder) req).content();
        if (buf != null) {
            call.body = new byte[buf.readableBytes()];
            buf.readBytes(call.body);
        }
    }

    return call;
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    Operation request = null;/*www  . j  a va 2 s . com*/
    Integer streamId = null;
    try {

        // Start of request processing, initialize in-bound operation
        FullHttpRequest nettyRequest = (FullHttpRequest) msg;
        long expMicros = Utils.getNowMicrosUtc() + this.host.getOperationTimeoutMicros();
        URI targetUri = new URI(nettyRequest.uri()).normalize();
        request = Operation.createGet(null);
        request.setAction(Action.valueOf(nettyRequest.method().toString())).setExpiration(expMicros);

        String query = targetUri.getQuery();
        if (query != null && !query.isEmpty()) {
            query = QueryStringDecoder.decodeComponent(targetUri.getQuery());
        }

        URI uri = new URI(UriUtils.HTTP_SCHEME, targetUri.getUserInfo(), ServiceHost.LOCAL_HOST,
                this.host.getPort(), targetUri.getPath(), query, null);
        request.setUri(uri);

        // @see OperationOption.SEND_WITH_CALLBACK
        String callbackLocation = getAndRemove(nettyRequest.headers(),
                Operation.REQUEST_CALLBACK_LOCATION_HEADER);
        URI callbackUri = null;

        if (callbackLocation == null) {
            // The streamId will be null for HTTP/1.1 connections, and valid for HTTP/2 connections
            streamId = nettyRequest.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        } else {
            request.setReferer(callbackLocation);
            callbackUri = new URI(callbackLocation);
        }

        if (streamId == null) {
            ctx.channel().attr(NettyChannelContext.OPERATION_KEY).set(request);
        }

        if (nettyRequest.decoderResult().isFailure()) {
            request.setStatusCode(Operation.STATUS_CODE_BAD_REQUEST).setKeepAlive(false);
            request.setBody(ServiceErrorResponse
                    .create(new IllegalArgumentException(ERROR_MSG_DECODING_FAILURE), request.getStatusCode()));
            sendResponse(ctx, request, streamId);
            return;
        }

        parseRequestHeaders(ctx, request, nettyRequest);

        if (callbackLocation != null) {
            Operation localOp = request.clone();
            // complete remote operation eagerly. We will PATCH the callback location with the
            // result when the local operation completes
            request.setStatusCode(Operation.STATUS_CODE_ACCEPTED).setBody(null);
            sendResponse(ctx, request, null);
            request = localOp;
        }

        decodeRequestBody(ctx, request, nettyRequest.content(), streamId, callbackUri);
    } catch (Throwable e) {
        this.host.log(Level.SEVERE, "Uncaught exception: %s", Utils.toString(e));
        if (request == null) {
            request = Operation.createGet(this.host.getUri());
        }
        int sc = Operation.STATUS_CODE_BAD_REQUEST;
        if (e instanceof URISyntaxException) {
            request.setUri(this.host.getUri());
        }
        request.setKeepAlive(false).setStatusCode(sc).setBodyNoCloning(ServiceErrorResponse.create(e, sc));
        sendResponse(ctx, request, streamId);
    }
}

From source file:divconq.web.Request.java

License:Open Source License

public void load(ChannelHandlerContext ctx, HttpRequest req) {
    this.method = req.getMethod();
    this.headers = req.headers();

    String value = req.headers().get(Names.COOKIE);

    if (StringUtil.isNotEmpty(value)) {
        Set<Cookie> cset = CookieDecoder.decode(value);

        for (Cookie cookie : cset)
            this.cookies.put(cookie.getName(), cookie);
    }/*from w ww.j a  v a2  s.co  m*/

    QueryStringDecoder decoderQuery = new QueryStringDecoder(req.getUri());
    this.parameters = decoderQuery.parameters(); // TODO decode
    this.path = new CommonPath(QueryStringDecoder.decodeComponent(decoderQuery.path()));
    this.orgpath = this.path;

    this.contentType = new ContentTypeParser(this.headers.get(Names.CONTENT_TYPE));
}

From source file:io.vertx.ext.web.handler.sockjs.impl.JsonPTransport.java

License:Open Source License

private void handleSend(RoutingContext rc, SockJSSession session) {
    rc.request().bodyHandler(buff -> {
        String body = buff.toString();

        boolean urlEncoded;
        String ct = rc.request().getHeader("content-type");
        if ("application/x-www-form-urlencoded".equalsIgnoreCase(ct)) {
            urlEncoded = true;// www. j a  v  a 2s  .co m
        } else if ("text/plain".equalsIgnoreCase(ct)) {
            urlEncoded = false;
        } else {
            rc.response().setStatusCode(500);
            rc.response().end("Invalid Content-Type");
            return;
        }

        if (body.equals("") || urlEncoded && (!body.startsWith("d=") || body.length() <= 2)) {
            rc.response().setStatusCode(500).end("Payload expected.");
            return;
        }

        if (urlEncoded) {
            body = QueryStringDecoder.decodeComponent(body).substring(2);
        }

        if (!session.handleMessages(body)) {
            sendInvalidJSON(rc.response());
        } else {
            setJSESSIONID(options, rc);
            rc.response().putHeader("Content-Type", "text/plain; charset=UTF-8");
            setNoCacheHeaders(rc);
            rc.response().end("ok");
            if (log.isTraceEnabled())
                log.trace("send handled ok");
        }
    });
}

From source file:org.glowroot.ui.JvmJsonService.java

License:Apache License

private static String getServerId(String queryString) {
    return QueryStringDecoder.decodeComponent(queryString.substring("server-id".length() + 1));
}

From source file:org.wso2.carbon.uuf.connector.ms.MicroserviceHttpRequest.java

License:Open Source License

public MicroserviceHttpRequest(io.netty.handler.codec.http.HttpRequest request, byte[] contentBytes) {
    this.url = null; // Netty HttpRequest does not have a 'getUrl()' method.
    this.method = request.getMethod().name();
    this.protocol = request.getProtocolVersion().text();
    this.headers = request.headers().entries().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    String rawUri = request.getUri();
    int uriPathEndIndex = rawUri.indexOf('?');
    String rawUriPath, rawQueryString;
    if (uriPathEndIndex == -1) {
        rawUriPath = rawUri;// w  w w .j a  v  a  2 s . co m
        rawQueryString = null;
    } else {
        rawUriPath = rawUri.substring(0, uriPathEndIndex);
        rawQueryString = rawUri.substring(uriPathEndIndex + 1, rawUri.length());
    }
    this.uri = QueryStringDecoder.decodeComponent(rawUriPath);
    this.appContext = UriUtils.getAppContext(this.uri);
    this.uriWithoutAppContext = UriUtils.getUriWithoutAppContext(this.uri);
    this.queryString = rawQueryString; // Query string is not very useful, so we don't bother to decode it.
    if (rawQueryString != null) {
        HashMap<String, Object> map = new HashMap<>();
        new QueryStringDecoder(rawQueryString, false).parameters()
                .forEach((key, value) -> map.put(key, (value.size() == 1) ? value.get(0) : value));
        this.queryParams = map;
    } else {
        this.queryParams = Collections.emptyMap();
    }
    if (contentBytes != null) {
        this.contentBytes = contentBytes;
        this.contentLength = contentBytes.length;
        this.inputStream = new ByteArrayInputStream(contentBytes);
    } else {
        this.contentBytes = null;
        this.contentLength = 0;
        this.inputStream = null;
    }
}

From source file:org.wso2.carbon.uuf.httpconnector.msf4j.MicroserviceHttpRequest.java

License:Open Source License

public MicroserviceHttpRequest(Request request, MultivaluedMap<String, ?> postParams) {
    this.msf4jRequest = request;
    this.method = request.getHttpMethod();

    // process URI
    String rawUri = request.getUri();
    int uriPathEndIndex = rawUri.indexOf('?');
    String rawUriPath, rawQueryString;
    if (uriPathEndIndex == -1) {
        rawUriPath = rawUri;//from  w  w w  .j  a v  a  2 s  .c om
        rawQueryString = null;
    } else {
        rawUriPath = rawUri.substring(0, uriPathEndIndex);
        rawQueryString = rawUri.substring(uriPathEndIndex + 1, rawUri.length());
    }
    this.uri = QueryStringDecoder.decodeComponent(rawUriPath);
    this.contextPath = HttpRequest.getContextPath(this.uri);
    this.uriWithoutContextPath = HttpRequest.getUriWithoutContextPath(this.uri);
    this.queryString = rawQueryString; // Query string is not very useful, so we don't bother to decode it.
    if (rawQueryString != null) {
        HashMap<String, Object> map = new HashMap<>();
        new QueryStringDecoder(rawQueryString, false).parameters()
                .forEach((key, value) -> map.put(key, (value.size() == 1) ? value.get(0) : value));
        this.queryParams = map;
    } else {
        this.queryParams = Collections.emptyMap();
    }

    // process headers and cookies
    this.headers = new HashMap<>();
    request.getHeaders().getAll().forEach(header -> this.headers.put(header.getName(), header.getValue()));
    String cookieHeader = this.headers.get(HttpHeaders.COOKIE);
    this.cookies = (cookieHeader == null) ? Collections.emptyMap()
            : ServerCookieDecoder.STRICT.decode(cookieHeader).stream()
                    .collect(Collectors.toMap(Cookie::name, c -> c));

    // process form POST form data
    if (postParams == null) {
        this.formParams = Collections.emptyMap();
        this.files = Collections.emptyMap();
    } else {
        this.formParams = new HashMap<>();
        this.files = new HashMap<>();
        for (Map.Entry<String, ? extends List<?>> entry : postParams.entrySet()) {
            List<?> values = entry.getValue();
            if (values.isEmpty()) {
                continue;
            }
            if (values.get(0) instanceof File) {
                this.files.put(entry.getKey(), (values.size() == 1) ? values.get(0) : values);
            } else {
                this.formParams.put(entry.getKey(), (values.size() == 1) ? values.get(0) : values);
            }
        }
    }
}

From source file:ratpack.path.internal.TokenPathBinder.java

License:Apache License

private String decodeURIComponent(String s) {
    try {//from  ww  w  . java 2  s  . com
        return QueryStringDecoder.decodeComponent(s.replace("+", "%2B"));
    } catch (IllegalArgumentException cause) {
        throw new InvalidPathEncodingException(cause);
    }
}