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:org.waarp.openr66.protocol.http.HttpFormattedHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    isCurrentRequestXml = false;/*from   w  w  w.  j  a v a2 s . c om*/
    isCurrentRequestJson = false;
    status = HttpResponseStatus.OK;
    FullHttpRequest request = this.request = msg;
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
    uriRequest = queryStringDecoder.path();
    logger.debug("Msg: " + uriRequest);
    if (uriRequest.contains("gre/") || uriRequest.contains("img/") || uriRequest.contains("res/")
            || uriRequest.contains("favicon.ico")) {
        HttpWriteCacheEnable.writeFile(request, ctx, Configuration.configuration.getHttpBasePath() + uriRequest,
                "XYZR66NOSESSION");
        return;
    }
    /*try {
       if (DbConstant.admin.isActive) {
      this.dbSession = new DbSession(DbConstant.admin, false);
      DbAdmin.nbHttpSession++;
      this.isPrivateDbSession = true;
       }
    } catch (WaarpDatabaseNoConnectionException e1) {
       // Cannot connect so use default connection
       logger.warn("Use default database connection");
       this.dbSession = DbConstant.admin.session;
    }*/
    try {
        char cval = 'z';
        long nb = LIMITROW;
        // check the URI
        if (uriRequest.equalsIgnoreCase("/active")) {
            cval = '0';
        } else if (uriRequest.equalsIgnoreCase("/error")) {
            cval = '1';
        } else if (uriRequest.equalsIgnoreCase("/done")) {
            cval = '2';
        } else if (uriRequest.equalsIgnoreCase("/all")) {
            cval = '3';
        } else if (uriRequest.equalsIgnoreCase("/status")) {
            cval = '4';
        } else if (uriRequest.equalsIgnoreCase("/statusxml")) {
            cval = '5';
            nb = 0; // since it could be the default or setup by request
            isCurrentRequestXml = true;
        } else if (uriRequest.toLowerCase().startsWith("/spooled")) {
            cval = '6';
        } else if (uriRequest.equalsIgnoreCase("/statusjson")) {
            cval = '7';
            nb = 0; // since it could be the default or setup by request
            isCurrentRequestJson = true;
        }
        // Get the params according to get or post
        if (request.method() == HttpMethod.GET) {
            params = queryStringDecoder.parameters();
        } else if (request.method() == HttpMethod.POST) {
            ByteBuf content = request.content();
            if (content.isReadable()) {
                String param = content.toString(WaarpStringUtils.UTF8);
                queryStringDecoder = new QueryStringDecoder("/?" + param);
            } else {
                responseContent.append(REQUEST.index.readFileUnique(this));
                writeResponse(ctx);
                return;
            }
            params = queryStringDecoder.parameters();
        }
        boolean getMenu = (cval == 'z');
        boolean extraBoolean = false;
        if (!params.isEmpty()) {
            // if not uri, from get or post
            if (getMenu) {
                String info = getTrimValue(sINFO);
                if (info != null) {
                    getMenu = false;
                    cval = info.charAt(0);
                } else {
                    getMenu = true;
                }
            }
            // search the nb param
            String snb = getTrimValue(sNB);
            if (snb != null) {
                try {
                    nb = Long.parseLong(snb);
                } catch (Exception e1) {
                }
            }
            // search the detail param
            String sdetail = getTrimValue(sDETAIL);
            if (sdetail != null) {
                try {
                    if (Integer.parseInt(sdetail) > 0) {
                        extraBoolean = true;
                    }
                } catch (Exception e1) {
                }
            }
            String langarg = getTrimValue("setLng");
            if (langarg != null && !langarg.isEmpty()) {
                lang = langarg;
            }
        }
        if (getMenu) {
            responseContent.append(REQUEST.index.readFileUnique(this));
        } else {
            // Use value 0=Active 1=Error 2=Done 3=All
            switch (cval) {
            case '0':
                active(ctx, (int) nb);
                break;
            case '1':
                error(ctx, (int) nb);
                break;
            case '2':
                done(ctx, (int) nb);
                break;
            case '3':
                all(ctx, (int) nb);
                break;
            case '4':
                status(ctx, (int) nb);
                break;
            case '5':
                statusxml(ctx, nb, extraBoolean);
                break;
            case '6':
                String name = null;
                if (params.containsKey("name")) {
                    name = getTrimValue("name");
                }
                int istatus = 0;
                if (params.containsKey("status")) {
                    String status = getTrimValue("status");
                    try {
                        istatus = Integer.parseInt(status);
                    } catch (NumberFormatException e1) {
                        istatus = 0;
                    }
                }
                if (uriRequest.toLowerCase().startsWith("/spooleddetail")) {
                    extraBoolean = true;
                }
                spooled(ctx, extraBoolean, name, istatus);
                break;
            case '7':
                statusjson(ctx, nb, extraBoolean);
                break;
            default:
                responseContent.append(REQUEST.index.readFileUnique(this));
            }
        }
        writeResponse(ctx);
    } finally {
        if (this.isPrivateDbSession && dbSession != null) {
            dbSession.forceDisconnect();
            DbAdmin.decHttpSession();
            dbSession = null;
        }
    }
}

