Search in sources :

Example 16 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class TestRpcHandler method httpOptionsCORSNotAllowed.

@Test
public void httpOptionsCORSNotAllowed() {
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "/api/v1/version");
    req.headers().add(HttpHeaders.ORIGIN, "42.com");
    handleHttpRpc(req, new Answer<ChannelFuture>() {

        public ChannelFuture answer(final InvocationOnMock args) throws Throwable {
            DefaultHttpResponse response = (DefaultHttpResponse) args.getArguments()[0];
            assertEquals(HttpResponseStatus.OK, response.getStatus());
            assertNull(response.headers().get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
            return null;
        }
    });
    tsdb.getConfig().overrideConfig("tsd.http.request.cors_domains", "aurther.com,dent.net,beeblebrox.org");
    final RpcHandler rpc = new RpcHandler(tsdb, rpc_manager);
    rpc.messageReceived(ctx, message);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 17 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class TestRpcHandler method httpCORSNotAllowedSimple.

@Test
public void httpCORSNotAllowedSimple() {
    final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/v1/version");
    req.headers().add(HttpHeaders.ORIGIN, "42.com");
    handleHttpRpc(req, new Answer<ChannelFuture>() {

        public ChannelFuture answer(final InvocationOnMock args) throws Throwable {
            DefaultHttpResponse response = (DefaultHttpResponse) args.getArguments()[0];
            assertEquals(HttpResponseStatus.OK, response.getStatus());
            assertNull(response.headers().get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
            return null;
        }
    });
    tsdb.getConfig().overrideConfig("tsd.http.request.cors_domains", "aurther.com,dent.net,beeblebrox.org");
    final RpcHandler rpc = new RpcHandler(tsdb, rpc_manager);
    rpc.messageReceived(ctx, message);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project opentsdb by OpenTSDB.

the class AbstractHttpQuery method sendBuffer.

/**
   * Sends an HTTP reply to the client.
   * @param status The status of the request (e.g. 200 OK or 404 Not Found).
   * @param buf The content of the reply to send.
   */
public void sendBuffer(final HttpResponseStatus status, final ChannelBuffer buf, final String contentType) {
    if (!chan.isConnected()) {
        done();
        return;
    }
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
    // TODO(tsuna): Server, X-Backend, etc. headers.
    // only reset the status if we have the default status, otherwise the user
    // already set it
    response.setStatus(status);
    response.setContent(buf);
    final boolean keepalive = HttpHeaders.isKeepAlive(request);
    if (keepalive) {
        HttpHeaders.setContentLength(response, buf.readableBytes());
    }
    final ChannelFuture future = chan.write(response);
    if (stats != null) {
        future.addListener(new SendSuccess());
    }
    if (!keepalive) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
    done();
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture)

Example 19 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class NettyProducer method process.

public boolean process(final Exchange exchange, AsyncCallback callback) {
    if (!isRunAllowed()) {
        if (exchange.getException() == null) {
            exchange.setException(new RejectedExecutionException());
        }
        callback.done(true);
        return true;
    }
    Object body;
    try {
        body = getRequestBody(exchange);
        if (body == null) {
            noReplyLogger.log("No payload to send for exchange: " + exchange);
            callback.done(true);
            return true;
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // set the exchange encoding property
    if (getConfiguration().getCharsetName() != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.normalizeCharset(getConfiguration().getCharsetName()));
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Pool[active={}, idle={}]", pool.getNumActive(), pool.getNumIdle());
    }
    // get a channel from the pool
    Channel existing;
    try {
        existing = pool.borrowObject();
        if (existing != null) {
            LOG.trace("Got channel from pool {}", existing);
        }
    } catch (Exception e) {
        exchange.setException(e);
        callback.done(true);
        return true;
    }
    // we must have a channel
    if (existing == null) {
        exchange.setException(new CamelExchangeException("Cannot get channel from pool", exchange));
        callback.done(true);
        return true;
    }
    if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {
        long timeoutInMs = exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
        ChannelHandler oldHandler = existing.getPipeline().get("timeout");
        ReadTimeoutHandler newHandler = new ReadTimeoutHandler(getEndpoint().getTimer(), timeoutInMs, TimeUnit.MILLISECONDS);
        if (oldHandler == null) {
            existing.getPipeline().addBefore("handler", "timeout", newHandler);
        } else {
            existing.getPipeline().replace(oldHandler, "timeout", newHandler);
        }
    }
    // need to declare as final
    final Channel channel = existing;
    final AsyncCallback producerCallback = new NettyProducerCallback(channel, callback);
    // setup state as attachment on the channel, so we can access the state later when needed
    channel.setAttachment(new NettyCamelState(producerCallback, exchange));
    InetSocketAddress remoteAddress = null;
    if (!isTcp()) {
        // Need to specify the remoteAddress for udp connection
        remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    }
    // write body
    NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() {

        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            LOG.trace("Operation complete {}", channelFuture);
            if (!channelFuture.isSuccess()) {
                // no success then exit, (any exception has been handled by ClientChannelHandler#exceptionCaught)
                return;
            }
            // if we do not expect any reply then signal callback to continue routing
            if (!configuration.isSync()) {
                try {
                    // should channel be closed after complete?
                    Boolean close;
                    if (ExchangeHelper.isOutCapable(exchange)) {
                        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    } else {
                        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    }
                    // should we disconnect, the header can override the configuration
                    boolean disconnect = getConfiguration().isDisconnect();
                    if (close != null) {
                        disconnect = close;
                    }
                    if (disconnect) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Closing channel when complete at address: {}", getEndpoint().getConfiguration().getAddress());
                        }
                        NettyHelper.close(channel);
                    }
                } finally {
                    // signal callback to continue routing
                    producerCallback.done(false);
                }
            }
        }
    });
    // continue routing asynchronously
    return false;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) CamelExchangeException(org.apache.camel.CamelExchangeException) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) AsyncCallback(org.apache.camel.AsyncCallback) ChannelHandler(org.jboss.netty.channel.ChannelHandler) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CamelException(org.apache.camel.CamelException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ConnectException(java.net.ConnectException) CamelExchangeException(org.apache.camel.CamelExchangeException) ReadTimeoutHandler(org.jboss.netty.handler.timeout.ReadTimeoutHandler)

Example 20 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class NettyProducer method openChannel.

protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
    }
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });
    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException("Interrupted while waiting for " + "connection to " + configuration.getAddress());
    }
    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.getCause() != null) {
            cause.initCause(channelFuture.getCause());
        }
        throw cause;
    }
    Channel answer = channelFuture.getChannel();
    // to keep track of all channels in use
    allChannels.add(answer);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) CamelException(org.apache.camel.CamelException) Channel(org.jboss.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) CamelException(org.apache.camel.CamelException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ConnectException(java.net.ConnectException) CamelExchangeException(org.apache.camel.CamelExchangeException) ConnectException(java.net.ConnectException)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)138 Channel (org.jboss.netty.channel.Channel)40 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)38 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)28 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)26 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)23 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)23 Test (org.junit.Test)15 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)9 Test (org.testng.annotations.Test)8 IOException (java.io.IOException)7 ConnectException (java.net.ConnectException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6