List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.mobius.software.android.iotbroker.mqtt.net.ExceptionHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ctx.write(msg, promise.addListener(new ChannelFutureListener() { @Override//from w w w . j a v a2 s .co m public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { Log.d("", "an error occured while write"); if (listener != null) listener.writeError(); } } })); }
From source file:com.mobius.software.mqtt.performance.controller.client.Client.java
License:Open Source License
@Override public Boolean execute() { try {/* w w w .j ava 2 s .co m*/ if (!status.get()) { Boolean previouslyNull = (channelHandler.get() == null); if (!previouslyNull) { ChannelFuture future = channelHandler.get(); if (future.isDone()) { if (future.isSuccess()) { ctx.updateLocalAddress(listener.finishConnection(future, this)); status.set(true); } else report.reportError(ErrorType.CONNECTION_LOST, "failed to establish TCP connection"); } } else channelHandler.compareAndSet(null, listener.connect(ctx.remoteAddress())); timestamp.set(System.currentTimeMillis() + orchestrator.getProperties().getInitialDelay()); return true; } else { Long currTimestamp = timestamp.get(); Command nextCommand = null; boolean firstIteration = true; do { nextCommand = commands.poll(); if (nextCommand != null) { if (firstIteration) { Command previous = pendingCommand.getAndSet(nextCommand); if (previous != null && nextCommand.getSendTime() > 0) { report.reportError(ErrorType.PREVIOUS_COMMAND_FAILED, previous.getType().toString()); failedCommands.incrementAndGet(); if (!orchestrator.getProperties().isContinueOnError()) { listener.close(ctx.localAddress()); return false; } } } MQMessage message = CommandParser.toMessage(nextCommand, clientID); Boolean closeChannel = false; switch (message.getType()) { case DISCONNECT: timers.stopAllTimers(); pendingCommand.set(null); closeChannel = true; break; case PUBLISH: Publish pub = (Publish) message; switch (pub.getTopic().getQos()) { case AT_MOST_ONCE: pendingCommand.set(null); break; case AT_LEAST_ONCE: case EXACTLY_ONCE: timers.store(pub); break; default: break; } break; case SUBSCRIBE: case UNSUBSCRIBE: timers.store(message); break; case CONNECT: Connect connect = (Connect) message; ctx.update(connect.isCleanSession(), connect.getKeepalive(), connect.getClientID()); //timers.storeConnect(message); break; default: break; } report.countOut(message.getType()); listener.send(ctx.localAddress(), message); if (closeChannel) { listener.releaseLocalPort(ctx.remoteAddress(), ((InetSocketAddress) ctx.localAddress()).getPort()); status.set(false); channelHandler.set(null); listener.close(ctx.localAddress()); } Command next = commands.peek(); if (next != null) timestamp.addAndGet(next.getSendTime()); else timestamp.set( System.currentTimeMillis() + orchestrator.getProperties().getInitialDelay()); firstIteration = false; } else orchestrator.notifyOnComplete(); } while (nextCommand != null && currTimestamp == timestamp.get()); return commands.peek() != null; } } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:com.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java
License:Open Source License
@Override public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {// w w w . j av a2 s . c om ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) exceptionCaught(ctx, future.cause()); } })); }
From source file:com.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ctx.write(msg, promise.addListener(new ChannelFutureListener() { @Override//from w w w . j a v a2 s . co m public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) exceptionCaught(ctx, future.cause()); } })); }
From source file:com.mongodb.connection.netty.NettyStream.java
License:Apache License
@Override public void openAsync(final AsyncCompletionHandler<Void> handler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup);// w w w.j a va2 s .c o m bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize()); } bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { if (sslSettings.isEnabled()) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(), address.getPort()); engine.setUseClientMode(true); if (!sslSettings.isInvalidHostNameAllowed()) { engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters())); } ch.pipeline().addFirst("ssl", new SslHandler(engine, false)); } ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS)); ch.pipeline().addLast(new InboundBufferHandler()); } }); final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = channelFuture.channel(); handler.completed(null); } else { handler.failed(future.cause()); } } }); }
From source file:com.mongodb.connection.netty.NettyStream.java
License:Apache License
@Override public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) { CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer(); for (ByteBuf cur : buffers) { io.netty.buffer.ByteBuf byteBuf = ((NettyByteBuf) cur).asByteBuf(); composite.addComponent(byteBuf.retain()); composite.writerIndex(composite.writerIndex() + byteBuf.writerIndex()); }/* www .jav a2 s.c om*/ channel.writeAndFlush(composite).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { handler.failed(future.cause()); } else { handler.completed(null); } } }); }
From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java
License:Apache License
public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) { final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode()); final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor : matched;//w w w .j av a 2 s . co m if (pair != null) { Runnable run = new Runnable() { @Override public void run() { try { RPCHook rpcHook = NettyRemotingAbstract.this.getRPCHook(); if (rpcHook != null) { rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd); } final RemotingCommand response = pair.getObject1().processRequest(ctx, cmd); if (rpcHook != null) { rpcHook.doAfterResponse(cmd, response); } // Oneway? if (!cmd.isOnewayRPC()) { if (response != null) { response.setOpaque(cmd.getOpaque()); response.markResponseType(); try { ctx.writeAndFlush(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { plog.error("response to " + RemotingHelper.parseChannelRemoteAddr(future.channel()) + " failed", future.cause()); plog.error(cmd.toString()); plog.error(response.toString()); } } }); } catch (Throwable e) { plog.error("process request over, but response failed", e); plog.error(cmd.toString()); plog.error(response.toString()); } } else { // ?processRequest? } } } catch (Throwable e) { plog.error("process request exception", e); plog.error(cmd.toString()); if (!cmd.isOnewayRPC()) { final RemotingCommand response = RemotingCommand.createResponseCommand( RemotingSysResponseCode.SYSTEM_ERROR, // RemotingHelper.exceptionSimpleDesc(e)); response.setOpaque(cmd.getOpaque()); ctx.writeAndFlush(response); } } } }; try { // ?????? pair.getObject2().submit(run); } catch (RejectedExecutionException e) { plog.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) // + ", too many requests and system thread pool busy, RejectedExecutionException " // + pair.getObject2().toString() // + " request code: " + cmd.getCode()); if (!cmd.isOnewayRPC()) { final RemotingCommand response = RemotingCommand.createResponseCommand( RemotingSysResponseCode.SYSTEM_BUSY, "too many requests and system thread pool busy, please try another server"); response.setOpaque(cmd.getOpaque()); ctx.writeAndFlush(response); } } } else { String error = " request type " + cmd.getCode() + " not supported"; final RemotingCommand response = RemotingCommand .createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error); response.setOpaque(cmd.getOpaque()); ctx.writeAndFlush(response); plog.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error); } }
From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java
License:Apache License
public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis, final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException { boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS); if (acquired) { final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync); final ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), timeoutMillis, invokeCallback, once);// w ww .ja v a 2 s. c om this.responseTable.put(request.getOpaque(), 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); responseFuture.executeInvokeCallback(); responseTable.remove(request.getOpaque()); plog.warn("send a request command to channel <" + channel.remoteAddress() + "> failed."); plog.warn(request.toString()); } }); } 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("invokeAsyncImpl invoke too fast"); } else { plog.warn("invokeAsyncImpl tryAcquire semaphore timeout, " + timeoutMillis + " waiting thread nums: " + this.semaphoreAsync.getQueueLength()); plog.warn(request.toString()); throw new RemotingTimeoutException("tryAcquire timeout(ms) " + timeoutMillis); } } }
From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java
License:Apache License
public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis) throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {/*from w w w. j a v a 2s .c om*/ 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."); plog.warn(request.toString()); } } }); } 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 { plog.warn("invokeOnewayImpl tryAcquire semaphore timeout, " + timeoutMillis + " waiting thread nums: " + this.semaphoreOneway.getQueueLength()); plog.warn(request.toString()); throw new RemotingTimeoutException("tryAcquire timeout(ms) " + timeoutMillis); } } }
From source file:com.mpush.core.push.BroadcastPushTask.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) {//?? Logs.PUSH.info("[Broadcast] push message to client success, userId={}, message={}", message.getUserId(), message);//from w ww . j ava 2 s .com } else {//? Logs.PUSH.warn("[Broadcast] push message to client failure, userId={}, message={}, conn={}", message.getUserId(), message, future.channel()); } if (finishTasks.decrementAndGet() == 0) { report(); } }