From source file:org.waarp.openr66.proxy.protocol.http.HttpFormattedHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    isCurrentRequestXml = false;/*from   www .j a  v  a2s .  c  o m*/
    isCurrentRequestJson = false;
    status = HttpResponseStatus.OK;
    FullHttpRequest request = this.request = msg;
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
    uriRequest = queryStringDecoder.path();
    logger.debug("Msg: " + uriRequest);
    if (uriRequest.contains("gre/") || uriRequest.contains("img/") || uriRequest.contains("res/")
            || uriRequest.contains("favicon.ico")) {
        HttpWriteCacheEnable.writeFile(request, ctx, Configuration.configuration.getHttpBasePath() + uriRequest,
                "XYZR66NOSESSION");
        return;
    }
    char cval = 'z';
    long nb = LIMITROW;
    // check the URI
    if (uriRequest.equalsIgnoreCase("/statusxml")) {
        cval = '5';
        nb = 0; // since it could be the default or setup by request
        isCurrentRequestXml = true;
    } else if (uriRequest.equalsIgnoreCase("/statusjson")) {
        cval = '7';
        nb = 0; // since it could be the default or setup by request
        isCurrentRequestJson = true;
    }
    if (request.method() == HttpMethod.GET) {
        params = queryStringDecoder.parameters();
    }
    boolean getMenu = (cval == 'z');
    boolean extraBoolean = false;
    if (!params.isEmpty()) {
        String langarg = getTrimValue("setLng");
        if (langarg != null && !langarg.isEmpty()) {
            lang = langarg;
        }
    }
    if (getMenu) {
        responseContent.append(REQUEST.index.readFileUnique(this));
    } else {
        // Use value 0=Active 1=Error 2=Done 3=All
        switch (cval) {
        case '5':
            statusxml(ctx, nb, extraBoolean);
            break;
        case '7':
            statusjson(ctx, nb, extraBoolean);
            break;
        default:
            responseContent.append(REQUEST.index.readFileUnique(this));
        }
    }
    writeResponse(ctx);
}

From source file:org.wso2.carbon.security.jaas.handler.SAMLCallbackHandler.java

License:Open Source License

