Search in sources :

Example 16 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project bagheera by mozilla-metrics.

the class SubmissionHandler method handleOptions.

private void handleOptions(MessageEvent e, BagheeraHttpRequest request) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST,PUT,DELETE");
    response.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 17 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project camel by apache.

the class NettyHttpProducerSimpleTest method testHttpSimpleExchange.

@Test
public void testHttpSimpleExchange() throws Exception {
    getMockEndpoint("mock:input").expectedBodiesReceived("Hello World");
    Exchange out = template.request("netty-http:http://localhost:{{port}}/foo", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody("Hello World");
        }
    });
    assertNotNull(out);
    assertTrue(out.hasOut());
    NettyHttpMessage response = out.getOut(NettyHttpMessage.class);
    assertNotNull(response);
    assertEquals(200, response.getHttpResponse().getStatus().getCode());
    // we can also get the response as body
    HttpResponse body = out.getOut().getBody(HttpResponse.class);
    assertNotNull(body);
    assertEquals(200, body.getStatus().getCode());
    assertMockEndpointsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Test(org.junit.Test)

Example 18 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project camel by apache.

the class HttpClientChannelHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    // store response, as this channel handler is created per pipeline
    Object msg = messageEvent.getMessage();
    // it may be a chunked message
    if (msg instanceof HttpChunk) {
        HttpChunk chunk = (HttpChunk) msg;
        if (LOG.isTraceEnabled()) {
            LOG.trace("HttpChunk received: {} isLast: {}", chunk, chunk.isLast());
        }
        if (msg instanceof HttpChunkTrailer) {
            // chunk trailer only has headers
            HttpChunkTrailer trailer = (HttpChunkTrailer) msg;
            for (Map.Entry<String, String> entry : trailer.trailingHeaders()) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Adding trailing header {}={}", entry.getKey(), entry.getValue());
                }
                response.headers().add(entry.getKey(), entry.getValue());
            }
        } else {
            // append chunked content
            buffer.writeBytes(chunk.getContent());
            if (LOG.isTraceEnabled()) {
                LOG.trace("Wrote {} bytes to chunk buffer", buffer.writerIndex());
            }
        }
        if (chunk.isLast()) {
            // the content is a copy of the buffer with the actual data we wrote to it
            int end = buffer.writerIndex();
            ChannelBuffer copy = buffer.copy(0, end);
            // the copy must not be readable when the content was chunked, so set the index to the end
            copy.setIndex(end, end);
            response.setContent(copy);
            // we get the all the content now, so call super to process the received message
            super.messageReceived(ctx, messageEvent);
        }
    } else if (msg instanceof HttpResponse) {
        response = (HttpResponse) msg;
        Exchange exchange = super.getExchange(ctx);
        if (!HttpHeaders.isKeepAlive(response)) {
            // just want to make sure we close the channel if the keepAlive is not true
            exchange.setProperty(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("HttpResponse received: {} chunked:", response, response.isChunked());
        }
        if (response.getStatus().getCode() == HttpResponseStatus.CONTINUE.getCode()) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("HttpResponse received: {}: {}", response, response.getStatus());
            }
        } else if (!response.isChunked()) {
            // the response is not chunked so we have all the content
            super.messageReceived(ctx, messageEvent);
        } else {
            // the response is chunkced so use a dynamic buffer to receive the content in chunks
            buffer = ChannelBuffers.dynamicBuffer();
        }
    } else {
        // ignore not supported message
        if (LOG.isTraceEnabled() && msg != null) {
            LOG.trace("Ignoring non supported response message of type {} -> {}", msg.getClass(), msg);
        }
    }
}
Also used : Exchange(org.apache.camel.Exchange) HttpChunkTrailer(org.jboss.netty.handler.codec.http.HttpChunkTrailer) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) Map(java.util.Map) HttpChunk(org.jboss.netty.handler.codec.http.HttpChunk) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 19 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project camel by apache.

