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:io.nebo.container.NettyHttpServletRequest.java

License:Apache License

NettyHttpServletRequest(ChannelHandlerContext ctx, NettyEmbeddedContext servletContext, HttpRequest request,
        ServletInputStream inputStream, HttpServletResponse servletResponse) {
    this.ctx = ctx;
    this.servletContext = servletContext;
    this.request = request;
    this.inputStream = inputStream;
    this.attributes = new HashMap<>();
    this.insocket = (InetSocketAddress) ctx.channel().remoteAddress();
    this.servletResponse = servletResponse;
    this.params = new ConcurrentHashMap<String, String[]>();
    this.attributes = new ConcurrentHashMap<String, Object>();
    String uri = request.getUri();

    if (uri.indexOf("?") != -1) {
        String[] strs = uri.split("\\?");
        this.requestURI = strs[0];
        this.queryString = strs[1];
    } else {//from ww w.j a  v  a2  s .  c om
        this.requestURI = uri;
    }

    if (queryString != null) {
        String[] params = queryString.split("&");
        for (String paramStr : params) {
            String[] paramArr = paramStr.split("=");
            String key = paramArr[0];
            String value = paramArr[1];
            HttpRequestUtils.setParamMap(key, value, this.params);
        }
    }
}

From source file:io.nebo.container.ServletContentHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        log.info("uri" + request.getUri());
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false);
        NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response);
        servletRequest = new NettyHttpServletRequest(ctx, servletContext, request, inputStream,
                servletResponse);/*from www .j a v a  2  s . com*/
        if (HttpMethod.GET.equals(request.getMethod())) {
            HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
            if (HttpHeaders.is100ContinueExpected(request)) {
                ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE),
                        ctx.voidPromise());
            }
            ctx.fireChannelRead(servletRequest);
        } else if (HttpMethod.POST.equals(request.getMethod())) {
            decoder = new HttpPostRequestDecoder(factory, request);
        }
    }

    if (decoder != null && msg instanceof HttpContent) {
        HttpContent chunk = (HttpContent) msg;
        log.info("HttpContent" + chunk.content().readableBytes());
        inputStream.addContent(chunk);
        List<InterfaceHttpData> interfaceHttpDatas = decoder.getBodyHttpDatas();

        for (InterfaceHttpData data : interfaceHttpDatas) {
            try {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    Attribute attribute = (Attribute) data;
                    Map<String, String[]> params = servletRequest.getParameterMap();
                    HttpRequestUtils.setParamMap(attribute.getName(), attribute.getValue(), params);
                }
            } finally {
                // data.release();
            }
        }

    }

    if (decoder != null && msg instanceof LastHttpContent) {
        ctx.fireChannelRead(servletRequest);
        reset();
    }
}

From source file:io.scalecube.socketio.pipeline.DisconnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        boolean disconnect = queryDecoder.parameters().containsKey(DISCONNECT);
        if (disconnect) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP disconnect request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final Packet disconnectPacket = new Packet(PacketType.DISCONNECT, sessionId);
            disconnectPacket.setOrigin(PipelineUtils.getOrigin(req));
            ctx.fireChannelRead(disconnectPacket);
            ReferenceCountUtil.release(msg);
            return;
        }/* w  ww . j a  v a 2 s  .  co  m*/
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.HandshakeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // //from w  w w .j av  a2 s  .  c  o m
    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (!requestPath.startsWith(handshakePath)) {
            log.warn("Received HTTP bad request: {} {} from channel: {}", requestMethod, requestPath,
                    ctx.channel());

            HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
            ChannelFuture f = ctx.channel().writeAndFlush(res);
            f.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(req);
            return;
        }

        if (HttpMethod.GET.equals(requestMethod) && requestPath.equals(handshakePath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP handshake request: {} {} from channel: {}", requestMethod, requestPath,
                        ctx.channel());

            handshake(ctx, req, queryDecoder);
            ReferenceCountUtil.release(req);
            return;
        }
    }

    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.ResourceHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?// w ww  .j  av  a2  s.c  o m
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        String requestPath = queryDecoder.path();
        URL resUrl = resources.get(requestPath);
        if (resUrl != null) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP resource request: {} {} from channel: {}", req.getMethod(),
                        requestPath, ctx.channel());

            URLConnection fileUrl = resUrl.openConnection();
            long lastModified = fileUrl.getLastModified();
            // check if file has been modified since last request
            if (isNotModified(req, lastModified)) {
                sendNotModified(ctx);
                return;
            }
            // create resource input-stream and check existence
            final InputStream is = fileUrl.getInputStream();
            if (is == null) {
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
            // create ok response
            HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            // set Content-Length header
            HttpHeaders.setContentLength(res, fileUrl.getContentLengthLong());
            // 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(ctx.name(), "chunked-writer-handler", new ChunkedWriteHandler());
            ChannelFuture writeFuture = ctx.writeAndFlush(new ChunkedStream(is, fileUrl.getContentLength()));
            // add operation complete listener so we can close the channel and the input stream
            writeFuture.addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}

From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

private String getWebSocketLocation(HttpRequest req) {
    String protocol = secure ? "wss://" : "ws://";
    String webSocketLocation = protocol + req.headers().get(HttpHeaders.Names.HOST) + req.getUri();
    if (log.isDebugEnabled())
        log.debug("Created {} at: {}", getTransportType().getName(), webSocketLocation);
    return webSocketLocation;
}

From source file:io.soliton.protobuf.json.JsonRpcServerHandler.java

License:Apache License