@Override
public boolean canHandle() {

    if (httpRequest != null) {

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri());
        Map<String, List<String>> requestParameters = queryStringDecoder.parameters();
        String b64SAMLResponse = requestParameters.get("SAMLResponse").get(0);

        ByteArrayInputStream SAMLResponseInputStream = null;

        try {//w  w  w . j a va  2s  .  c  om
            String responseXml;
            responseXml = new String(org.opensaml.xml.util.Base64.decode(b64SAMLResponse), "UTF-8");
            if (!openSAMLBootstrapped) {
                DefaultBootstrap.bootstrap();
                openSAMLBootstrapped = true;
            }

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
            docBuilder.setEntityResolver((publicId, systemId) -> {
                throw new SAXException("AuthnRequest contains invalid elements. Possibly "
                        + "an XML External Entity (XXE) attack.");
            });
            SAMLResponseInputStream = new ByteArrayInputStream(responseXml.getBytes("UTF8"));
            Document document = docBuilder.parse(SAMLResponseInputStream);

            Element element = document.getDocumentElement();

            UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

            XMLObject xmlObject = unmarshaller.unmarshall(element);
            if (xmlObject instanceof Response) {
                samlAssertion = ((Response) xmlObject).getAssertions().get(0);
            } else if (xmlObject instanceof Assertion) {
                samlAssertion = (Assertion) xmlObject;
            } else {
                return false;
            }

            return true;

        } catch (UnsupportedEncodingException e) {
            //throw new CarbonSecurityException("Error decoding SAML Response", e);
        } catch (ConfigurationException e) {
            //throw new CarbonSecurityException("Failed to bootstrap OpenSAML 2 Library", e);
        } catch (ParserConfigurationException | SAXException | IOException | UnmarshallingException e) {
            //throw new CarbonSecurityException("Failed to parse SAML XML Response", e);
        } finally {
            if (SAMLResponseInputStream != null) {
                try {
                    SAMLResponseInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    return false;
}

From source file:org.wso2.gw.emulator.http.consumer.HttpRequestInformationProcessor.java

License:Open Source License

private void populateQueryParameters(HttpRequest request, HttpRequestContext requestContext) {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
    Map<String, List<String>> params = queryStringDecoder.parameters();
    requestContext.setQueryParameters(params);
}

From source file:ozy.server.ServerHandler.java

License:Open Source License

private void receiveHeader() {
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(_httpRequest.getUri());
    _serviceRequest.setMethod(_httpRequest.getMethod().toString());
    _serviceRequest.setSenderHost(HttpHeaders.getHost(_httpRequest, "unknown"));
    _serviceRequest.setPath(queryStringDecoder.path());
    HttpHeaders headers = _httpRequest.headers();
    if (!headers.isEmpty()) {
        for (Map.Entry<String, String> h : headers) {
            _serviceRequest.headers().put(h.getKey(), h.getValue());
        }//from w  w  w.  jav  a2s  . c  o  m
    }
    Map<String, List<String>> params = queryStringDecoder.parameters();
    if (!params.isEmpty()) {
        for (Entry<String, List<String>> p : params.entrySet()) {
            _serviceRequest.params().put(p.getKey(), p.getValue());
        }
    }
}

From source file:ratpack.session.clientside.internal.DefaultClientSessionService.java

License:Apache License

@Override
public ConcurrentMap<String, Object> deserializeSession(Cookie cookie) {
    ConcurrentMap<String, Object> sessionStorage = new ConcurrentHashMap<>();

    String encodedPairs = cookie == null ? null : cookie.value();
    if (encodedPairs != null) {
        String[] parts = encodedPairs.split(SESSION_SEPARATOR);
        if (parts.length == 2) {
            byte[] urlEncoded = DECODER.decode(parts[0]);
            byte[] digest = DECODER.decode(parts[1]);

            try {
                byte[] expectedDigest = signer.sign(Unpooled.wrappedBuffer(urlEncoded));

                if (Arrays.equals(digest, expectedDigest)) {
                    byte[] message;
                    if (crypto == null) {
                        message = urlEncoded;
                    } else {
                        message = crypto.decrypt(Unpooled.wrappedBuffer(urlEncoded));
                    }/*from w  w w .  j a  v a 2  s  .  c om*/

                    String payload = new String(message, CharsetUtil.UTF_8);
                    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(payload, CharsetUtil.UTF_8,
                            false);
                    Map<String, List<String>> decoded = queryStringDecoder.parameters();
                    for (Map.Entry<String, List<String>> entry : decoded.entrySet()) {
                        String value = entry.getValue().isEmpty() ? null : entry.getValue().get(0);
                        sessionStorage.put(entry.getKey(), value);
                    }
                }
            } catch (Exception e) {
                throw Exceptions.uncheck(e);
            }
        }
    }

    return sessionStorage;
}

From source file:test.httpupload.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;

        URI uri = new URI(request.uri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);//  ww w .ja  v  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.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");
            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 {
                System.out.println("=============================================" + count.incrementAndGet());
            }
        }
    }
}

