public synchronized ListenableFuture<Void> connect () { if ( this.connectFuture != null ) { return this.connectFuture; } final ChannelFuture channelFuture = this.bootstrap.connect ( this.address ); this.connectFuture = SettableFuture.create (); channelFuture.addListener ( new GenericFutureListener<ChannelFuture> () { @Override public void operationComplete ( final ChannelFuture future ) throws Exception { handleOperationComplete ( Client.this.connectFuture, future ); } } ); return this.connectFuture; }
/** * Establishes a new socket connection with connection test */ protected void setupWithTest() { ChannelFuture future = boot.connect(uri.host(), port); future.addListener( new GenericFutureListener<ChannelFuture>() { public void operationComplete(ChannelFuture f) { if (f.isSuccess()) { channel = (HTTPChannel) f.channel(); testConnection(); onTestBell.promise(onConnectBell); } else { onConnectBell.ring(f.cause()); } } }); }
/** * Kick a player from the server with a reason */ public void kickPlayerFromServer(String reason) { final ChatComponentText chatcomponenttext = new ChatComponentText(reason); this.netManager.sendPacket(new S40PacketDisconnect(chatcomponenttext), new GenericFutureListener < Future <? super Void >> () { public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception { NetHandlerPlayServer.this.netManager.closeChannel(chatcomponenttext); } }, new GenericFutureListener[0]); this.netManager.disableAutoRead(); Futures.getUnchecked(this.serverController.addScheduledTask(new Runnable() { public void run() { NetHandlerPlayServer.this.netManager.checkDisconnected(); } })); }
public void sendPacket(Packet packetIn) { if (this.isChannelOpen()) { this.flushOutboundQueue(); this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null); } else { this.field_181680_j.writeLock().lock(); try { this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null)); } finally { this.field_181680_j.writeLock().unlock(); } } }
public void sendPacket(Packet packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners) { if (this.isChannelOpen()) { this.flushOutboundQueue(); this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)); } else { this.field_181680_j.writeLock().lock(); try { this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener))); } finally { this.field_181680_j.writeLock().unlock(); } } }
public RemoteConnection(SocketChannel channel, String name) { super(); this.channel = channel; this.clientName = name; this.writeManager = new WriteManager(); channel.pipeline().addLast(new BackPressureHandler()); channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { public void operationComplete(Future<? super Void> future) throws Exception { // this could possibly overrelease but it doesn't matter since we're only going to do this to ensure that we // fail out any pending messages writeManager.disable(); writeManager.setWritable(true); } }); }
/** * Kick a player from the server with a reason */ public void kickPlayerFromServer(String reason) { final TextComponentString textcomponentstring = new TextComponentString(reason); this.netManager.sendPacket(new SPacketDisconnect(textcomponentstring), new GenericFutureListener < Future <? super Void >> () { public void operationComplete(Future <? super Void > p_operationComplete_1_) throws Exception { NetHandlerPlayServer.this.netManager.closeChannel(textcomponentstring); } }, new GenericFutureListener[0]); this.netManager.disableAutoRead(); Futures.getUnchecked(this.serverController.addScheduledTask(new Runnable() { public void run() { NetHandlerPlayServer.this.netManager.checkDisconnected(); } })); }
@Override public void connectionSucceeded(final ServerConnection connection) { connection.getChannel().closeFuture().addListener( new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { for (final UserResultsListener listener : queryIdToResultsListenersMap.values()) { listener.submissionFailed(UserException.connectionError() .message("Connection %s closed unexpectedly. SabotNode down?", connection.getName()) .build(logger)); if (listener instanceof BufferingResultsListener) { // the appropriate listener will be failed by SubmissionListener#failed logger.warn("Buffering listener failed before results were transferred to the actual listener."); } } } }); parentHandler.connectionSucceeded(connection); }
private void kickWithMessage(String message) { final TextComponentString TextComponentString = new TextComponentString(message); if (side == Side.CLIENT) { manager.closeChannel(TextComponentString); } else { manager.sendPacket(new SPacketDisconnect(TextComponentString), new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> result) { manager.closeChannel(TextComponentString); } }, (GenericFutureListener<? extends Future<? super Void>>[])null); } manager.channel().config().setAutoRead(false); }
public void sendPacket(Packet<?> packetIn) { if (this.isChannelOpen()) { this.flushOutboundQueue(); this.dispatchPacket(packetIn, (GenericFutureListener <? extends Future <? super Void >> [])null); } else { this.readWriteLock.writeLock().lock(); try { this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])null)); } finally { this.readWriteLock.writeLock().unlock(); } } }
public void sendPacket(Packet<?> packetIn, GenericFutureListener <? extends Future <? super Void >> listener, GenericFutureListener <? extends Future <? super Void >> ... listeners) { if (this.isChannelOpen()) { this.flushOutboundQueue(); this.dispatchPacket(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener)); } else { this.readWriteLock.writeLock().lock(); try { this.outboundPacketsQueue.add(new NetworkManager.InboundHandlerTuplePacketListener(packetIn, (GenericFutureListener[])ArrayUtils.add(listeners, 0, listener))); } finally { this.readWriteLock.writeLock().unlock(); } } }
private void kickWithMessage(String message) { final ChatComponentText chatcomponenttext = new ChatComponentText(message); if (side == Side.CLIENT) { manager.func_150718_a(chatcomponenttext); } else { manager.func_150725_a(new S40PacketDisconnect(chatcomponenttext), new GenericFutureListener<Future<?>>() { @Override public void operationComplete(Future<?> result) { manager.func_150718_a(chatcomponenttext); } }); } manager.channel().config().setAutoRead(false); }
@Override public void sendOneWayMessage(Message message, SendResultCallback callback) { if (message.getMessageId() == null) { message.assignMessageId(); } io.netty.channel.Channel _socket = this.socket; if (_socket == null || !_socket.isOpen()) { callback.messageSent(message, new Exception(this + " connection is closed")); return; } _socket.writeAndFlush(message).addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { callback.messageSent(message, null); } else { LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause()); callback.messageSent(message, future.cause()); close(); } } }); }
@Test public void finalizeChannelPipeline_should_send_event_to_metricsListener_for_successful_response_and_flush_context() throws Exception { // given ChannelFuture responseWriterChannelFuture = mock(ChannelFuture.class); state.setResponseWriterFinalChunkChannelFuture(responseWriterChannelFuture); HttpProcessingState stateSpy = spy(state); doReturn(stateSpy).when(stateAttributeMock).get(); ChannelFuture responseWriteFutureResult = mock(ChannelFuture.class); doReturn(true).when(responseWriteFutureResult).isSuccess(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isFalse(); // when handler.finalizeChannelPipeline(ctxMock, null, stateSpy, null); // then ArgumentCaptor<GenericFutureListener> channelFutureListenerArgumentCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); verify(responseWriterChannelFuture).addListener(channelFutureListenerArgumentCaptor.capture()); GenericFutureListener futureListener = channelFutureListenerArgumentCaptor.getValue(); assertThat(futureListener, notNullValue()); futureListener.operationComplete(responseWriteFutureResult); verify(metricsListenerMock).onEvent(eq(ServerMetricsEvent.RESPONSE_SENT), any(HttpProcessingState.class)); verify(ctxMock).flush(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isTrue(); }
@Test public void finalizeChannelPipeline_should_send_event_to_metricsListener_for_failure_response_and_flush_context() throws Exception { // given ChannelFuture responseWriterChannelFuture = mock(ChannelFuture.class); state.setResponseWriterFinalChunkChannelFuture(responseWriterChannelFuture); HttpProcessingState stateSpy = spy(state); doReturn(stateSpy).when(stateAttributeMock).get(); ChannelFuture responseWriteFutureResult = mock(ChannelFuture.class); doReturn(false).when(responseWriteFutureResult).isSuccess(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isFalse(); // when handler.finalizeChannelPipeline(ctxMock, null, stateSpy, null); // then ArgumentCaptor<GenericFutureListener> channelFutureListenerArgumentCaptor = ArgumentCaptor.forClass(GenericFutureListener.class); verify(responseWriterChannelFuture).addListener(channelFutureListenerArgumentCaptor.capture()); GenericFutureListener futureListener = channelFutureListenerArgumentCaptor.getValue(); assertThat(futureListener, notNullValue()); futureListener.operationComplete(responseWriteFutureResult); verify(metricsListenerMock).onEvent(ServerMetricsEvent.RESPONSE_WRITE_FAILED, null); verify(ctxMock).flush(); Assertions.assertThat(stateSpy.isRequestMetricsRecordedOrScheduled()).isTrue(); }
private void verifyCloseFutureListener(GenericFutureListener closeFutureListener) throws Exception { // If the double-check ScheduledFuture is not done then it cancels it. reset(doubleCheckScheduledFutureMock); doReturn(false).when(doubleCheckScheduledFutureMock).isDone(); closeFutureListener.operationComplete(null); verify(doubleCheckScheduledFutureMock).isDone(); verify(doubleCheckScheduledFutureMock).cancel(false); verifyNoMoreInteractions(doubleCheckScheduledFutureMock); // And when the double-check ScheduledFuture is done, then nothing happens. reset(doubleCheckScheduledFutureMock); doReturn(true).when(doubleCheckScheduledFutureMock).isDone(); closeFutureListener.operationComplete(null); verify(doubleCheckScheduledFutureMock).isDone(); verifyNoMoreInteractions(doubleCheckScheduledFutureMock); }
@DataProvider(value = { "0", "1" }) @Test public void doChannelActive_marks_and_schedules_double_check_timeout_if_too_many_open_channels( int numOpenChannelsGreaterThanMax ) throws Exception { // given int actualOpenChannels = maxOpenChannelsThreshold + numOpenChannelsGreaterThanMax; setActualOpenChannels(actualOpenChannels); // when PipelineContinuationBehavior result = handler.doChannelActive(ctxMock); // then assertThat(result).isEqualTo(CONTINUE); Pair<Runnable, GenericFutureListener> futureInfoPair = extractDoubleCheckRunnableAndCloseFutureListener(); verify(tooManyOpenConnectionsAttributeMock).set(actualOpenChannels); verifyDoubleCheckFuture(futureInfoPair.getLeft()); verifyCloseFutureListener(futureInfoPair.getRight()); verify(channelGroupMock, never()).add(channelMock); }
@Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { // Once session is secured, send a greeting and register the channel to // the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture() .addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush("Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine() .getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); }
protected void send(MqttMessage message, GenericFutureListener<? extends Future<? super Void>> completeListener) { if (!session.isConnected(true)) { logger.error("Message is not sent - Channel is inactive or out of the node. [{}]", message); return; } ChannelHandlerContext ctx = Session.NEXUS.channelHandlerContext(session.clientId()); String log = message.toString(); ChannelFuture cf = ctx.writeAndFlush(message).addListener(f -> { if (f.isSuccess()) { logger.debug("packet outgoing [{}]", log); } else { logger.error("packet outgoing failed [{}] {}", log, f.cause()); } }); if (completeListener != null) { cf.addListener(completeListener); } }
@SafeVarargs public final void sendPacket(final Packet<?> packet, final GenericFutureListener<? extends Future<? super Void>> listener, final GenericFutureListener<? extends Future<? super Void>>... listeners) { if (this.closed) { this.handleClosed(); return; } if (this.isChannelOpen()) { this.nextPacket(); this.sendPacket(packet, ArrayUtils.add(listeners, 0, listener)); } else { this.packetQueue.add(new QueuedPacket(packet, ArrayUtils.add(listeners, 0, listener))); } }
@SafeVarargs public final void sendPacket(IPacket packet, GenericFutureListener<? extends Future<? super Void>>... listeners) { SentPacket sentPacket = new SentPacket(handler, handler.getPacketMap().getPacketId(packet.getClass()), packet); if (channel.eventLoop().inEventLoop()) { channel.writeAndFlush(sentPacket).addListeners(listeners) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } else { channel.eventLoop().execute(new Runnable() { @Override public void run() { channel.writeAndFlush(sentPacket).addListeners(listeners) .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } }); } }
@Override public void sendAsync(List<Append> appends, CompletedCallback callback) { recentMessage.set(true); Channel ch; try { ch = getChannel(); } catch (ConnectionFailedException e) { callback.complete(new ConnectionFailedException("Connection to " + connectionName + " is not established.")); return; } PromiseCombiner combiner = new PromiseCombiner(); for (Append append : appends) { batchSizeTracker.recordAppend(append.getEventNumber(), append.getData().readableBytes()); combiner.add(ch.write(append)); } ch.flush(); ChannelPromise promise = ch.newPromise(); promise.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { Throwable cause = future.cause(); callback.complete(cause == null ? null : new ConnectionFailedException(cause)); } }); combiner.finish(promise); }
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush( "Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); }
/** * Wraps and returns a Listener that will, as soon as its operationComplete is called, call the operationComplete * of the given listener, but on the UI Thread. */ protected <T extends Future<?>> GenericFutureListener<T> listenerOnUiThread(final GenericFutureListener<T> listener) { final String tag = BoundFragment.this.getClass().getSimpleName(); return new GenericFutureListener<T>() { @Override public void operationComplete(final T future) throws Exception { final FragmentActivity activity = getActivity(); if (activity == null) { Log.i(tag, "Not calling listener " + listener + " of future " + future + " as fragment is no longer attached."); } else { activity.runOnUiThread(new Runnable() { @Override public void run() { try { listener.operationComplete(future); } catch (Exception e) { Log.w(tag, "Listener for Future " + future + " threw an Exception", e); } } }); } } }; }
/** * Disconnects. This will wait for pending writes to be flushed before * disconnecting. * * @return Future<Void> for when we're done disconnecting. If we weren't * connected, this returns null. */ Future<Void> disconnect() { if (channel == null) { return null; } else { final Promise<Void> promise = channel.newPromise(); writeToChannel(Unpooled.EMPTY_BUFFER).addListener( new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete( Future<? super Void> future) throws Exception { closeChannel(promise); } }); return promise; } }
private void closeChannel(final Promise<Void> promise) { channel.close().addListener( new GenericFutureListener<Future<? super Void>>() { public void operationComplete( Future<? super Void> future) throws Exception { if (future .isSuccess()) { promise.setSuccess(null); } else { promise.setFailure(future .cause()); } }; }); }
/** * Does the work of processing the current step, checking the result and * handling success/failure. * * @param LOG */ @SuppressWarnings("unchecked") private void doProcessCurrentStep(final ProxyConnectionLogger LOG) { currentStep.execute().addListener( new GenericFutureListener<Future<?>>() { public void operationComplete( io.netty.util.concurrent.Future<?> future) throws Exception { synchronized (connectLock) { if (future.isSuccess()) { LOG.debug("ConnectionFlowStep succeeded"); currentStep .onSuccess(ConnectionFlow.this); } else { LOG.debug("ConnectionFlowStep failed", future.cause()); fail(future.cause()); } } }; }); }
/** * Called when the flow fails at some {@link ConnectionFlowStep}. * Disconnects the {@link ProxyToServerConnection} and informs the * {@link ClientToProxyConnection} that our connection failed. */ @SuppressWarnings("unchecked") void fail(final Throwable cause) { final ConnectionState lastStateBeforeFailure = serverConnection .getCurrentState(); serverConnection.disconnect().addListener( new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { synchronized (connectLock) { if (!clientConnection.serverConnectionFailed( serverConnection, lastStateBeforeFailure, cause)) { // the connection to the server failed and we are not retrying, so transition to the // DISCONNECTED state serverConnection.become(ConnectionState.DISCONNECTED); // We are not retrying our connection, let anyone waiting for a connection know that we're done notifyThreadsWaitingForConnection(); } } } }); }