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

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

Introduction

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

Prototype

String path

To view the source code for io.netty.handler.codec.http QueryStringDecoder path.

Click Source Link

Usage

From source file:com.addthis.hydra.query.web.HttpQueryHandler.java

License:Apache License

protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;//from w w w  . jav a 2 s  .c o m
    }
    QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri());
    String target = urlDecoder.path();
    if (request.getMethod() == HttpMethod.POST) {
        log.trace("POST Method handling triggered for {}", request);
        String postBody = request.content().toString(CharsetUtil.UTF_8);
        log.trace("POST body {}", postBody);
        urlDecoder = new QueryStringDecoder(postBody, false);
    }
    log.trace("target uri {}", target);
    KVPairs kv = new KVPairs();
    /**
     * The "/query/google/submit" endpoint needs to unpack the
     * "state" parameter into KV pairs.
     */
    if (target.equals("/query/google/submit")) {
        String state = urlDecoder.parameters().get("state").get(0);
        QueryStringDecoder newDecoder = new QueryStringDecoder(state, false);
        decodeParameters(newDecoder, kv);
        if (urlDecoder.parameters().containsKey("code")) {
            kv.add(GoogleDriveAuthentication.authtoken, urlDecoder.parameters().get("code").get(0));
        }
        if (urlDecoder.parameters().containsKey("error")) {
            kv.add(GoogleDriveAuthentication.autherror, urlDecoder.parameters().get("error").get(0));
        }
    } else {
        decodeParameters(urlDecoder, kv);
    }
    log.trace("kv pairs {}", kv);
    switch (target) {
    case "/":
        sendRedirect(ctx, "/query/index.html");
        break;
    case "/q/":
        sendRedirect(ctx, "/query/call?" + kv.toString());
        break;
    case "/query/call":
    case "/query/call/":
        QueryServer.rawQueryCalls.inc();
        queryQueue.queueQuery(meshQueryMaster, kv, request, ctx);
        break;
    case "/query/google/authorization":
        GoogleDriveAuthentication.gdriveAuthorization(kv, ctx);
        break;
    case "/query/google/submit":
        boolean success = GoogleDriveAuthentication.gdriveAccessToken(kv, ctx);
        if (success) {
            queryQueue.queueQuery(meshQueryMaster, kv, request, ctx);
        }
        break;
    default:
        fastHandle(ctx, request, target, kv);
        break;
    }
}

From source file:com.addthis.hydra.query.web.HttpStaticFileHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from  w  ww  .j a  va2  s. c  o  m*/
        return;
    }
    // since we are using send file, we must remove the compression unit or it will donk out
    ChannelHandler compressor = ctx.pipeline().get("compressor");
    if (compressor != null) {
        ctx.pipeline().remove("compressor");
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri());
    String target = urlDecoder.path();

    final String path = sanitizeUri(target);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    Path file = Paths.get(webDir + path);
    log.trace("trying to serve static file {}", file);
    if (Files.isHidden(file) || Files.notExists(file)) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (!Files.isRegularFile(file)) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    log.trace("cache validation occuring for {}", file);
    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HttpUtils.HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = Files.getLastModifiedTime(file).toMillis() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    log.trace("sending {}", file);

    FileChannel fileChannel;
    try {
        fileChannel = FileChannel.open(file, StandardOpenOption.READ);
    } catch (IOException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = fileChannel.size();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    try {
        setDateAndCacheHeaders(response, file);
    } catch (IOException ioex) {
        fileChannel.close();
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ctx.write(new DefaultFileRegion(fileChannel, 0, fileLength));

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.pipeline().remove(this);
        if (compressor != null) {
            ctx.pipeline().addBefore("query", "compressor", compressor);
        }
    }
}

From source file:com.alibaba.dubbo.qos.command.decoder.HttpCommandDecoder.java

License:Apache License

