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:com.difference.historybook.proxy.littleproxy.LittleProxy.java

License:Apache License

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override/*ww w.  j  ava 2 s .  c  o  m*/
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {
                private final ProxyFilter filter = filterFactory != null ? filterFactory.getInstance() : null;
                private EmbeddedChannel bufferChannel = null;

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    if (filter != null && httpObject instanceof DefaultHttpRequest) {
                        filter.processRequest(new LittleProxyRequest((DefaultHttpRequest) httpObject));
                    }
                    return null;
                }

                @Override
                public HttpObject proxyToClientResponse(HttpObject httpObject) {
                    if (httpObject instanceof DefaultHttpResponse) {
                        DefaultHttpResponse response = (DefaultHttpResponse) httpObject;
                        Map<String, String> headers = new HashMap<>();
                        response.headers().forEach(e -> {
                            headers.put(e.getKey(), e.getValue());
                        });

                        if (selector != null && selector.test(new ProxyTransactionInfo(originalRequest.getUri(),
                                response.getStatus().code(), headers))) {
                            bufferChannel = new EmbeddedChannel(new HttpResponseDecoder(),
                                    new HttpContentDecompressor(), new HttpObjectAggregator(maxBufferSize));

                            DefaultHttpResponse copiedResponse = new DefaultHttpResponse(
                                    response.getProtocolVersion(), response.getStatus());
                            copiedResponse.headers().add(response.headers());

                            bufferChannel.writeInbound(copiedResponse);
                        }
                    } else if (httpObject instanceof DefaultHttpContent && bufferChannel != null) {
                        DefaultHttpContent httpContent = (DefaultHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());

                        if (ProxyUtils.isLastChunk(httpObject))
                            processChunkedResponse();
                    } else if (httpObject instanceof LastHttpContent && bufferChannel != null) {
                        LastHttpContent httpContent = (LastHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());
                        processChunkedResponse();
                    } else if (filter != null && httpObject instanceof FullHttpResponse) {
                        filter.processResponse(new LittleProxyResponse((FullHttpResponse) httpObject));
                    }
                    return httpObject;
                };

                private void processChunkedResponse() {
                    bufferChannel.flush();
                    bufferChannel.finish();
                    FullHttpResponse fullResponse = (FullHttpResponse) bufferChannel.readInbound();
                    filter.processResponse(new LittleProxyResponse(fullResponse));
                    bufferChannel = null;
                }
            };
        };
    };
}

From source file:com.digisky.innerproxy.server.InnerProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/*from  w  w w.  java  2  s  .  c om*/
        }
    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(),
                "content:" + content.toString(CharsetUtil.UTF_8));
        String jsonmsg = null;
        try {
            jsonmsg = java.net.URLDecoder.decode(content.toString(CharsetUtil.UTF_8), "utf-8");
        } catch (UnsupportedEncodingException e) {
            LogMgr.warn("", "URLDecoder exceptionn caught.");
            // e.printStackTrace();
        }
        if (msgCheck(jsonmsg) == false) { //contain ';', bad.
            LogMgr.error(InnerProxyHttpServerHandler.class.getName(),
                    "jsonmsg contain ; or ', close it. peer info:" + ctx.channel().remoteAddress().toString());
            ctx.channel().close();
            return;
        }
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "jsonmsg:" + jsonmsg);
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "method:" + request.getMethod());
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
        } else { //POST
            LogMgr.debug(InnerProxyHttpServerHandler.class.getName(), "type:" + type);
            // ugly code
            ProcessServerManager.getInstance().process(ctx.channel(), type, jsonmsg.replace("val=", ""));
        }
    }
}

From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//from   w ww  .  ja v a  2  s. c o  m
        }
    }
    if (msg instanceof HttpContent) {
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
            return;
        } else if (type.equals("email_pwd_reset") == true) { //?
            String[] tmp = request.getUri().split("=");
            String vcode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}");
            return;
        }

        //email_active  email_pwd_reset, 
        //???
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
        InterfaceHttpData postData = decoder.getBodyHttpData("val");
        if (postData instanceof FileUpload == false) {//outerProxy????
            ctx.close();
            return;
        }
        FileUpload binData = (FileUpload) postData;
        ByteBuf content = null;
        try {
            content = binData.getByteBuf();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //content??. , 0. ?(head)?id, json?, ?. ??, ???. 
        //?content?head
        int index = content.bytesBefore((byte) 0);
        if (index < 0) {
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request.");
            ctx.channel().close();
            return;
        }
        byte[] head = new byte[index];
        content.readBytes(head);
        String strHead = new String(head);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead);
        JSONObject jo = JSONObject.parseObject(strHead);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),
                "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version"));
        content.readByte();//0

        //?content?tail
        byte[] tail = new byte[content.readableBytes()];
        content.readBytes(tail);
        String sjsonmsg = null;
        if (jo.getString("version").equals("0")) { //?0
            byte[] bjsonmsg = XXTEA.decrypt(tail, key);
            int data_len = bjsonmsg.length;
            for (int i = bjsonmsg.length - 1; i != 0; --i) {
                if (bjsonmsg[i] == 0) {
                    data_len--;
                    continue;
                } else {
                    break;
                }
            }
            try {
                sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else { //TODO?0, app_id. ???
            LogMgr.error(OuterProxyHttpServerHandler.class.getName(),
                    "?0, ??");
            ctx.close();
            return;
        }
        sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//?
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg);

        //debug code
        //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg);
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model"));

        /* debug code
        //b.getBytes(n+1, tail, 0, b.g-n-1);
        for(int i=0; i< tail.length; ++i) {
           System.out.print(String.format("%x ", tail[i]));
        }
        */

        //debug code
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg);

        //
        ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg);
    }
}

