List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.weibo.api.motan.transport.netty.NettyChannel.java
License:Apache License
@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); }//w ww . j a v a 2 s .c o m NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient); this.nettyClient.registerCallback(request.getRequestId(), response); ChannelFuture writeFuture = this.channel.writeAndFlush(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(false); response = this.nettyClient.removeCallback(request.getRequestId()); if (response != null) { response.cancel(); } // nettyClient.incrErrorCount(); if (writeFuture.cause() != null) { throw new MotanServiceException( "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.cause()); } else { throw new MotanServiceException( "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request)); } }
From source file:com.weibo.api.motan.transport.netty.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }// w w w . jav a 2s.com 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.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channleFuture.channel() != null) { connected = channleFuture.channel().isActive(); } if (channleFuture.cause() != null) { channleFuture.cancel(false); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channleFuture.cause()); } else { channleFuture.cancel(false); 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(); } } }
From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java
License:Apache License
@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("Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); }/*from w ww . j a v a 2s .c o m*/ NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient); this.nettyClient.registerCallback(request.getRequestId(), response); ChannelFuture writeFuture = this.channel.writeAndFlush(request); boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.SECONDS); 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(true); response = this.nettyClient.removeCallback(request.getRequestId()); if (response != null) { response.cancel(); } // nettyClient.incrErrorCount(); if (writeFuture.cause() != null) { throw new MotanServiceException( "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request), writeFuture.cause()); } else { throw new MotanServiceException( "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local=" + localAddress + " " + MotanFrameworkUtil.toString(request)); } }
From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }// w ww. j a va2s. com try { ChannelFuture channelFuture = 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( "Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ??connectTimeout boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); boolean success = channelFuture.isSuccess(); if (result && success) { channel = channelFuture.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channelFuture.channel() != null) { connected = channelFuture.channel().isOpen(); } if (channelFuture.cause() != null) { channelFuture.cancel(true); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.cause()); } else { channelFuture.cancel(true); 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(); } } }
From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java
License:Open Source License
/** * Start the discovery process./*w w w. j a va 2 s .c o m*/ * * @throws IOException on failure */ public void start() throws IOException { searchRequestRunnable = new SearchRequestRunnable(this); // set up the inbound channel handler bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new DatagramToByteBufHandler()); // convert an incoming DatagramPacket into a ByteBuf pipeline.addLast(new OrderDecoder()); // convert an incoming ByteBuf into an Order pipeline.addLast(new InboundOrderHandler(listener)); // handle incoming Orders } }); // bind to the address ChannelFuture cf = bootstrap.bind(new InetSocketAddress(0)); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { channel = (DatagramChannel) channelFuture.channel(); // perform initial search request group.execute(searchRequestRunnable); // schedule two quick follow-up search requests to make sure a camera didn't miss the first request group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS, TimeUnit.SECONDS); group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2, TimeUnit.SECONDS); // set up a recurring search request so we can keep track of cameras coming/going searchFuture = group.scheduleAtFixedRate(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2 + getSearchRequestFrequencySeconds, getSearchRequestFrequencySeconds, TimeUnit.SECONDS); } else { logger.error("Bind attempt failed", channelFuture.cause()); } } }); }
From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java
License:Open Source License
/** * Connect the channel./*from w ww . j a v a2 s .c o m*/ * * @param b a Netty Bootstrap object */ synchronized private void connect(Bootstrap b) { logger.debug("connect()"); if (connectionState == State.NOT_CONNECTED) { logger.debug("Attempting to connect"); connectionState = State.CONNECTING; b.connect(socketAddress).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { logger.debug("Connection established"); connectionState = State.CONNECTED; // save the channel AbstractChannelObjectPlugin.this.channel = channelFuture.channel(); // set a close listener to notify the plugin subclass when the channel has closed channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { logger.info("Connection was closed"); channel = null; connectionState = State.NOT_CONNECTED; executeInEventLoop(new Runnable() { @Override public void run() { onChannelDisconnected(); } }); if (isRunning) { scheduleReconnect(channelFuture.channel().eventLoop()); } } }); executeInEventLoop(new Runnable() { @Override public void run() { onChannelConnected(); } }); } else { logger.warn("Connection attempt to " + socketAddress.toString() + " failed", channelFuture.cause()); connectionState = State.NOT_CONNECTED; if (isRunning) { scheduleReconnect(channelFuture.channel().eventLoop()); } } } }); } else { logger.debug("Ignoring connect request due to state: " + connectionState); } }
From source file:com.whizzosoftware.wzwave.controller.netty.NettyZWaveController.java
License:Open Source License
public void start() { if (channel == null) { // set up Netty bootstrap bootstrap = new Bootstrap(); bootstrap.group(new OioEventLoopGroup()); bootstrap.channel(RxtxChannel.class); bootstrap.handler(new ChannelInitializer<RxtxChannel>() { @Override/*from w ww . java 2 s. com*/ protected void initChannel(RxtxChannel channel) throws Exception { NettyZWaveController.this.channel = channel; channel.config().setBaudrate(115200); channel.config().setDatabits(RxtxChannelConfig.Databits.DATABITS_8); channel.config().setParitybit(RxtxChannelConfig.Paritybit.NONE); channel.config().setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1); channel.pipeline().addLast("decoder", new ZWaveFrameDecoder()); channel.pipeline().addLast("ack", new ACKInboundHandler()); channel.pipeline().addLast("encoder", new ZWaveFrameEncoder()); channel.pipeline().addLast("writeQueue", new FrameQueueHandler()); channel.pipeline().addLast("transaction", new TransactionInboundHandler()); channel.pipeline().addLast("handler", inboundHandler); } }); bootstrap.connect(new RxtxDeviceAddress(serialPort)).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { sendDataFrame(new Version()); sendDataFrame(new MemoryGetId()); sendDataFrame(new InitData()); } else { onZWaveConnectionFailure(future.cause()); } } }); } }
From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java
License:Apache License
/** * ?????//from w w w .j a v a2 s.c om * @param channel * @param request * @param timeoutMillis * @return * @throws InterruptedException * @throws RemotingSendRequestException * @throws RemotingTimeoutException */ public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException { final int opaque = request.getOpaque(); try { final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null); this.responseTable.put(opaque, responseFuture); final SocketAddress addr = channel.remoteAddress(); channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } else { responseFuture.setSendRequestOK(false); } responseTable.remove(opaque); responseFuture.setCause(f.cause()); responseFuture.putResponse(null); plog.warn("send a request command to channel <" + addr + "> failed."); } }); // ?responseFuture.putResponse RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis); if (null == responseCommand) { if (responseFuture.isSendRequestOK()) { throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis, responseFuture.getCause()); } else { throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr), responseFuture.getCause()); } } return responseCommand; } finally { this.responseTable.remove(opaque); } }
From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java
License:Apache License
/** * ????/*from w ww.j a v a 2 s . c om*/ * @param channel * @param request * @param timeoutMillis * @param invokeCallback * @throws InterruptedException * @throws RemotingTooMuchRequestException * @throws RemotingTimeoutException * @throws RemotingSendRequestException */ public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { final int opaque = request.getOpaque(); boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync); final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once); this.responseTable.put(opaque, responseFuture); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { responseFuture.setSendRequestOK(true); return; } else { responseFuture.setSendRequestOK(false); } responseFuture.putResponse(null); responseTable.remove(opaque); try { responseFuture.executeInvokeCallback(); } catch (Throwable e) { plog.warn("excute callback in writeAndFlush addListener, and callback throw", e); } finally { responseFuture.release(); } plog.warn("send a request command to channel <{}> failed.", RemotingHelper.parseChannelRemoteAddr(channel)); } }); } catch (Exception e) { responseFuture.release(); plog.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel) + "> Exception", e); throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e); } } else { String info = String.format( "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", // timeoutMillis, // this.semaphoreAsync.getQueueLength(), // this.semaphoreAsync.availablePermits()// ); plog.warn(info); throw new RemotingTooMuchRequestException(info); } }
From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java
License:Apache License
/** * ?????//from www . j a v a2s. co m * @param channel * @param request * @param timeoutMillis * @throws InterruptedException * @throws RemotingTooMuchRequestException * @throws RemotingTimeoutException * @throws RemotingSendRequestException */ public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { request.markOnewayRPC(); boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway); try { channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { once.release(); if (!f.isSuccess()) { plog.warn( "send a request command to channel <" + channel.remoteAddress() + "> failed."); } } }); } catch (Exception e) { once.release(); plog.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed."); throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e); } } else { if (timeoutMillis <= 0) { throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast"); } else { String info = String.format( "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", // timeoutMillis, // this.semaphoreOneway.getQueueLength(), // this.semaphoreOneway.availablePermits()// ); plog.warn(info); throw new RemotingTimeoutException(info); } } }