Example usage for io.netty.util.concurrent Future cause

List of usage examples for io.netty.util.concurrent Future cause

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future cause.

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:com.ibasco.agql.core.transport.NettyPooledTransport.java

License:Open Source License

/**
 * <p>Acquires a {@link Channel} from the {@link ChannelPool}</p>
 *
 * @param message/*from  ww  w.jav  a  2s .co m*/
 *         An {@link AbstractRequest} that will be used as the lookup reference for the {@link
 *         io.netty.channel.pool.ChannelPoolMap} key
 *
 * @return A {@link CompletableFuture} containing the acquired {@link Channel}
 */
@Override
public CompletableFuture<Channel> getChannel(M message) {
    final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
    //Retrieve our channel pool based on the message
    final ChannelPool pool = poolMap.get(message);

    log.debug("Acquiring channel from pool '{}' for message : {}", pool, message);

    //Acquire a channel from the pool and listen for completion
    pool.acquire().addListener((Future<Channel> future) -> {
        if (future.isSuccess()) {
            log.debug("Successfully acquired Channel from pool");
            Channel channel = future.get();
            channel.attr(ChannelAttributes.CHANNEL_POOL).set(pool);
            channelFuture.complete(channel);
        } else {
            log.debug("Failed to acquire Channel from Pool");
            channelFuture.completeExceptionally(new ConnectException(future.cause()));
        }
    });
    return channelFuture;
}

From source file:com.jfastnet.peers.netty.FutureGenericFutureListener.java

License:Apache License

@Override
public void operationComplete(final Future<? super Void> future) throws Exception {
    if (!future.isSuccess()) {
        if (callerObj != null) {
            log.error("Operation failed for '{}'. Caller: {}, Message: {}, toString: {}",
                    new Object[] { action, callerObj.getClass().getSimpleName(),
                            messageObj.getClass().getSimpleName(), messageObj.toString(), future.cause() });
            if (messageObj instanceof Message) {
                Message message = (Message) messageObj;
                if (message.payload instanceof ByteBuf) {
                    ByteBuf payload = (ByteBuf) message.payload;
                    int writerIndex = payload.writerIndex();
                    log.error("Size of failed message: {}", writerIndex);
                }/* www  . j a v a  2s.  c o m*/
            }
        } else if (msgType == null) {
            log.error("Operation failed", future.cause());
        } else {
            log.error("Operation failed for {}", msgType, future.cause());
        }
    }
}

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

License:Apache License

private void sendOnChannel(final Channel channel, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {

    httpRequestContext.attachedToChannel(channel);

    scheduleTimeOutTasks(requestEventBus, httpRequestContext, httpRequestContext.getTotalRequestTimeoutMillis(),
            httpRequestContext.getIdleTimeoutMillis());

    ChannelFuture channelFuture = channel.writeAndFlush(httpRequestContext);
    channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/*  w w  w. ja v  a 2 s.  com*/
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }
        }
    });

    logger.trace("Wrote {} to channel {}", httpRequestContext, channel);
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Connects to the hostname and port./*from   w w w .  ja  v  a  2 s. c  o m*/
 * 
 * @param hostname
 * @param port
 */
public ListenableFuture<KixmppClient> connect(String hostname, int port, String domain) {
    checkAndSetState(State.CONNECTING, State.DISCONNECTED);

    this.jid = new KixmppJid(domain);
    try {
        this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                new URI("ws://" + hostname + ":" + port), WebSocketVersion.V13, null, false,
                new DefaultHttpHeaders());
    } catch (Exception e) {
        throw new RuntimeException("Unable to set up handshaker.", e);
    }

    setUp();

    // set this in case we get disconnected
    deferredDisconnect = SettableFuture.create();
    deferredLogin = SettableFuture.create();

    final SettableFuture<KixmppClient> responseFuture = SettableFuture.create();

    connectListener.set(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.isSuccess()) {
                if (state.compareAndSet(State.CONNECTING, State.CONNECTED)) {
                    logger.info("Kixmpp Client connected to [{}]",
                            ((ChannelFuture) future).channel().remoteAddress());

                    channel.set(((ChannelFuture) future).channel());
                    responseFuture.set(KixmppClient.this);
                }
            } else {
                state.set(State.DISCONNECTED);
                responseFuture.setException(future.cause());
            }
        }
    });

    ChannelFuture future = bootstrap.connect(hostname, port);

    switch (type) {
    case TCP:
        future.addListener(connectListener.get());
        break;
    case WEBSOCKET:
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    state.set(State.DISCONNECTED);
                    responseFuture.setException(future.cause());
                }
            }
        });
        break;
    }

    return responseFuture;
}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Starts the server.//  w  ww .j ava2 s  .c o m
 * 
 * @throws Exception
 */