From source file:com.ebay.jetstream.http.netty.server.DefaultHttpServletRequest.java

License:MIT License

public DefaultHttpServletRequest(HttpRequest req, Channel channel) {
    m_req = req;/*from  w  ww  .ja v a  2  s . c  om*/
    m_queryStringDecoder = new QueryStringDecoder(req.getUri());
    m_params = m_queryStringDecoder.parameters();
    m_channel = channel;
    m_inputStream = new JetstreamServletInputStream(req);
}

From source file:com.ebay.jetstream.http.netty.server.HttpRequestHandler.java

License:MIT License

private void debugHeadersAndCookies(HttpRequest request) {

    StringBuilder headersandaccokies = new StringBuilder();

    // echo the header for now
    for (Map.Entry<String, String> h : request.headers()) {
        headersandaccokies.append("HEADER: " + h.getKey() + " = " + h.getValue() + "\r\n");
    }/*w  w w.  ja v  a  2s .co  m*/
    headersandaccokies.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) {
                headersandaccokies.append("PARAM: " + key + " = " + val + "\r\n");
            }
        }
        headersandaccokies.append("\r\n");
    }

    debug(headersandaccokies.toString());

}

From source file:com.ebay.jetstream.http.netty.server.HttpServer.java

License:MIT License

public void processHttpRequest(HttpRequest request, Channel channel) throws Exception {

    String path = URI.create(request.getUri()).getPath();

    ServletHolder sh = null;/* w  w  w. j ava  2  s  . com*/

    if (path == null) {
        invalidCounter.increment();
        new HttpErrorRequest(request, channel, HttpResponseStatus.INTERNAL_SERVER_ERROR).run();
        return;
    }

    sh = m_servlets.get(path);

    if (sh == null) {
        String p = path;

        while (p.lastIndexOf("/") > 0) {
            p = p.substring(0, p.lastIndexOf('/'));
            sh = m_servlets.get(p);
            if (sh != null) {
                break;
            }
        }
    }

    if (sh == null) {
        notFoundCounter.increment();
        new HttpErrorRequest(request, channel, HttpResponseStatus.NOT_FOUND).run();
        return;
    }

    HttpServlet servlet = (HttpServlet) sh.getServlet();

    if (servlet != null) {
        if (!processor.processRequest(new HttpWorkRequest(request, channel, servlet, m_serverConfig))) {
            tooBusyCounter.increment();
            new HttpErrorRequest(request, channel, HttpResponseStatus.SERVICE_UNAVAILABLE).run();
        }
    } else {
        notFoundCounter.increment();
        new HttpErrorRequest(request, channel, HttpResponseStatus.NOT_FOUND).run();
    }

}

From source file:com.eucalyptus.ws.handlers.IoAddressingHandler.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    if (msg instanceof IoMessage && ((IoMessage) msg).isRequest()) {
        final IoMessage ioMessage = (IoMessage) msg;
        final HttpRequest httpRequest = (HttpRequest) ioMessage.getHttpMessage();
        final String action = addAddressing(prefix, ioMessage.getSoapEnvelope(), ioMessage.getOmMessage(),
                httpRequest.getUri());
        httpRequest.headers().add("SOAPAction", action);
    }/*from  w ww.  j av a2s.c  om*/
    super.write(ctx, msg, promise);
}

From source file:com.fire.login.http.HttpInboundHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        URI uri = URI.create(req.getUri());
        ctx.channel().attr(KEY_PATH).set(uri.getPath());

        if (req.getMethod().equals(HttpMethod.GET)) {
            QueryStringDecoder decoder = new QueryStringDecoder(URI.create(req.getUri()));
            Map<String, List<String>> parameter = decoder.parameters();
            dispatch(ctx.channel(), parameter);
            return;
        }/*from   w w w .j  a  va2  s.  c o  m*/

        decoder = new HttpPostRequestDecoder(factory, req);
    }

    if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            decoder.offer(chunk);

            List<InterfaceHttpData> list = decoder.getBodyHttpDatas();
            Map<String, List<String>> parameter = new HashMap<>();
            for (InterfaceHttpData data : list) {
                if (data.getHttpDataType() == HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) data;
                    addParameter(attribute.getName(), attribute.getValue(), parameter);
                }
            }

            if (chunk instanceof LastHttpContent) {
                reset();
                dispatch(ctx.channel(), parameter);
            }
        }
    }
}