/**
 * In charge of validating all the transport-related aspects of the incoming
 * HTTP request.//from   www.  j a v  a  2s  . c om
 * <p/>
 * <p>The checks include:</p>
 * <p/>
 * <ul>
 * <li>that the request's path matches that of this handler;</li>
 * <li>that the request's method is {@code POST};</li>
 * <li>that the request's content-type is {@code application/json};</li>
 * </ul>
 *
 * @param request the received HTTP request
 * @return {@code null} if the request passes the transport checks, an error
 *         to return to the client otherwise.
 * @throws URISyntaxException if the URI of the request cannot be parsed
 */
private JsonRpcError validateTransport(HttpRequest request) throws URISyntaxException, JsonRpcError {
    URI uri = new URI(request.getUri());
    JsonRpcError error = null;

    if (!uri.getPath().equals(rpcPath)) {
        error = new JsonRpcError(HttpResponseStatus.NOT_FOUND, "Not Found");
    }

    if (!request.getMethod().equals(HttpMethod.POST)) {
        error = new JsonRpcError(HttpResponseStatus.METHOD_NOT_ALLOWED, "Method not allowed");
    }

    if (!request.headers().get(HttpHeaders.Names.CONTENT_TYPE).equals(JsonRpcProtocol.CONTENT_TYPE)) {
        error = new JsonRpcError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, "Unsupported media type");
    }

    return error;
}

From source file:io.soliton.protobuf.json.JsonRpcServerHandler.java

License:Apache License

/**
 * Determines whether the response to the request should be pretty-printed.
 *
 * @param request the HTTP request.//from  ww w .jav a  2s.c  o  m
 * @return {@code true} if the response should be pretty-printed.
 */
private boolean shouldPrettyPrint(HttpRequest request) {
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri(), Charsets.UTF_8, true, 2);
    Map<String, List<String>> parameters = decoder.parameters();
    if (parameters.containsKey(PP_PARAMETER)) {
        return parseBoolean(parameters.get(PP_PARAMETER).get(0));
    } else if (parameters.containsKey(PRETTY_PRINT_PARAMETER)) {
        return parseBoolean(parameters.get(PRETTY_PRINT_PARAMETER).get(0));
    }
    return true;
}

From source file:io.soliton.protobuf.quartz.QuartzServerHandler.java

License:Apache License

/**
 * {@inheritDoc}//from   w  ww .  j a  v  a 2  s .c o  m
 */
@Override
protected boolean accept(HttpRequest request) {
    try {
        return new URI(request.getUri()).getPath().startsWith(path);
    } catch (URISyntaxException e) {
        logger.warning("Cannot validate URL path, skipping request");
        return false;
    }
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

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

    if (msg instanceof HttpRequest) {

        if (requestState != RequestState.EXPECT_REQUEST) {
            sendError(ctx, ERROR_BAD_REQUEST);
            return;
        }//from w w w  . j  av  a  2s. c om

        request = (HttpRequest) msg;

        log.info("received HttpRequest: {} {}", request.getMethod(), request.getUri());

        final ObjectRequest r;

        try {
            r = new ObjectRequest(request);
        } catch (ExceptionInInitializerError e) {
            log.warn("unable to parse the request into a command: {}", request.getUri());
            return;
        }

        objectRequest = r;
        httpRequest = request;

        if (HttpMethod.PUT.equals(request.getMethod())) {
            if (objectRequest.isNotDirectory()) // make dir request
                setupProxyToPUT(ctx, objectRequest);

            requestState = RequestState.EXPECT_CONTENT_OR_LAST;
        } else {
            requestState = RequestState.EXPECT_LAST;
            ctx.read();
        }

        return;
    }

    if (objectRequest == null) {
        String uri = request == null ? "" : request.getUri();
        log.warn("not expecting an empty objectRequest. parse error maybe: {}", uri);
        ByteBuf body = request == null || request.getMethod().equals(HttpMethod.HEAD) ? null
                : errorBody("ResourceNotFoundError", uri + " does not exist");
        sendError(ctx, HttpResponseStatus.NOT_FOUND, body);
        return;
    }

    if (msg instanceof HttpContent) {

        if (requestState != RequestState.EXPECT_LAST && requestState != RequestState.EXPECT_CONTENT_OR_LAST) {
            log.warn("not expecting LAST or CONTENT, requestState: {}", requestState);
            sendError(ctx, HttpResponseStatus.NOT_EXTENDED);
            return;
        }

        final boolean last = msg instanceof LastHttpContent;
        final boolean emptyLast = last && msg == LastHttpContent.EMPTY_LAST_CONTENT;

        if (proxyMode && !emptyLast) // todo: the emptyLast was added for mln
            ctx.fireChannelRead(msg);

        // example of reading only if at the end
        if (last) {

            log.debug("received LastHttpContent: {}", msg);
            requestState = RequestState.EXPECT_REQUEST;

            final HttpRequest request = httpRequest;

            if (HttpMethod.HEAD.equals(request.getMethod())) {
                handleHEAD(ctx, objectRequest);
                return;
            }

            if (HttpMethod.GET.equals(request.getMethod())) {
                handleGET(ctx, objectRequest);
                return;
            }

            if (HttpMethod.DELETE.equals(request.getMethod())) {
                handleDELETE(ctx, objectRequest);
                return;
            }

            if (HttpMethod.PUT.equals(request.getMethod())) {
                if (proxyMode)
                    log.info("finished file upload: {}", objectRequest);
                else
                    handlePUTmkdir(ctx, objectRequest);
                return;
            }

            log.warn("unknown request: {}", request);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        }

        return;
    }

    log.warn("unexpected msg type: {}", msg);
    sendError(ctx, HttpResponseStatus.BAD_REQUEST);
}