public ListenableFuture<KixmppServer> start() throws Exception {
    checkAndSetState(State.STARTING, State.STOPPED);

    logger.info("Starting Kixmpp Server on [{}]...", bindAddress);

    // register all modules
    for (String moduleClassName : modulesToRegister) {
        installModule(moduleClassName);
    }

    final SettableFuture<KixmppServer> responseFuture = SettableFuture.create();

    final GenericFutureListener<Future<? super Void>> channelFutureListener = new GenericFutureListener<Future<? super Void>>() {
        @Override
        public synchronized void operationComplete(Future<? super Void> future) throws Exception {
            if (webSocketChannelFuture.get() != null && webSocketChannelFuture.get().isDone()) {
                if (webSocketChannelFuture.get().isSuccess()) {
                    logger.info("Kixmpp WebSocket Server listening on [{}]", webSocketAddress);

                    webSocketChannel.set(webSocketChannelFuture.get().channel());
                    if (channelFuture.get() == null && !responseFuture.isDone()) {
                        logger.info("Started Kixmpp Server");
                        state.set(State.STARTED);
                        responseFuture.set(KixmppServer.this);
                    }
                    webSocketChannelFuture.set(null);
                } else {
                    logger.error("Unable to start Kixmpp WebSocket Server on [{}]", webSocketAddress,
                            future.cause());

                    if (channelFuture.get() == null && !responseFuture.isDone()) {
                        state.set(State.STOPPED);
                        responseFuture.setException(future.cause());
                    }
                    webSocketChannelFuture.set(null);
                }
            } else if (channelFuture.get() != null && channelFuture.get().isDone()) {
                if (channelFuture.get().isSuccess()) {
                    logger.info("Kixmpp Server listening on [{}]", bindAddress);

                    channel.set(channelFuture.get().channel());
                    if (webSocketChannelFuture.get() == null && !responseFuture.isDone()) {
                        logger.info("Started Kixmpp Server");
                        state.set(State.STARTED);
                        responseFuture.set(KixmppServer.this);
                    }
                    channelFuture.set(null);
                } else {
                    logger.error("Unable to start Kixmpp Server on [{}]", bindAddress, future.cause());

                    if (webSocketChannelFuture.get() == null && !responseFuture.isDone()) {
                        state.set(State.STOPPED);
                        responseFuture.setException(future.cause());
                    }
                    channelFuture.set(null);
                }
            }
        }
    };

    channelFuture.set(bootstrap.bind(bindAddress));

    channelFuture.get().addListener(channelFutureListener);

    if (webSocketAddress != null && webSocketBootstrap != null) {
        webSocketChannelFuture.set(webSocketBootstrap.bind(webSocketAddress));

        webSocketChannelFuture.get().addListener(channelFutureListener);
    }

    return responseFuture;
}

From source file:com.lambdaworks.redis.resource.Futures.java

License:Apache License

/**
 * Create a promise that emits a {@code Boolean} value on completion of the {@code future}
 * /*w  w  w  . ja va 2 s  . c o m*/
 * @param future the future.
 * @return Promise emitting a {@code Boolean} value. {@literal true} if the {@code future} completed successfully, otherwise
 *         the cause wil be transported.
 */
static Promise<Boolean> toBooleanPromise(Future<?> future) {
    final DefaultPromise<Boolean> result = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);

    future.addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(Future<Object> future) throws Exception {

            if (future.isSuccess()) {
                result.setSuccess(true);
            } else {
                result.setFailure(future.cause());
            }
        }
    });
    return result;
}

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java

License:Apache License

@SuppressWarnings("unchecked")
private static <T> Future<T> failedFuture() {
    Future<T> future = mockFuture();
    when(future.isSuccess()).thenReturn(false);
    when(future.cause()).thenReturn(new Exception());
    return future;
}

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java

License:Apache License

@Test
public void testStateTransition() throws Exception {
    FakeTicker ticker = new FakeTicker();
    int minimumRequestThreshold = 2;
    Duration circuitOpenWindow = Duration.ofSeconds(60);
    Duration counterSlidingWindow = Duration.ofSeconds(180);
    Duration counterUpdateInterval = Duration.ofMillis(1);
    Future<Object> successFuture = successFuture();
    Future<Object> failedFuture = failedFuture();

    CircuitBreaker circuitBreaker = new CircuitBreakerBuilder(remoteServiceName)
            .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow)
            .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval)
            .ticker(ticker).build();//from   w w  w  . ja  v  a2  s .  c  o  m

    RemoteInvoker remoteInvoker = mock(RemoteInvoker.class);
    // return failed future
    when(remoteInvoker.invoke(any(), any(), any(), any(), any(), any())).thenReturn(failedFuture);

    CircuitBreakerMapping mapping = (eventLoop1, uri, options1, codec1, method, args1) -> circuitBreaker;
    CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping);

    // CLOSED
    for (int i = 0; i < minimumRequestThreshold + 1; i++) {
        Future<Object> future = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
        // The future is `failedFuture` itself
        assertThat(future.isSuccess(), is(false));
        // This is not a CircuitBreakerException
        assertThat(future.cause(), is(not(instanceOf(FailFastException.class))));
        ticker.advance(Duration.ofMillis(1).toNanos());
    }

    // OPEN
    Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
    // The circuit is OPEN
    assertThat(future1.isSuccess(), is(false));
    assertThat(future1.cause(), instanceOf(FailFastException.class));
    assertThat(((FailFastException) future1.cause()).getCircuitBreaker(), is(circuitBreaker));

    ticker.advance(circuitOpenWindow.toNanos());

    // return success future
    when(remoteInvoker.invoke(any(), any(), any(), any(), any(), any())).thenReturn(successFuture);

    // HALF OPEN
    Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
    assertThat(future2.isSuccess(), is(true));

    // CLOSED
    Future<Object> future3 = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
    assertThat(future3.isSuccess(), is(true));
}

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java