From source file:com.github.ambry.rest.EchoMethodHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception {
    logger.trace("Reading on channel {}", ctx.channel());
    if (obj instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) obj;
        logger.trace("Handling incoming request " + request);
        requestUri = request.getUri();
        byte[] methodBytes = request.getMethod().toString().getBytes();
        if (request.headers().get(IS_CHUNKED) == null || !request.headers().get(IS_CHUNKED).equals("true")) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer(methodBytes));
            updateHeaders(response, request, methodBytes.length);
        } else {//from   www  .j a  va  2  s. c o  m
            httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            HttpHeaders.setTransferEncodingChunked(httpResponse);
            httpContentList = new ArrayList<HttpContent>();
            ByteBuf content = Unpooled.wrappedBuffer(methodBytes);
            HttpContent httpContent = new DefaultHttpContent(content);
            httpContentList.add(httpContent);
            httpContentList.add(httpContent);
            updateHeaders(httpResponse, request, methodBytes.length);
        }
    } else if (obj instanceof LastHttpContent) {
        if (requestUri.equals(DISCONNECT_URI)) {
            ctx.disconnect();
        } else if (requestUri.equals(CLOSE_URI)) {
            ctx.close();
        } else {
            if (response != null) {
                ctx.writeAndFlush(response);
            } else if (httpResponse != null) {
                ctx.writeAndFlush(httpResponse);
                for (HttpContent httpContent : httpContentList) {
                    ctx.writeAndFlush(httpContent);
                }
                ctx.writeAndFlush(new DefaultLastHttpContent());
            }
        }
    }
}

From source file:com.github.ambry.rest.NettyMessageProcessor.java

License:Open Source License

/**
 * Handles a {@link HttpRequest}.//  w  ww .j a  v a  2  s .c  o  m
 * <p/>
 * Does some state maintenance for all HTTP methods by creating a {@link RestRequest} wrapping this
 * {@link HttpRequest}
 * <p/>
 * In case of POST, delegates handling of {@link RestRequest} to the {@link RestRequestHandler}.
 * @param httpRequest the {@link HttpRequest} that needs to be handled.
 * @throws RestServiceException if there is an error handling the current {@link HttpRequest}.
 */
private void handleRequest(HttpRequest httpRequest) throws RestServiceException {
    if (responseChannel == null || responseChannel.isResponseComplete()) {
        long processingStartTime = System.currentTimeMillis();
        try {
            resetState();
            nettyMetrics.requestArrivalRate.mark();
            if (!httpRequest.getDecoderResult().isSuccess()) {
                logger.warn("Decoder failed because of malformed request on channel {}", ctx.channel());
                nettyMetrics.malformedRequestError.inc();
                throw new RestServiceException("Decoder failed because of malformed request",
                        RestServiceErrorCode.MalformedRequest);
            }
            // We need to maintain state about the request itself for the subsequent parts (if any) that come in. We will
            // attach content to the request as the content arrives.
            if (HttpPostRequestDecoder.isMultipart(httpRequest)) {
                nettyMetrics.multipartPostRequestRate.mark();
                request = new NettyMultipartRequest(httpRequest, nettyMetrics);
            } else {
                request = new NettyRequest(httpRequest, nettyMetrics);
            }
            responseChannel.setRequest(request);
            logger.trace("Channel {} now handling request {}", ctx.channel(), request.getUri());
            // We send POST that is not multipart for handling immediately since we expect valid content with it that will
            // be streamed in. In the case of POST that is multipart, all the content has to be received for Netty's
            // decoder and NettyMultipartRequest to work. So it is scheduled for handling when LastHttpContent is received.
            // With any other method that we support, we do not expect any valid content. LastHttpContent is a Netty thing.
            // So we wait for LastHttpContent (throw an error if we don't receive it or receive something else) and then
            // schedule the other methods for handling in handleContent().
            if (request.getRestMethod().equals(RestMethod.POST)
                    && !HttpPostRequestDecoder.isMultipart(httpRequest)) {
                requestHandler.handleRequest(request, responseChannel);
            }
        } finally {
            request.getMetricsTracker().nioMetricsTracker
                    .addToRequestProcessingTime(System.currentTimeMillis() - processingStartTime);
        }
    } else {
        // We have received a request when we were not expecting one. This shouldn't happen and there is no good way to
        // deal with it. So just update a metric and log an error.
        logger.warn(
                "Discarding unexpected request on channel {}. Request under processing: {}. Unexpected request: {}",
                ctx.channel(), request.getUri(), httpRequest.getUri());
        nettyMetrics.duplicateRequestError.inc();
    }
}