Package io.netty.handler.codec.http

Examples of io.netty.handler.codec.http.HttpRequest


                    .to("mock:input")
                    .process(new Processor() {
                        @Override
                        public void process(Exchange exchange) throws Exception {
                            // we can get the original http request
                            HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest();
                            assertNotNull(request);
                        }
                    })
                    .transform().constant("Bye World");
            }
View Full Code Here


        if (message.getBody() instanceof HttpRequest) {
            return (HttpRequest) message.getBody();
        }

        // just assume GET for now, we will later change that to the actual method to use
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
       
        Object body = message.getBody();
        if (body != null) {
            // support bodies as native Netty
            ByteBuf buffer;
            if (body instanceof ByteBuf) {
                buffer = (ByteBuf) body;
            } else {
                // try to convert to buffer first
                buffer = message.getBody(ByteBuf.class);
                if (buffer == null) {
                    // fallback to byte array as last resort
                    byte[] data = message.getMandatoryBody(byte[].class);
                    buffer = NettyConverter.toByteBuffer(data);
                }
            }
            if (buffer != null) {
                request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, buffer);
                int len = buffer.readableBytes();
                // set content-length
                request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
                LOG.trace("Content-Length: {}", len);
            } else {
                // we do not support this kind of body
                throw new NoTypeConversionAvailableException(body, ByteBuf.class);
            }
        }

        // update HTTP method accordingly as we know if we have a body or not
        HttpMethod method = NettyHttpHelper.createMethod(message, body != null);
        request.setMethod(method);
       
        TypeConverter tc = message.getExchange().getContext().getTypeConverter();

        // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
        // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
        Map<String, Object> skipRequestHeaders = null;
        if (configuration.isBridgeEndpoint()) {
            String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class);
            if (queryString != null) {
                skipRequestHeaders = URISupport.parseQuery(queryString);
            }
            // Need to remove the Host key as it should be not used
            message.getHeaders().remove("host");
        }

        // append headers
        // must use entrySet to ensure case of keys is preserved
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            // we should not add headers for the parameters in the uri if we bridge the endpoint
            // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
            if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                continue;
            }

            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
            while (it.hasNext()) {
                String headerValue = tc.convertTo(String.class, it.next());

                if (headerValue != null && headerFilterStrategy != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                    LOG.trace("HTTP-Header: {}={}", key, headerValue);
                    request.headers().add(key, headerValue);
                }
            }
        }

        // set the content type in the response.
        String contentType = MessageHelper.getContentType(message);
        if (contentType != null) {
            // set content-type
            request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
            LOG.trace("Content-Type: {}", contentType);
        }

        // must include HOST header as required by HTTP 1.1
        // use URI as its faster than URL (no DNS lookup)
        URI u = new URI(uri);
        String host = u.getHost();
        request.headers().set(HttpHeaders.Names.HOST, host);
        LOG.trace("Host: {}", host);

        // configure connection to accordingly to keep alive configuration
        // favor using the header from the message
        String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
        if (connection == null) {
            // fallback and use the keep alive from the configuration
            if (configuration.isKeepAlive()) {
                connection = HttpHeaders.Values.KEEP_ALIVE;
            } else {
                connection = HttpHeaders.Values.CLOSE;
            }
        }
        request.headers().set(HttpHeaders.Names.CONNECTION, connection);
        LOG.trace("Connection: {}", connection);

        return request;
    }
View Full Code Here

    protected Object getRequestBody(Exchange exchange) throws Exception {
        // creating the url to use takes 2-steps
        String uri = NettyHttpHelper.createURL(exchange, getEndpoint());
        URI u = NettyHttpHelper.createURI(exchange, uri, getEndpoint());

        HttpRequest request = getEndpoint().getNettyHttpBinding().toNettyRequest(exchange.getIn(), u.toString(), getConfiguration());
        String actualUri = request.getUri();
        exchange.getIn().setHeader(Exchange.HTTP_URL, actualUri);
        // Need to check if we need to close the connection or not
        if (!HttpHeaders.isKeepAlive(request)) {
            // just want to make sure we close the channel if the keepAlive is not true
            exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
View Full Code Here

    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        if (cause instanceof WebSocketHandshakeException) {
            final HttpRequest request = ctx.attr(REQUEST_KEY).get();
            logger.error("Failed with ws handshake for request: " + request, cause);
            ctx.writeAndFlush(internalServerErrorResponse(request.getProtocolVersion(), cause.getMessage()))
            .addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.fireExceptionCaught(cause);
        }
    }
View Full Code Here

    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        if (cause instanceof JsonParseException) {
            logger.trace("Failed to part JSON", cause);
            ctx.close();
        } else if (cause instanceof WebSocketHandshakeException) {
            final HttpRequest request = ctx.attr(REQUEST_KEY).get();
            logger.error("Failed with ws handshake for request: " + request, cause);
            ctx.writeAndFlush(internalServerErrorResponse(request.getProtocolVersion(), cause.getMessage()))
            .addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.fireExceptionCaught(cause);
        }
    }
View Full Code Here

    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        if (cause instanceof JsonParseException) {
            logger.error("Could not parse json", cause);
            ctx.close();
        } else if (cause instanceof WebSocketHandshakeException) {
            final HttpRequest request = ctx.attr(REQUEST_KEY).get();
            logger.error("Failed with ws handshake for request: " + request, cause);
            ctx.writeAndFlush(internalServerErrorResponse(request.getProtocolVersion(), cause.getMessage()))
            .addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.fireExceptionCaught(cause);
        }
    }
View Full Code Here

    private static EmbeddedChannel newEventSourceChannel() {
        return newStreamingChannel(SockJsConfig.withPrefix("/test").cookiesNeeded().build());
    }

    private static EmbeddedChannel newStreamingChannel(final SockJsConfig config) {
        final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, Transports.Type.EVENTSOURCE.path());
        final EventSourceTransport transport = new EventSourceTransport(config, request);
        return new EmbeddedChannel(transport);
    }
View Full Code Here

    private static EmbeddedChannel newHtmlFileChannel(final String path) {
        return newStreamingChannel(SockJsConfig.withPrefix("/test").cookiesNeeded().build(), path);
    }

    private static EmbeddedChannel newStreamingChannel(final SockJsConfig config, final String path) {
        final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, path);
        final HtmlFileTransport transport = new HtmlFileTransport(config, request);
        return new EmbeddedChannel(transport);
    }
View Full Code Here

    private static EmbeddedChannel newStreamingChannel() {
        return newStreamingChannel(SockJsConfig.withPrefix("/test").cookiesNeeded().build());
    }

    private static EmbeddedChannel newStreamingChannel(final SockJsConfig config) {
        final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/xhr-streaming");
        final XhrStreamingTransport transport = new XhrStreamingTransport(config, request);
        return new EmbeddedChannel(transport);
    }
View Full Code Here

        }
    }

    protected HttpClientRequest<I> createRedirectRequest(HttpClientRequest<I> original, URI redirectLocation,
                                                         int redirectStatus) {
        HttpRequest nettyRequest = original.getNettyRequest();
        nettyRequest.setUri(getNettyRequestUri(redirectLocation));

        HttpClientRequest<I> newRequest = new HttpClientRequest<I>(nettyRequest, original);

        if (redirectStatus == 303) {
            // according to HTTP spec, 303 mandates the change of request type to GET
            nettyRequest.setMethod(HttpMethod.GET);
            // If it is a get, then the content is not to be sent.
            newRequest.removeContent();
        }
        return newRequest;
    }
View Full Code Here

TOP

Related Classes of io.netty.handler.codec.http.HttpRequest

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.