Example usage for io.netty.channel ChannelFutureListener operationComplete

List of usage examples for io.netty.channel ChannelFutureListener operationComplete

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener operationComplete.

Prototype

void operationComplete(F future) throws Exception;

Source Link

Document

Invoked when the operation associated with the Future has been completed.

Usage

From source file:com.basho.riak.client.core.RiakNodeTest.java

License:Apache License

@Test
public void healthCheckChangesState() throws InterruptedException, UnknownHostException, Exception {
    ChannelFuture future = mock(ChannelFuture.class);
    Channel c = mock(Channel.class);
    Bootstrap bootstrap = PowerMockito.spy(new Bootstrap());

    doReturn(future).when(c).closeFuture();
    doReturn(true).when(c).isOpen();//from   www  . j  a  v a 2s. c  o  m
    doReturn(future).when(future).await();
    doReturn(false).when(future).isSuccess();
    doReturn(c).when(future).channel();

    doReturn(future).when(bootstrap).connect();
    doReturn(bootstrap).when(bootstrap).clone();

    RiakNode node = new RiakNode.Builder().withBootstrap(bootstrap).build();

    for (int i = 0; i < 5; i++) {
        ChannelFutureListener listener = Whitebox.getInternalState(node, "inAvailableCloseListener",
                RiakNode.class);
        listener.operationComplete(future);
    }

    NodeStateListener listener = mock(NodeStateListener.class);
    node.addStateListener(listener);
    Whitebox.setInternalState(node, "state", State.RUNNING);
    Whitebox.invokeMethod(node, "checkHealth", new Object[0]);
    verify(listener).nodeStateChanged(node, State.HEALTH_CHECKING);
}

From source file:com.king.platform.net.http.netty.request.InputStreamHttpBodyTest.java

License:Apache License

@Test
public void operationCompletedShouldCloseInputStream() throws Exception {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    Channel channel = mock(Channel.class);
    when(ctx.channel()).thenReturn(channel);

    ChannelFuture channelFuture = mock(ChannelFuture.class);
    when(channel.write(any(ChunkedStream.class), any(ChannelPromise.class))).thenReturn(channelFuture);

    when(channelFuture.addListener(any(ChannelFutureListener.class))).thenAnswer(new CallHandler() {
        @Override// w w w.j  a v  a  2 s  .c  o m
        public Object invoke(Object obj, MethodCall call) throws Throwable {
            ChannelFutureListener channelFutureListener = (ChannelFutureListener) call.getArguments()[0];
            channelFutureListener.operationComplete(mock(ChannelFuture.class));
            return null;
        }
    });

    inputStreamHttpBody.writeContent(ctx, false);

    verifyOnce().on(inputStream).close();
}

From source file:com.linecorp.armeria.common.ServiceInvocationContext.java

License:Apache License

/**
 * Returns a {@link ChannelFutureListener} that makes sure the current invocation
 * context is set and then invokes the input {@code listener}.
 *///from w w w  .ja v a  2  s.co m
public final ChannelFutureListener makeContextAware(ChannelFutureListener listener) {
    ServiceInvocationContext propagatedContext = this;
    return future -> {
        boolean mustResetContext = propagateContextIfNotPresent(propagatedContext);
        try {
            listener.operationComplete(future);
        } finally {
            if (mustResetContext) {
                resetContext(propagatedContext);
            }
        }
    };
}

From source file:com.mastfrog.acteur.Acteur.java

License:Open Source License

/**
 * Set a ChannelFutureListener which will be called after headers are
 * written and flushed to the socket; prefer
 * <code>setResponseWriter()</code> to this method unless you are not using
 * chunked encoding and want to stream your response (in which case, be sure
 * to setChunked(false) or you will have encoding errors).
 *
 * @param listener/*from   www .j  a  va2s. co  m*/
 */