public static CommandContext decode(HttpRequest request) {
    CommandContext commandContext = null;
    if (request != null) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
        String path = queryStringDecoder.path();
        String[] array = path.split("/");
        if (array.length == 2) {
            String name = array[1];

            // process GET request and POST request separately. Check url for GET, and check body for POST
            if (request.getMethod() == HttpMethod.GET) {
                if (queryStringDecoder.parameters().isEmpty()) {
                    commandContext = CommandContextFactory.newInstance(name);
                    commandContext.setHttp(true);
                } else {
                    List<String> valueList = new ArrayList<String>();
                    for (List<String> values : queryStringDecoder.parameters().values()) {
                        valueList.addAll(values);
                    }// w  w w.  ja va  2  s  .c o  m
                    commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}),
                            true);
                }
            } else if (request.getMethod() == HttpMethod.POST) {
                HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request);
                List<String> valueList = new ArrayList<String>();
                for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) {
                    if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                        Attribute attribute = (Attribute) interfaceHttpData;
                        try {
                            valueList.add(attribute.getValue());
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
                if (valueList.isEmpty()) {
                    commandContext = CommandContextFactory.newInstance(name);
                    commandContext.setHttp(true);
                } else {
                    commandContext = CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}),
                            true);
                }
            }
        }
    }

    return commandContext;
}

From source file:com.beeswax.hexbid.handler.DefaultHandler.java

License:Apache License

public FullHttpResponse processRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri());
    LOGGER.debug("Responding with 404: not found path {}", queryDecoder.path());

    return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
            Unpooled.wrappedBuffer(CONTENT_MESSAGE.getBytes()));
}

From source file:com.beeswax.http.handler.GlobalHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    final QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri());
    LOGGER.debug("path: {}", queryDecoder.path());

    // trim trailing backslash so that the handler can recognize /PATH/
    final RequestHandler handler = handlerFactory.getHandler(queryDecoder.path().replaceAll("/$", ""));
    final FullHttpResponse response = handler.processRequest(ctx, request);
    response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE)
            .set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

    ctx.writeAndFlush(response);/*from ww w . j ava 2 s . co  m*/
}

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

License:Open Source License

