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

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

Introduction

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

Prototype

public Map<String, List<String>> parameters() 

Source Link

Document

Returns the decoded key-value parameter pairs of the URI.

Usage

From source file:eastwind.webpush.WebPushHandler.java

License:Apache License

private void handleHttpOper(ChannelHandlerContext ctx, FullHttpRequest req, Session s, String oper)
        throws JsonProcessingException {
    String uid = s.getUid();//ww  w. ja  v a 2  s .c om
    if (oper.equals("registers")) {
        QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
        List<String> types = decoder.parameters().get("type");
        s.registerTypes(types);
        if (types != null) {
            logger.debug("registers:{}-{}", uid, objectMapper.writeValueAsString(types));
        }
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer("{}", Charset.forName("utf-8"))));
    } else if (oper.equals("register")) {
        QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
        List<String> types = decoder.parameters().get("type");
        if (types != null && types.size() > 0) {
            s.registerType(types.get(0));
            logger.debug("register:{}-{}", uid, types.get(0));
        }
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.copiedBuffer("{}", Charset.forName("utf-8"))));
    } else if (oper.equals("cancel")) {
        s.setCanceled();
        sessionManager.get(uid).remove(s);
        logger.debug("cancel:{}-{}", uid, s.getUuid());
    }
}

From source file:edu.upennlib.redirect.RedirectHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    QueryStringDecoder orig = new QueryStringDecoder(msg.getUri());
    List<String> vals = orig.parameters().get(REDIRECT_PARAM_KEY);
    String val;
    if (vals == null || vals.isEmpty() || (val = vals.get(0)) == null) {
        badRequest("no redirect specified", ctx);
        return;// w  ww.  jav  a 2s . c om
    }
    Matcher m = PRE_PATH.matcher(val);
    String parsed = null;
    if (!m.find() || !validHosts.contains(parsed = m.group())) {
        badRequest("redirect not permitted: " + val + ", parsed=" + parsed, ctx);
        return;
    }
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
    resp.headers().add(LOCATION, val);
    resp.headers().add(CONNECTION, CLOSE);
    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}

From source file:fileShare.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        System.out.println("==================================HttpRequest==================================");
        System.out.println(msg.toString());
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);/* w  w  w  .  j  av  a  2 s .  co m*/
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                System.out.println(
                        "==================================HttpContent==================================");
                //?
                System.out.println(new String(((DefaultHttpContent) chunk).content().array()));
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:holon.internal.http.netty.HttpUploadServerHandlerTempl.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);/*from  w w w .  ja  v  a 2 s. c o  m*/
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        if (request.getMethod().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }

        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:holon.internal.http.netty.NettyRequestContext.java

License:Open Source License

@Override
public Map<String, Iterable<String>> queryParams() {
    if (queryParams == null) {
        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        queryParams = decoderQuery.parameters();
    }//from  w w  w  .  j  a  v a 2 s .  c o m
    return (Map) queryParams;
}

From source file:io.advantageous.conekt.http.impl.HttpServerRequestImpl.java

License:Open Source License

@Override
public MultiMap params() {
    if (params == null) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri());
        Map<String, List<String>> prms = queryStringDecoder.parameters();
        params = new CaseInsensitiveHeaders();
        if (!prms.isEmpty()) {
            for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                params.add(entry.getKey(), entry.getValue());
            }//from   w  w  w. ja v  a 2 s  .c om
        }
    }
    return params;
}

From source file:io.aos.netty5.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//from   ww  w  .j a  v a2s. co m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:io.aos.netty5.http.upload.HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//from   www .  j  a va 2 s. c o  m
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        for (Entry<String, String> entry : request.headers()) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        if (request.method().equals(HttpMethod.GET)) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So stop here
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            // Not now: LastHttpContent will be sent writeResponse(ctx.channel());
            return;
        }
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        }

        readingChunks = HttpHeaderUtil.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    } else {
        writeResponse(ctx.channel());
    }
}

From source file:io.gravitee.gateway.core.endpoint.resolver.impl.TargetEndpointResolver.java

License:Apache License

private String encode(String uri, MultiValueMap<String, String> parameters, ExecutionContext executionContext) {
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    Map<String, List<String>> queryParameters = decoder.parameters();

    // Merge query parameters from user target into incoming request query parameters
    for (Map.Entry<String, List<String>> param : queryParameters.entrySet()) {
        parameters.put(param.getKey(), param.getValue());
    }// w w w.  j av  a2  s  . co  m

    // Retrieve useRawPath config from ExecutionContext
    Boolean useRawPath = (Boolean) executionContext
            .getAttribute(ExecutionContext.ATTR_ENDPOINT_RESOLVER_USE_RAW_PATH);
    if (Boolean.TRUE.equals(useRawPath)) {
        return decoder.rawPath();
    } else {
        // Path segments must be encoded to avoid bad URI syntax
        String path = decoder.path();
        String[] segments = path.split(URI_PATH_SEPARATOR);
        StringBuilder builder = new StringBuilder();

        for (String pathSeg : segments) {
            builder.append(UrlEscapers.urlPathSegmentEscaper().escape(pathSeg)).append(URI_PATH_SEPARATOR);
        }

        if (path.charAt(path.length() - 1) == URI_PATH_SEPARATOR_CHAR) {
            return builder.toString();
        } else {
            return builder.substring(0, builder.length() - 1);
        }
    }

}

From source file:io.jsync.http.impl.DefaultHttpServerRequest.java

License:Open Source License

@Override
public MultiMap params() {
    if (params == null) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri());
        Map<String, List<String>> prms = queryStringDecoder.parameters();
        params = new CaseInsensitiveMultiMap();
        if (!prms.isEmpty()) {
            for (Map.Entry<String, List<String>> entry : prms.entrySet()) {
                params.add(entry.getKey(), entry.getValue());
            }//from  w  w w.j av  a  2s .  c om
        }
    }
    return params;
}