Example usage for io.netty.handler.codec.http HttpRequest getUri

List of usage examples for io.netty.handler.codec.http HttpRequest getUri

Introduction

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

Prototype

@Deprecated
String getUri();

Source Link

Usage

From source file:HttpUploadServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object 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  .  j ava 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
        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 {
                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) {
                readHttpDataAllReceive(ctx.channel());
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }//w ww .j av a 2  s .  c o  m
        boolean keepAlive = HttpHeaders.isKeepAlive(request);

        // Encode the cookie.
        String cookieString = request.headers().get(Names.COOKIE);
        if (cookieString != null) {
            Set<Cookie> cookies = CookieDecoder.decode(cookieString);
            if (!cookies.isEmpty()) {
                // Reset the cookies if necessary.
                for (Cookie cookie : cookies) {
                    response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie));
                }
            }
        } else {
            // Browser sent no cookie.  Add some.
            /*  response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key1", "value1"));
              response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));*/
        }

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        responseContent.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n");
        //responseContent.append("HOSTNAME: ").append(request.headers().).append("\r\n");
        responseContent.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Entry<String, String> h : headers) {
                CharSequence key = h.getKey();
                CharSequence value = h.getValue();
                responseContent.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            responseContent.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) {
                    responseContent.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            responseContent.append("\r\n");
        }

        response = setResponse(response, responseContent);

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }

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

        if (msg instanceof LastHttpContent) {

        }
    }
}

From source file:br.unifei.edu.eco009.steamlansync.proxy.SteamActivityTracker.java

public void requestSentToServer(FullFlowContext flowContext, HttpRequest httpRequest) {
    if (httpRequest.getMethod().equals(HttpMethod.GET)
            && httpRequest.getUri().contains("steampowered.com/depot/")) {
        System.out.println(httpRequest.getUri());
        System.out.println(UriParser.getAppId(httpRequest));
    }/*w ww  .j a v a  2s  . c  o m*/

}

From source file:br.unifei.edu.eco009.steamlansync.proxy.SteamDepotFilter.java

public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {
    if (originalRequest.getMethod().equals(HttpMethod.GET)
            && originalRequest.getUri().contains("steampowered.com/depot/")
            && originalRequest.getUri().contains("chunk")) {

        // alterar o precedimento da
        // request:
        return new HttpFiltersAdapter(originalRequest) {
            boolean store = false;
            String chunkId = UriParser.getChunkId(originalRequest);
            HttpChunkContents cachedChunk;

            @Override//from   w  ww . java 2  s .  co  m
            public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                //                        return chunks.get(getChunkId(originalRequest)).copy().retain();
                cachedChunk = SteamCache.getChunk(chunkId);
                if (cachedChunk == null) {
                    store = true;
                    System.out.println("cache MISS");
                    return super.clientToProxyRequest(httpObject);
                }
                System.out.println("cache HIT");
                return cachedChunk.getFullHttpResponse().retain();

            }

            @Override
            public HttpObject proxyToClientResponse(HttpObject httpObject) {
                FullHttpResponse resp = (FullHttpResponse) super.proxyToClientResponse(httpObject);
                //                        chunks.put(getChunkId(originalRequest), resp.copy());
                if (store) {
                    SteamCache.putChunk(chunkId, new HttpChunkContents(resp));
                }
                return resp;
            }

        };
    }
    return null;
}

From source file:br.unifei.edu.eco009.steamlansync.utils.UriParser.java

public static String getChunkId(HttpRequest req) {
    String uri = req.getUri();
    return uri.split("chunk\\/")[1].split("\\?")[0];
}

From source file:br.unifei.edu.eco009.steamlansync.utils.UriParser.java

public static String getAppId(HttpRequest req) {
    String uri = req.getUri();
    return uri.split("depot\\/")[1].split("\\/")[0];
}

From source file:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println(msg.toString());
    } else {//from   w w  w .j a v  a  2 s. co  m
        System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content()));
        //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset()));
    }

    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);
            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 {
                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:co.freeside.betamax.util.ProxyOverrider.java

License:Apache License

/**
 * Used by LittleProxy to connect to a downstream proxy if there is one.
 */// ww w .  j  av a 2s. c  om
@Override
public void lookupChainedProxies(HttpRequest request, Queue<ChainedProxy> chainedProxies) {
    final InetSocketAddress originalProxy = originalProxies.get(URI.create(request.getUri()).getScheme());
    if (originalProxy != null) {
        ChainedProxy chainProxy = new ChainedProxyAdapter() {
            @Override
            public InetSocketAddress getChainedProxyAddress() {
                return originalProxy;
            }
        };
        chainedProxies.add(chainProxy);
    }
}

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 va2s  .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.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    CommandContext commandContext = HttpCommandDecoder.decode(msg);
    // return 404 when fail to construct command context
    if (commandContext == null) {
        log.warn("can not found commandContext url: " + msg.getUri());
        FullHttpResponse response = http_404();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {/*from  w w  w  .j  av  a2s .  c o m*/
        commandContext.setRemote(ctx.channel());
        try {
            String result = commandExecutor.execute(commandContext);
            FullHttpResponse response = http_200(result);
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } catch (NoSuchCommandException ex) {
            log.error("can not find commandContext: " + commandContext, ex);
            FullHttpResponse response = http_404();
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } catch (Exception qosEx) {
            log.error("execute commandContext: " + commandContext + " got exception", qosEx);
            FullHttpResponse response = http_500(qosEx.getMessage());
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}