License:Apache License

@Test
public void testServiceScope() throws Exception {
    FakeTicker ticker = new FakeTicker();
    int minimumRequestThreshold = 2;
    Duration circuitOpenWindow = Duration.ofSeconds(60);
    Duration counterSlidingWindow = Duration.ofSeconds(180);
    Duration counterUpdateInterval = Duration.ofMillis(1);
    Future<Object> successFuture = successFuture();
    Future<Object> failedFuture = failedFuture();

    CircuitBreaker circuitBreaker = new CircuitBreakerBuilder(remoteServiceName)
            .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow)
            .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval)
            .ticker(ticker).build();/*from   w  w  w  .  j  ava 2s . c  o m*/

    RemoteInvoker remoteInvoker = mock(RemoteInvoker.class);
    // Always return failed future for methodA
    when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodA()), any())).thenReturn(failedFuture);
    // Always return success future for methodB
    when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodB()), any())).thenReturn(successFuture);

    CircuitBreakerMapping mapping = (eventLoop1, uri, options1, codec1, method, args1) -> circuitBreaker;
    CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping);

    // CLOSED
    for (int i = 0; i < minimumRequestThreshold + 1; i++) {
        stub.invoke(eventLoop, uri, options, codec, methodA(), args);
        ticker.advance(Duration.ofMillis(1).toNanos());
    }

    // OPEN (methodA)
    Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
    assertThat(future1.isSuccess(), is(false));
    assertThat(future1.cause(), instanceOf(FailFastException.class));

    // OPEN (methodB)
    Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodB(), args);
    assertThat(future2.isSuccess(), is(false));
    assertThat(future2.cause(), instanceOf(FailFastException.class));
}

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvokerTest.java

License:Apache License

@Test
public void testPerMethodScope() throws Exception {
    FakeTicker ticker = new FakeTicker();
    int minimumRequestThreshold = 2;
    Duration circuitOpenWindow = Duration.ofSeconds(60);
    Duration counterSlidingWindow = Duration.ofSeconds(180);
    Duration counterUpdateInterval = Duration.ofMillis(1);
    Future<Object> successFuture = successFuture();
    Future<Object> failedFuture = failedFuture();

    Function<String, CircuitBreaker> factory = method -> new CircuitBreakerBuilder(remoteServiceName)
            .minimumRequestThreshold(minimumRequestThreshold).circuitOpenWindow(circuitOpenWindow)
            .counterSlidingWindow(counterSlidingWindow).counterUpdateInterval(counterUpdateInterval)
            .ticker(ticker).build();/*ww  w  . java2 s .  c om*/

    RemoteInvoker remoteInvoker = mock(RemoteInvoker.class);
    // Always return failed future for methodA
    when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodA()), any())).thenReturn(failedFuture);
    // Always return success future for methodB
    when(remoteInvoker.invoke(any(), any(), any(), any(), eq(methodB()), any())).thenReturn(successFuture);

    CircuitBreakerMapping mapping = new KeyedCircuitBreakerMapping<>(KeySelector.METHOD, factory::apply);
    CircuitBreakerRemoteInvoker stub = new CircuitBreakerRemoteInvoker(remoteInvoker, mapping);

    // CLOSED (methodA)
    for (int i = 0; i < minimumRequestThreshold + 1; i++) {
        stub.invoke(eventLoop, uri, options, codec, methodA(), args);
        ticker.advance(Duration.ofMillis(1).toNanos());
    }

    // OPEN (methodA)
    Future<Object> future1 = stub.invoke(eventLoop, uri, options, codec, methodA(), args);
    assertThat(future1.isSuccess(), is(false));
    assertThat(future1.cause(), instanceOf(FailFastException.class));

    // CLOSED (methodB)
    Future<Object> future2 = stub.invoke(eventLoop, uri, options, codec, methodB(), args);
    assertThat(future2.isSuccess(), is(true));
}