public static Call fromRequest(HttpRequest req) {
    Objects.requireNonNull(req);/*from  www .j  a v  a  2  s.c o  m*/
    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.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpRequest) {
        this.httprequest = (HttpRequest) msg;

        requestBuilder = new Request.Builder();

        requestBuilder.requestMethod(RequestMethod.valueOf(httprequest.method().name())).uri(httprequest.uri());

        try {/*from   w  ww .  j av  a2  s . c  o  m*/

            // Decode URI GET query parameters
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httprequest.uri());
            requestBuilder.path(queryStringDecoder.path()).query(queryStringDecoder.parameters());

            // Process cookies
            List<Cookie> cookies = new ArrayList<>();

            String cookieString = httprequest.headers().get(HttpHeaderNames.COOKIE);
            if (cookieString != null) {
                ServerCookieDecoder.STRICT.decode(cookieString).stream().forEach((cookie) -> {
                    cookies.add(NettyCookieConverter.convertToFuga(cookie));
                });
            }

            requestBuilder.cookies(cookies);

            // Process headers
            Map<String, String> headers = new HashMap<>();
            httprequest.headers().entries().stream().forEach((e) -> {
                headers.put(e.getKey(), e.getValue());
            });

            requestBuilder.headers(headers);

            // Get real parameters from frontend HTTP server
            boolean isSecure = false;
            SocketAddress remoteAddress = ctx.channel().remoteAddress();

            if (forwarded == 1) { // RFC7239
                if (headers.containsKey("Forwarded")) {
                    String fwdStr = headers.get("Forwarded");

                    List<String> fwdparams = Stream.of(fwdStr.split("; ")).map((s) -> s.trim())
                            .collect(Collectors.toList());

                    for (String f : fwdparams) {
                        String p[] = f.split("=");

                        switch (p[0]) {
                        case "for":
                            remoteAddress = parseAddress(p[1]);
                            break;
                        case "proto":
                            isSecure = p[1].equals("https");
                            break;
                        }
                    }
                }
            } else if (forwarded == 0) { // X-Forwarded
                if (headers.containsKey("X-Forwarded-Proto")) {
                    if (headers.get("X-Forwarded-Proto").equalsIgnoreCase("https")) {
                        isSecure = true;
                    }
                }

                if (headers.containsKey("X-Forwarded-For")) {
                    String fwdfor = headers.get("X-Forwarded-For");
                    remoteAddress = parseAddress(
                            fwdfor.contains(",") ? fwdfor.substring(0, fwdfor.indexOf(',')) : fwdfor);
                } else if (headers.containsKey("X-Real-IP")) {
                    remoteAddress = parseAddress(headers.get("X-Real-IP"));
                }
            }

            requestBuilder.remoteAddress(remoteAddress).isSecure(isSecure);

            if (headers.containsKey("Accept-Language")) {
                String acceptLanguage = headers.get("Accept-Language");

                List<Locale> acceptLocales = Stream.of(acceptLanguage.split(","))
                        .map((s) -> s.contains(";") ? s.substring(0, s.indexOf(";")).trim() : s.trim())
                        .map((s) -> s.contains("-") ? new Locale(s.split("-")[0], s.split("-")[0])
                                : new Locale(s))
                        .collect(Collectors.toList());

                requestBuilder.acceptLocales(acceptLocales);
            }
            //

            if (httprequest.method().equals(HttpMethod.GET)) {
                processResponse(ctx);
                return;
            }
            decoder = true;
        } catch (Exception e) {
            processClientError(ctx, requestBuilder.build(), 400);
            return;
        }
    }

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

        contentBuffer.writeBytes(httpContent.content());

        if (httpContent instanceof LastHttpContent) {
            requestBuilder.content(new BufferedContent(contentBuffer.nioBuffer()));
            processResponse(ctx);
        }
    }
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    SchedulerKey key = new SchedulerKey(Type.PING_TIMEOUT, ctx.channel());
    disconnectScheduler.cancel(key);/*www . j a v a  2 s.  com*/

    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        if (!configuration.isAllowCustomRequests() && !queryDecoder.path().startsWith(connectPath)) {
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
            req.release();
            log.warn("Blocked wrong request! url: {}, ip: {}", queryDecoder.path(), channel.remoteAddress());
            return;
        }

        List<String> sid = queryDecoder.parameters().get("sid");
        if (queryDecoder.path().equals(connectPath) && sid == null) {
            String origin = req.headers().get(HttpHeaders.Names.ORIGIN);
            if (!authorize(ctx, channel, origin, queryDecoder.parameters(), req)) {
                req.release();
                return;
            }
            // forward message to polling or websocket handler to bind channel
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        URL resUrl = resources.get(queryDecoder.path());
        if (resUrl != null) {
            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);/*from  w ww. j  a  v a  2s .c o  m*/
                req.release();
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            setContentLength(res, fileUrl.getContentLength());
            // set Content-Type header
            setContentTypeHeader(res, fileUrl);
            // set Date, Expires, Cache-Control and Last-Modified headers
            setDateAndCacheHeaders(res, lastModified);
            // write initial response header
            ctx.write(res);

            // write the content stream
            ctx.pipeline().addBefore(SocketIOChannelInitializer.RESOURCE_HANDLER, "chunkedWriter",
                    new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            return;
        }
    }
    ctx.fireChannelRead(msg);
}

From source file:com.corundumstudio.socketio.handler.WrongUrlHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        Channel channel = ctx.channel();
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
        ChannelFuture f = channel.writeAndFlush(res);
        f.addListener(ChannelFutureListener.CLOSE);
        req.release();/*from  w w  w  .j  a  v a 2 s. c  om*/
        log.warn("Blocked wrong socket.io-context request! url: {}, params: {}, ip: {}", queryDecoder.path(),
                queryDecoder.parameters(), channel.remoteAddress());
    }
}