Search in sources :

Example 46 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 47 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 48 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 49 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project motan by weibocom.

the class NettyChannel method request.

@Override
public Response request(Request request) throws TransportException {
    int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(), URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }
    NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient);
    this.nettyClient.registerCallback(request.getRequestId(), response);
    ChannelFuture writeFuture = this.channel.write(request);
    boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
    if (result && writeFuture.isSuccess()) {
        response.addListener(new FutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess() || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
                    // 成功的调用 
                    nettyClient.resetErrorCount();
                } else {
                    // 失败的调用 
                    nettyClient.incrErrorCount();
                }
            }
        });
        return response;
    }
    writeFuture.cancel();
    response = this.nettyClient.removeCallback(request.getRequestId());
    if (response != null) {
        response.cancel();
    }
    // 失败的调用 
    nettyClient.incrErrorCount();
    if (writeFuture.getCause() != null) {
        throw new MotanServiceException("NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.getCause());
    } else {
        throw new MotanServiceException("NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request));
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) FutureListener(com.weibo.api.motan.rpc.FutureListener) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) Future(com.weibo.api.motan.rpc.Future) ChannelFuture(org.jboss.netty.channel.ChannelFuture) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) TransportException(com.weibo.api.motan.transport.TransportException)

Example 50 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project motan by weibocom.

the class NettyChannel method open.

@Override
public synchronized boolean open() {
    if (isAvailable()) {
        LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri());
        return true;
    }
    try {
        ChannelFuture channleFuture = nettyClient.getBootstrap().connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));
        long start = System.currentTimeMillis();
        int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
        if (timeout <= 0) {
            throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
        // 不去依赖于connectTimeout
        boolean result = channleFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
        boolean success = channleFuture.isSuccess();
        if (result && success) {
            channel = channleFuture.getChannel();
            if (channel.getLocalAddress() != null && channel.getLocalAddress() instanceof InetSocketAddress) {
                localAddress = (InetSocketAddress) channel.getLocalAddress();
            }
            state = ChannelState.ALIVE;
            return true;
        }
        boolean connected = false;
        if (channleFuture.getChannel() != null) {
            connected = channleFuture.getChannel().isConnected();
        }
        if (channleFuture.getCause() != null) {
            channleFuture.cancel();
            throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channleFuture.getCause());
        } else {
            channleFuture.cancel();
            throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected);
        }
    } catch (MotanServiceException e) {
        throw e;
    } catch (Exception e) {
        throw new MotanServiceException("NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e);
    } finally {
        if (!state.isAliveState()) {
            nettyClient.incrErrorCount();
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) InetSocketAddress(java.net.InetSocketAddress) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) TransportException(com.weibo.api.motan.transport.TransportException)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)122 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)36 Channel (org.jboss.netty.channel.Channel)33 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)29 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)26 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)25 InetSocketAddress (java.net.InetSocketAddress)22 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)22 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)19 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 Test (org.junit.Test)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)8 Test (org.testng.annotations.Test)8 ConnectException (java.net.ConnectException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6