Example usage for io.netty.util.concurrent Promise setFailure

List of usage examples for io.netty.util.concurrent Promise setFailure

Introduction

In this page you can find the example usage for io.netty.util.concurrent Promise setFailure.

Prototype

Promise<V> setFailure(Throwable cause);

Source Link

Document

Marks this future as a failure and notifies all listeners.

Usage

From source file:com.linecorp.armeria.client.http.HttpSessionChannelFactory.java

License:Apache License

void connect(SocketAddress remoteAddress, SessionProtocol protocol, Promise<Channel> sessionPromise) {
    final Bootstrap bootstrap = bootstrap(protocol);
    final ChannelFuture connectFuture = bootstrap.connect(remoteAddress);

    connectFuture.addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            initSession(protocol, future, sessionPromise);
        } else {//w  w  w  .j  a v  a  2s .co m
            sessionPromise.setFailure(future.cause());
        }
    });
}

From source file:com.linecorp.armeria.client.HttpRemoteInvoker.java

License:Apache License

@Override
public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec,
        Method method, Object[] args) throws Exception {

    requireNonNull(uri, "uri");
    requireNonNull(options, "options");
    requireNonNull(codec, "codec");
    requireNonNull(method, "method");

    final Scheme scheme = Scheme.parse(uri.getScheme());
    final SessionProtocol sessionProtocol = validateSessionProtocol(scheme.sessionProtocol());
    final InetSocketAddress remoteAddress = convertToSocketAddress(uri, sessionProtocol.isTls());

    final PoolKey poolKey = new PoolKey(remoteAddress, sessionProtocol);
    final Future<Channel> channelFuture = pool(eventLoop).acquire(poolKey);

    final Promise<T> resultPromise = eventLoop.newPromise();

    codec.prepareRequest(method, args, resultPromise);
    if (channelFuture.isSuccess()) {
        Channel ch = channelFuture.getNow();
        invoke0(codec, ch, method, args, options, resultPromise, poolKey);
    } else {/*from ww w .  ja  va 2s.  co  m*/
        channelFuture.addListener((Future<Channel> future) -> {
            if (future.isSuccess()) {
                Channel ch = future.getNow();
                invoke0(codec, ch, method, args, options, resultPromise, poolKey);
            } else {
                resultPromise.setFailure(channelFuture.cause());
            }
        });
    }

    return resultPromise;
}

From source file:com.linecorp.armeria.client.HttpRemoteInvoker.java

License:Apache License

static <T> void invoke0(ClientCodec codec, Channel channel, Method method, Object[] args, ClientOptions options,
        Promise<T> resultPromise, PoolKey poolKey) {

    final HttpSession session = HttpSessionHandler.get(channel);
    final SessionProtocol sessionProtocol = session.protocol();
    if (sessionProtocol == null) {
        resultPromise.setFailure(ClosedSessionException.INSTANCE);
        return;/*from  w ww.ja va  2s  .co m*/
    }

    final EncodeResult encodeResult = codec.encodeRequest(channel, sessionProtocol, method, args);
    if (encodeResult.isSuccess()) {
        ServiceInvocationContext ctx = encodeResult.invocationContext();
        Promise<FullHttpResponse> responsePromise = channel.eventLoop().newPromise();

        final Invocation invocation = new Invocation(ctx, options, responsePromise, encodeResult.content());
        //write request
        final ChannelFuture writeFuture = writeRequest(channel, invocation, ctx, options);
        writeFuture.addListener(fut -> {
            if (!fut.isSuccess()) {
                ctx.rejectPromise(responsePromise, fut.cause());
            } else {
                long responseTimeoutMillis = options.responseTimeoutPolicy().timeout(ctx);
                scheduleTimeout(channel, responsePromise, responseTimeoutMillis, false);
            }
        });

        //handle response
        if (responsePromise.isSuccess()) {
            decodeResult(codec, resultPromise, ctx, responsePromise.getNow());
        } else {
            responsePromise.addListener((Future<FullHttpResponse> future) -> {
                if (future.isSuccess()) {
                    decodeResult(codec, resultPromise, ctx, responsePromise.getNow());
                } else {
                    ctx.rejectPromise(resultPromise, future.cause());
                }
            });
        }
    } else {
        final Throwable cause = encodeResult.cause();
        if (!resultPromise.tryFailure(cause)) {
            logger.warn("Failed to reject an invocation promise ({}) with {}", resultPromise, cause, cause);
        }
    }

    if (!session.onRequestSent()) {
        // Can't send a request via the current session anymore; do not return the channel to the pool.
        return;
    }

    // Return the channel to the pool.
    final KeyedChannelPool<PoolKey> pool = KeyedChannelPool.findPool(channel);
    if (sessionProtocol.isMultiplex()) {
        pool.release(poolKey, channel);
    } else {
        resultPromise.addListener(fut -> pool.release(poolKey, channel));
    }
}

