Example usage for io.netty.channel DefaultChannelPromise setFailure

List of usage examples for io.netty.channel DefaultChannelPromise setFailure

Introduction

In this page you can find the example usage for io.netty.channel DefaultChannelPromise setFailure.

Prototype

@Override
    public ChannelPromise setFailure(Throwable cause) 

Source Link

Usage

From source file:com.github.spapageo.jannel.client.ClientSessionTest.java

License:Open Source License

@Test(expected = RuntimeException.class)
public void testIdentifyWhenWriteFailsAndChannelIsActiveClosesChannelAndThrows() throws Exception {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next());
    promise.setFailure(new IOException("test"));

    when(channel.writeAndFlush(any())).thenReturn(promise);
    when(channel.isActive()).thenReturn(true);
    when(channel.close()).thenReturn(promise);

    Admin admin = new Admin();
    admin.setBoxId("test");
    admin.setAdminCommand(AdminCommand.IDENTIFY);

    try {/*from   ww w .  jav a2  s  . c  o  m*/
        clientSession.identify(admin);
    } finally {
        verify(channel).writeAndFlush(admin);
        verify(channel).close();

        assertTrue(clientSession.isClosed());
    }
}

From source file:com.github.spapageo.jannel.client.ClientSessionTest.java

License:Open Source License

@Test(expected = RuntimeException.class)
public void testIdentifyWhenWriteFailsAndChannelIsInactiveSetsClosedState() throws Exception {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next());
    promise.setFailure(new IOException("test"));

    when(channel.writeAndFlush(any())).thenReturn(promise);
    when(channel.isActive()).thenReturn(false);

    Admin admin = new Admin();
    admin.setBoxId("test");
    admin.setAdminCommand(AdminCommand.IDENTIFY);

    try {/*from w  w  w  .  ja v  a2s. co  m*/
        clientSession.identify(admin);
    } finally {
        verify(channel).writeAndFlush(admin);
        verify(channel, times(0)).close();

        assertTrue(clientSession.isClosed());
    }
}

From source file:com.github.spapageo.jannel.client.ClientSessionTest.java

License:Open Source License

@Test(expected = IOException.class)
public void testSendSmsReturnsFailedFutureWhenWriteFails() throws Exception {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next());
    promise.setFailure(new IOException());

    when(channel.writeAndFlush(any())).thenReturn(promise);

    Sms sms = new Sms();
    sms.setId(UUID.randomUUID());
    sms.setBoxId("test box");

    WindowFuture<Sms, Ack> future = clientSession.sendSms(sms, 5000);

    Futures.getChecked(future, IOException.class);
}

From source file:com.github.spapageo.jannel.client.ClientSessionTest.java

License:Open Source License

@Test
public void testSendSmsAndWaitThrowsWhenWriteFails() throws Exception {
    DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next());
    promise.setFailure(new IOException());

    when(channel.writeAndFlush(any())).thenReturn(promise);

    Sms sms = new Sms();
    sms.setId(UUID.randomUUID());
    sms.setBoxId("test box");

    try {//ww w  .j a va  2 s  .  c o  m
        clientSession.sendSmsAndWait(sms, 5000);
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof IOException);
    }
}

From source file:com.github.spapageo.jannel.client.JannelClientTest.java

License:Open Source License

@Test(expected = PrematureChannelClosureException.class)
public void testIdentifyCloseChannelOnFailure() throws Exception {
    Channel channel = mock(Channel.class, Answers.RETURNS_SMART_NULLS.get());
    mockWriteHandler = mock(ChannelHandler.class);

    DefaultChannelPromise completedFuture = new DefaultChannelPromise(channel);
    completedFuture.setSuccess();//from  w  w  w  . ja v  a2s .  c om

    DefaultChannelPromise failedFuture = new DefaultChannelPromise(channel);
    failedFuture.setFailure(new PrematureChannelClosureException("test"));

    ChannelPipeline channelPipeline = mock(ChannelPipeline.class);
    when(channelPipeline.addLast(anyString(), any(ChannelHandler.class))).thenReturn(channelPipeline);
    when(channelPipeline.addLast(any(EventExecutorGroup.class), anyString(), any(ChannelHandler.class)))
            .thenReturn(channelPipeline);
    when(channel.pipeline()).thenReturn(channelPipeline);
    when(channel.isActive()).thenReturn(true);
    when(channel.writeAndFlush(any())).thenReturn(failedFuture);
    when(channel.close()).thenReturn(completedFuture);

    when(bootstrap.connect(anyString(), anyInt())).thenReturn(completedFuture);

    ClientSessionConfiguration configuration = new ClientSessionConfiguration();

    jannelClient.identify(configuration, null);
}

From source file:io.lettuce.core.protocol.DefaultEndpointTest.java

License:Apache License

@Test
public void shouldCancelCommandsOnEncoderException() {

    when(channel.isActive()).thenReturn(true);
    sut.notifyChannelActive(channel);/*w w  w  .  ja v a2s .  c om*/

    DefaultChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);

    when(channel.writeAndFlush(any())).thenAnswer(invocation -> {
        if (invocation.getArguments()[0] instanceof RedisCommand) {
            queue.add((RedisCommand) invocation.getArguments()[0]);
        }

        if (invocation.getArguments()[0] instanceof Collection) {
            queue.addAll((Collection) invocation.getArguments()[0]);
        }
        return promise;
    });

    promise.setFailure(new EncoderException("foo"));

    sut.write(command);

    assertThat(command.exception).isInstanceOf(EncoderException.class);
}