public final void setResponseBodyWriter(final ChannelFutureListener listener) {
    if (listener == ChannelFutureListener.CLOSE || listener == ChannelFutureListener.CLOSE_ON_FAILURE) {
        getResponse().setBodyWriter(listener);
        return;
    }
    final Page p = Page.get();
    final Application app = p.getApplication();
    class WL implements ChannelFutureListener, Callable<Void> {

        private ChannelFuture future;
        private Callable<Void> wrapper = app.getRequestScope().wrap(this);

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            this.future = future;
            wrapper.call();
        }

        @Override
        public Void call() throws Exception {
            listener.operationComplete(future);
            return null;
        }

        @Override
        public String toString() {
            return "Scope wrapper for " + listener;
        }
    }
    getResponse().setBodyWriter(new WL());
}

From source file:jj.http.server.websocket.WebSocketFrameHandlerTest.java

License:Apache License

@Test
public void testHandlerAdded() throws Exception {

    wsfh.handlerAdded(ctx);//from  ww  w . ja v  a2  s.c o m

    verify(connectionTracker).addConnection(connection);
    verify(webSocketConnectionHost).connected(connection);
    verify(executor).submit(connection, HostEvent.clientConnected.toString(), connection);
    verify(ctx.channel().closeFuture()).addListener(futureListenerCaptor.capture());

    ChannelFutureListener listener = futureListenerCaptor.getValue();

    listener.operationComplete(future);

    verify(connectionTracker).removeConnection(connection);
    verify(webSocketConnectionHost).disconnected(connection);
    verify(executor).submit(connection, HostEvent.clientDisconnected.toString(), connection);
    ;
}

From source file:org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnection.java

License:Apache License

public void write(final ActiveMQBuffer buffer, final boolean flush, final boolean batch,
        final ChannelFutureListener futureListener) {
    final ActiveMQBuffer copied = buffer.copy(0, buffer.capacity());

    copied.setIndex(buffer.readerIndex(), buffer.writerIndex());

    try {/*w ww  .j a v a2  s  .  co  m*/
        executor.execute(new Runnable() {
            public void run() {
                try {
                    if (!closed) {
                        copied.readInt(); // read and discard
                        if (isTrace) {
                            ActiveMQServerLogger.LOGGER.trace(InVMConnection.this + "::Sending inVM packet");
                        }
                        handler.bufferReceived(id, copied);
                        if (futureListener != null) {
                            // TODO BEFORE MERGE: (is null a good option here?)
                            futureListener.operationComplete(null);
                        }
                    }
                } catch (Exception e) {
                    final String msg = "Failed to write to handler on connector " + this;
                    ActiveMQServerLogger.LOGGER.errorWritingToInvmConnector(e, this);
                    throw new IllegalStateException(msg, e);
                } finally {
                    if (isTrace) {
                        ActiveMQServerLogger.LOGGER.trace(InVMConnection.this + "::packet sent done");
                    }
                }
            }
        });

        if (flush && flushEnabled) {
            final CountDownLatch latch = new CountDownLatch(1);
            executor.execute(new Runnable() {
                public void run() {
                    latch.countDown();
                }
            });

            try {
                if (!latch.await(10, TimeUnit.SECONDS)) {
                    ActiveMQServerLogger.LOGGER.timedOutFlushingInvmChannel();
                }
            } catch (InterruptedException e) {
                throw new ActiveMQInterruptedException(e);
            }
        }
    } catch (RejectedExecutionException e) {
        // Ignore - this can happen if server/client is shutdown and another request comes in
    }

}

From source file:org.hornetq.amqp.test.invm.ProtonINVMSPI.java

License:Apache License