From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java

License:Apache License

private void notifyConnect(K key, Future<Channel> future, Promise<Channel> promise) {
    assert future.isDone();

    try {// w w  w  .  j av  a 2 s .  c  om
        if (future.isSuccess()) {
            Channel channel = future.getNow();
            channel.attr(KeyedChannelPoolUtil.POOL).set(this);
            channelPoolHandler.channelCreated(key, channel);
            channel.closeFuture().addListener(f -> channelPoolHandler.channelClosed(key, channel));
            promise.setSuccess(channel);
        } else {
            promise.setFailure(future.cause());
        }
    } catch (Exception e) {
        promise.setFailure(e);
    }
}

From source file:com.linecorp.armeria.client.pool.DefaultKeyedChannelPool.java

License:Apache License

private static void closeAndFail(Channel channel, Throwable cause, Promise<?> promise) {
    closeChannel(channel);// www  .  ja va2 s.co  m
    promise.setFailure(cause);
}

From source file:com.linkedin.mitm.proxy.channel.ChannelMediator.java

License:Open Source License

private void closeChannel(final Promise<Void> promise, final Channel channel) {
    channel.close().addListener(future -> {
        if (future.isSuccess()) {
            promise.setSuccess(null);/*from   www .j av a  2s .  c  o  m*/
        } else {
            promise.setFailure(future.cause());
        }
    });
}

From source file:com.zextras.modules.chat.server.xmpp.netty.TransparentProxy.java

License:Open Source License

public Future<Channel> connect() {
    final Promise<Channel> channelFuture = new DefaultProgressivePromise<Channel>(
            ImmediateEventExecutor.INSTANCE);

    if (mServerChannel == null) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(mNettyService.getEventLoopGroup()).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(mAccount.getMailHost(), mPort)).handler(new Initializer());

        ChannelFuture serverChannelFuture = bootstrap.connect();
        serverChannelFuture.addListener(new ChannelFutureListener() {
            @Override/*from   ww w  . j  av a2s .c om*/
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ChatLog.log.info(
                            "Proxy xmpp requests for " + mAccount.getName() + " to " + mAccount.getMailHost());
                    mServerChannel = future.channel();

                    mServerChannel.write(Unpooled.wrappedBuffer(mStreamInit.getBytes()));
                    mServerChannel.writeAndFlush(Unpooled.wrappedBuffer(mInitialPayload.getBytes()));

                    mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

                    mClientChannel.pipeline().addLast("proxyToServer", new Proxy(mServerChannel));

                    mServerChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mClientChannel.close();
                        }
                    });

                    mClientChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mServerChannel.close();
                        }
                    });

                    future.channel().closeFuture();

                    channelFuture.setSuccess(mServerChannel);
                } else {
                    ChatLog.log.info("Cannot proxy xmpp requests for " + mAccount.getName() + " to "
                            + mAccount.getMailHost() + ": " + Utils.exceptionToString(future.cause()));
                    sendInternalError(mClientChannel);
                    mClientChannel.flush().close();
                    channelFuture.setFailure(future.cause());
                }
            }
        });

        return channelFuture;
    } else {
        mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

        mServerChannel.writeAndFlush(mInitialPayload.getBytes());

        channelFuture.setSuccess(mServerChannel);
        return channelFuture;
    }
}

From source file:de.unipassau.isl.evs.ssh.app.handler.AbstractAppHandler.java

License:Open Source License

/**
 * Generate a new Future that will track the status of the request contained in the given sent AddressedMessage.
 * If the AddressedMessage couldn't be sent due to an IOException, the returned Future will also fail.
 * Otherwise, the returned Future will complete once {@link #handleResponse(Message.AddressedMessage)} with the
 * according response message is called.
 * <p/>//  w ww.ja  v  a  2s. c  om
 * <i>The generic return type of this method T must match the payload of the response message.
 * If you are e.g. expecting a {@link de.unipassau.isl.evs.ssh.core.messaging.RoutingKeys#MASTER_LIGHT_GET_REPLY}
 * response, the returned Future should be a Future<LightPayload>. If a error response with an {@link ErrorPayload}
 * is received, the Future will fail the cause being the received ErrorPayload.
 * If the request can have more than one successful response
 * (except for the ErrorPayload, which is always handled as described above and doesn't count here),
 * the most common supertype of both payloads (i.e. MessagePayload) must be declared as generic type for the Future.</i>
 */