From source file:io.soliton.protobuf.json.HttpJsonRpcClientTest.java

License:Apache License

@Test
public void testEncodeMethodCallFailure() throws InvalidProtocolBufferException, InterruptedException {
    Channel channel = Mockito.mock(Channel.class);

    Mockito.when(channel.remoteAddress())
            .thenReturn(new InetSocketAddress(InetAddress.getLoopbackAddress(), 10000));

    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);

    DefaultChannelPromise failure = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
    failure.setFailure(new Exception("OMGWTF"));
    Mockito.when(channel.writeAndFlush(captor.capture())).thenReturn(failure);

    JsonRpcClientHandler handler = new JsonRpcClientHandler();
    HttpJsonRpcClient client = new HttpJsonRpcClient(channel, handler, "/rpc", new NullClientLogger());

    ClientMethod<TimeResponse> method = Mockito.mock(ClientMethod.class);
    Mockito.when(method.serviceName()).thenReturn("TimeService");
    Mockito.when(method.name()).thenReturn("GetTime");
    Mockito.when(method.outputParser()).thenReturn(TimeResponse.PARSER);

    final CountDownLatch latch = new CountDownLatch(1);
    FutureCallback<TimeResponse> callback = new FutureCallback<TimeResponse>() {
        @Override/*ww w  .  jav  a 2 s .  c o  m*/
        public void onSuccess(@Nullable TimeResponse result) {
        }

        @Override
        public void onFailure(Throwable t) {
            Assert.assertEquals("OMGWTF", t.getMessage());
            latch.countDown();
        }
    };

    ListenableFuture<TimeResponse> future = client.encodeMethodCall(method,
            TimeRequest.newBuilder().setTimezone("UTC").build());

    Futures.addCallback(future, callback);
    latch.await(5, TimeUnit.SECONDS);

    Assert.assertEquals(0, handler.inFlightRequests().size());
}

From source file:io.soliton.protobuf.socket.RpcClientTest.java

License:Apache License

@Test
public void testEncodeMethodCallFailure() throws InvalidProtocolBufferException, InterruptedException {
    Channel channel = Mockito.mock(Channel.class);
    ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);

    DefaultChannelPromise failure = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
    failure.setFailure(new Exception("OMGWTF"));
    Mockito.when(channel.writeAndFlush(captor.capture())).thenReturn(failure);

    RpcClientHandler handler = new RpcClientHandler();
    RpcClient client = new RpcClient(channel, handler, new NullClientLogger());

    ClientMethod<TimeResponse> method = Mockito.mock(ClientMethod.class);
    Mockito.when(method.serviceName()).thenReturn("TimeService");
    Mockito.when(method.name()).thenReturn("GetTime");
    Mockito.when(method.outputParser()).thenReturn(TimeResponse.PARSER);

    final CountDownLatch latch = new CountDownLatch(1);
    FutureCallback<TimeResponse> callback = new FutureCallback<TimeResponse>() {
        @Override//from w w  w .  j  a va2s. c  o  m
        public void onSuccess(@Nullable TimeResponse result) {
        }

        @Override
        public void onFailure(Throwable t) {
            Assert.assertEquals("OMGWTF", t.getMessage());
            latch.countDown();
        }
    };

    ListenableFuture<TimeResponse> future = client.encodeMethodCall(method,
            TimeRequest.newBuilder().setTimezone("UTC").build());

    Futures.addCallback(future, callback);
    latch.await(5, TimeUnit.SECONDS);

    Assert.assertEquals(0, handler.inFlightRequests().size());
}

From source file:org.opendaylight.netconf.nettyutil.AbstractNetconfSession.java

License:Open Source License

@Override
public ChannelFuture sendMessage(final NetconfMessage netconfMessage) {
    // From: https://github.com/netty/netty/issues/3887
    // Netty can provide "ordering" in the following situations:
    // 1. You are doing all writes from the EventLoop thread; OR
    // 2. You are doing no writes from the EventLoop thread (i.e. all writes are being done in other thread(s)).
    ///* w  w  w.j av a  2s  . c  om*/
    // Restconf writes to a netconf mountpoint execute multiple messages
    // and one of these was executed from a restconf thread thus breaking ordering so
    // we need to execute all messages from an EventLoop thread.
    final DefaultChannelPromise proxyFuture = new DefaultChannelPromise(channel);
    channel.eventLoop().execute(new Runnable() {
        @Override
        public void run() {
            final ChannelFuture future = channel.writeAndFlush(netconfMessage);
            future.addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    if (future.isSuccess()) {
                        proxyFuture.setSuccess();
                    } else {
                        proxyFuture.setFailure(future.cause());
                    }
                }
            });
            if (delayedEncoder != null) {
                replaceMessageEncoder(delayedEncoder);
                delayedEncoder = null;
            }
        }
    });

    return proxyFuture;
}