@Override
public void output(final ByteBuf bytes, final ChannelFutureListener futureCompletion) {
    if (DebugInfo.debug) {
        ByteUtil.debugFrame("InVM->", bytes);
    }//from  www.j  a  v  a  2s. com

    bytes.retain();
    mainExecutor.execute(new Runnable() {
        public void run() {
            try {
                if (DebugInfo.debug) {
                    ByteUtil.debugFrame("InVMDone->", bytes);
                }
                serverConnection.inputBuffer(bytes);
                try {
                    futureCompletion.operationComplete(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } finally {
                bytes.release();
            }
        }
    });
}

From source file:org.hornetq.core.remoting.impl.invm.InVMConnection.java

License:Apache License

public void write(final HornetQBuffer buffer, final boolean flush, final boolean batch,
        final ChannelFutureListener futureListener) {
    final HornetQBuffer copied = buffer.copy(0, buffer.capacity());

    copied.setIndex(buffer.readerIndex(), buffer.writerIndex());

    try {//from ww w  .j  av  a 2 s . c  o  m
        executor.execute(new Runnable() {
            public void run() {
                try {
                    if (!closed) {
                        copied.readInt(); // read and discard
                        if (isTrace) {
                            HornetQServerLogger.LOGGER.trace(InVMConnection.this + "::Sending inVM packet");
                        }
                        handler.bufferReceived(id, copied);
                        if (futureListener != null) {
                            // TODO BEFORE MERGE: (is null a good option here?)
                            futureListener.operationComplete(null);
                        }
                    }
                } catch (Exception e) {
                    final String msg = "Failed to write to handler on connector " + this;
                    HornetQServerLogger.LOGGER.errorWritingToInvmConnector(e, this);
                    throw new IllegalStateException(msg, e);
                } finally {
                    if (isTrace) {
                        HornetQServerLogger.LOGGER.trace(InVMConnection.this + "::packet sent done");
                    }
                }
            }
        });

        if (flush && flushEnabled) {
            final CountDownLatch latch = new CountDownLatch(1);
            executor.execute(new Runnable() {
                public void run() {
                    latch.countDown();
                }
            });

            try {
                if (!latch.await(10, TimeUnit.SECONDS)) {
                    HornetQServerLogger.LOGGER.timedOutFlushingInvmChannel();
                }
            } catch (InterruptedException e) {
                throw new HornetQInterruptedException(e);
            }
        }
    } catch (RejectedExecutionException e) {
        // Ignore - this can happen if server/client is shutdown and another request comes in
    }

}

From source file:org.restcomm.media.network.netty.channel.AsyncNettyNetworkChannelTest.java

License:Open Source License

@SuppressWarnings("unchecked")
@Test//from www  .j  a  v  a 2  s .  com
public void testBindFailure() {
    // given
    final SocketAddress localAddress = new InetSocketAddress("127.0.0.1", 2427);

    final ChannelFuture channelBindFuture = mock(ChannelFuture.class);
    final ChannelFuture channelCloseFuture = mock(ChannelFuture.class);
    final Channel channel = mock(Channel.class);
    final ChannelHandler channelHandler = mock(ChannelHandler.class);

    this.eventGroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap().group(eventGroup).handler(channelHandler)
            .channel(NioDatagramChannel.class);
    final NettyNetworkManager networkManager = new NettyNetworkManager(bootstrap);
    final NettyNetworkManager networkManagerSpy = spy(networkManager);
    final AsyncNettyNetworkChannel<Object> networkChannel = new AsyncNettyNetworkChannel<>(networkManagerSpy);

    final FutureCallback<Void> openCallback = mock(FutureCallback.class);
    final FutureCallback<Void> bindCallback = mock(FutureCallback.class);
    final Exception exception = new RuntimeException("Testing purposes!");

    when(channel.bind(localAddress)).thenReturn(channelBindFuture);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            final FutureCallback<Channel> callback = invocation.getArgumentAt(0, FutureCallback.class);
            callback.onSuccess(channel);
            return null;
        }

    }).when(networkManagerSpy).openChannel(any(FutureCallback.class));
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            final ChannelFutureListener listener = invocation.getArgumentAt(0, ChannelFutureListener.class);
            final ChannelPromise promise = new DefaultChannelProgressivePromise(channel,
                    mock(EventExecutor.class));
            promise.setFailure(exception);
            listener.operationComplete(promise);
            return null;
        }

    }).when(channelBindFuture).addListener(any(ChannelFutureListener.class));
    when(channel.close()).thenReturn(channelCloseFuture);

    // when - open
    networkChannel.open(openCallback);
    networkChannel.bind(localAddress, bindCallback);

    // then
    verify(bindCallback, timeout(100)).onFailure(exception);
    assertFalse(networkChannel.isOpen());
    assertFalse(networkChannel.isBound());
    assertFalse(networkChannel.isConnected());
}