protected <T> Future<T> newResponseFuture(final Message.AddressedMessage message) {
    if (!message.getFromID().equals(requireComponent(NamingManager.KEY).getOwnID())) {
        throw new IllegalArgumentException("Can only track messages sent by me");
    }
    final Promise<T> promise = requireComponent(ExecutionServiceComponent.KEY).newPromise();
    final MessageMetrics metrics;
    if (CoreConstants.TRACK_STATISTICS) {
        metrics = new MessageMetrics(message);
        promise.addListener(new FutureListener<T>() {
            @Override
            public void operationComplete(Future<T> future) throws Exception {
                metrics.finished(future);
                Log.v(AbstractAppHandler.this.getClass().getSimpleName() + "-Metrics", metrics.toString());
            }
        });
    } else {
        metrics = null;
    }
    message.getSendFuture().addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                promise.setFailure(future.cause());
            } else {
                if (metrics != null) {
                    metrics.sent(future);
                }
            }
        }
    });
    promise.setUncancellable();
    mappings.put(message.getSequenceNr(), promise);
    return promise;
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<List<InetSocketAddress>> resolveRemoteAddresses(Request request, EventLoop eventLoop,
        HttpListener listener, RequestTimeout requestTimeout) {
    if (!request.getUri().isSecured() && request.getProxyServer() instanceof HttpProxyServer) {
        // directly connect to proxy over clear HTTP
        InetSocketAddress remoteAddress = ((HttpProxyServer) request.getProxyServer()).getAddress();
        return ImmediateEventExecutor.INSTANCE.newSucceededFuture(singletonList(remoteAddress));
    } else {// ww  w .j a  va  2  s  .c om
        Promise<List<InetSocketAddress>> p = eventLoop.newPromise();

        request.getNameResolver().resolveAll(request.getUri().getHost(), eventLoop.newPromise())
                .addListener((Future<List<InetAddress>> whenAddresses) -> {
                    if (whenAddresses.isSuccess()) {
                        List<InetSocketAddress> remoteInetSocketAddresses = whenAddresses.getNow().stream().map(
                                address -> new InetSocketAddress(address, request.getUri().getExplicitPort()))
                                .collect(Collectors.toList());

                        p.setSuccess(remoteInetSocketAddresses);
                    } else {
                        if (!requestTimeout.isDone()) {
                            // only report if we haven't timed out
                            listener.onThrowable(whenAddresses.cause());
                        }
                        p.setFailure(whenAddresses.cause());
                    }
                });
        return p;
    }
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private void openNewChannelRec(List<InetSocketAddress> remoteAddresses, InetSocketAddress localAddress, int i,
        Promise<Channel> channelPromise, Bootstrap bootstrap, HttpListener listener,
        RequestTimeout requestTimeout) {

    if (isClosed()) {
        return;/* ww  w  .  j a  v  a  2  s . c o m*/
    }

    InetSocketAddress remoteAddress = remoteAddresses.get(i);

    listener.onTcpConnectAttempt(remoteAddress);
    ChannelFuture whenChannel = bootstrap.connect(remoteAddress, localAddress);

    whenChannel.addListener(f -> {
        if (f.isSuccess()) {
            Channel channel = whenChannel.channel();
            listener.onTcpConnectSuccess(remoteAddress, channel);
            channelPromise.setSuccess(channel);

        } else {
            listener.onTcpConnectFailure(remoteAddress, f.cause());

            if (requestTimeout.isDone()) {
                channelPromise.setFailure(IGNORE_REQUEST_TIMEOUT_REACHED_WHILE_TRYING_TO_CONNECT);
                return;
            }

            int nextI = i + 1;
            if (nextI < remoteAddresses.size()) {
                openNewChannelRec(remoteAddresses, localAddress, nextI, channelPromise, bootstrap, listener,
                        requestTimeout);

            } else {
                requestTimeout.cancel();
                listener.onThrowable(f.cause());
                channelPromise.setFailure(f.cause());
            }
        }
    });
}