the class HttpServerChannelHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    HttpRequest request = (HttpRequest) messageEvent.getMessage();
    LOG.debug("Message received: {}", request);
    if (consumer.isSuspended()) {
        // are we suspended?
        LOG.debug("Consumer suspended, cannot service request {}", request);
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // if its an OPTIONS request then return which methods is allowed
    boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
    if ("OPTIONS".equals(request.getMethod().getName()) && !isRestrictedToOptions) {
        String s;
        if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
            s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
        } else {
            // allow them all
            s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.setChunked(false);
        response.headers().set("Allow", s);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().getName())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    if ("TRACE".equals(request.getMethod().getName()) && !consumer.getEndpoint().isTraceEnabled()) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // must include HOST header as required by HTTP 1.1
    if (!request.headers().contains(HttpHeaders.Names.HOST)) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // is basic auth configured
    NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
    if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
        String url = request.getUri();
        // drop parameters from url
        if (url.contains("?")) {
            url = ObjectHelper.before(url, "?");
        }
        // we need the relative path without the hostname and port
        URI uri = new URI(request.getUri());
        String target = uri.getPath();
        // strip the starting endpoint path so the target is relative to the endpoint uri
        String path = consumer.getConfiguration().getPath();
        if (path != null) {
            // need to match by lower case as we want to ignore case on context-path
            path = path.toLowerCase(Locale.US);
            String match = target.toLowerCase(Locale.US);
            if (match.startsWith(path)) {
                target = target.substring(path.length());
            }
        }
        // is it a restricted resource?
        String roles;
        if (security.getSecurityConstraint() != null) {
            // if restricted returns null, then the resource is not restricted and we should not authenticate the user
            roles = security.getSecurityConstraint().restricted(target);
        } else {
            // assume any roles is valid if no security constraint has been configured
            roles = "*";
        }
        if (roles != null) {
            // basic auth subject
            HttpPrincipal principal = extractBasicAuthSubject(request);
            // authenticate principal and check if the user is in role
            Subject subject = null;
            boolean inRole = true;
            if (principal != null) {
                subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
                if (subject != null) {
                    String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                    inRole = matchesRoles(roles, userRoles);
                }
            }
            if (principal == null || subject == null || !inRole) {
                if (principal == null) {
                    LOG.debug("Http Basic Auth required for resource: {}", url);
                } else if (subject == null) {
                    LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                } else {
                    LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                }
                // restricted resource, so send back 401 to require valid username/password
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
                messageEvent.getChannel().write(response).syncUninterruptibly();
                messageEvent.getChannel().close();
                return;
            } else {
                LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
            }
        }
    }
    // let Camel process this message
    // It did the way as camel-netty component does
    super.messageReceived(ctx, messageEvent);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) NettyHttpSecurityConfiguration(org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) URI(java.net.URI) HttpPrincipal(org.apache.camel.component.netty.http.HttpPrincipal) Subject(javax.security.auth.Subject)

Example 20 with HttpResponse

use of org.jboss.netty.handler.codec.http.HttpResponse in project camel by apache.

the class HttpServerMultiplexChannelHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    HttpServerChannelHandler handler = (HttpServerChannelHandler) ctx.getAttachment();
    if (handler != null) {
        handler.exceptionCaught(ctx, e);
    } else {
        if (e.getCause() instanceof ClosedChannelException) {
            // The channel is closed so we do nothing here
            LOG.debug("Channel already closed. Ignoring this exception.");
            return;
        } else {
            if ("Broken pipe".equals(e.getCause().getMessage())) {
                // Can't recover channel at this point. Only valid thing to do is close. A TCP RST is a possible cause for this.
                // Note that trying to write to channel in this state will cause infinite recursion in netty 3.x
                LOG.debug("Channel pipe is broken. Closing channel now.", e);
                ctx.getChannel().close();
            } else {
                // we cannot throw the exception here
                LOG.warn("HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", e.getCause());
                // Now we just send 404 back to the client
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                // Here we don't want to expose the exception detail to the client
                response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
                ctx.getChannel().write(response).syncUninterruptibly();
                // close the channel after send error message
                ctx.getChannel().close();
            }
        }
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Aggregations

HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)124 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)95 Test (org.testng.annotations.Test)51 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)49 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)49 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)45 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)36 Channel (org.jboss.netty.channel.Channel)33 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)30 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)27 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)25 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)25 Checkpoint (com.linkedin.databus.core.Checkpoint)24 InetSocketAddress (java.net.InetSocketAddress)24 SocketAddress (java.net.SocketAddress)23 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)20 Test (org.junit.Test)20 Logger (org.apache.log4j.Logger)16 Map (java.util.Map)15 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)15