From source file:test.netty.HttpCollectorServerHandler.java

License:Apache License

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

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);//from  www  .j a  v  a 2s  .c o  m
        }

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

        buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).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.getUri());
        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");
            }

            writeResponse(trailer, ctx);
        }
    }
}

From source file:testserver.routes.Redirect.java

License:Apache License

@Override
public void handle(ChannelHandlerContext ctx, HttpRequest request) {
    QueryStringDecoder qsd = new QueryStringDecoder(request.getUri());
    List<String> newUri = qsd.parameters().get("uri");
    HttpResponse response;/*from www .j a va  2s. co  m*/
    if (newUri == null) {
        response = StdResponses.BADREQUEST.resp();
    } else {
        Statistic.addRedirect(newUri.get(0));
        response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
        response.headers().set(LOCATION, newUri.get(0));
    }
    ctx.writeAndFlush(response).addListener(CLOSE);
}

From source file:uapi.web.http.netty.internal.NettyHttpRequest.java

License:Open Source License

NettyHttpRequest(final ILogger logger, final HttpRequest httpRequest) {
    this._logger = logger;
    this._request = httpRequest;

    HttpHeaders headers = this._request.headers();
    Looper.from(headers.iteratorAsString())
            .foreach(entry -> this._headers.put(entry.getKey().toLowerCase(), entry.getValue()));

    this._uri = this._request.uri();
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this._uri);
    Map<String, List<String>> params = queryStringDecoder.parameters();
    Looper.from(params.entrySet()).foreach(entry -> this._params.put(entry.getKey(), entry.getValue()));

    HttpVersion version = this._request.protocolVersion();
    if (HttpVersion.HTTP_1_0.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_0;
    } else if (HttpVersion.HTTP_1_1.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_1;
    } else {/*  w  ww  .  ja v a  2 s.  c  o  m*/
        throw new KernelException("Unsupported Http version - {}", version);
    }

    HttpMethod method = this._request.method();
    if (HttpMethod.GET.equals(method)) {
        this._method = uapi.web.http.HttpMethod.GET;
    } else if (HttpMethod.PUT.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PUT;
    } else if (HttpMethod.POST.equals(method)) {
        this._method = uapi.web.http.HttpMethod.POST;
    } else if (HttpMethod.PATCH.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PATCH;
    } else if (HttpMethod.DELETE.equals(method)) {
        this._method = uapi.web.http.HttpMethod.DELETE;
    } else {
        throw new KernelException("Unsupported http method {}", method.toString());
    }

    // Decode content type
    String contentTypeString = this._headers.get(HttpHeaderNames.CONTENT_TYPE.toString());
    if (contentTypeString == null) {
        this._conentType = ContentType.TEXT;
        this._charset = Charset.forName("UTF-8");
    } else {
        String[] contentTypeInfo = contentTypeString.split(";");
        if (contentTypeInfo.length < 0) {
            this._conentType = ContentType.TEXT;
            this._charset = CharsetUtil.UTF_8;
        } else if (contentTypeInfo.length == 1) {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = CharsetUtil.UTF_8;
        } else {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = Looper.from(contentTypeInfo).map(info -> info.split("="))
                    .filter(kv -> kv.length == 2).filter(kv -> kv[0].trim().equalsIgnoreCase("charset"))
                    .map(kv -> kv[1].trim()).map(Charset::forName).first(CharsetUtil.UTF_8);
        }
    }
}