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:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<Channel> installHttp2Handler(HttpTx tx, Channel channel, ChannelPool channelPool) {

    Promise<Channel> whenAlpn = channel.eventLoop().newPromise();

    channel.pipeline().addAfter(SSL_HANDLER, ALPN_HANDLER,
            new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
                @Override//  ww w.j  a v  a 2s .c  o  m
                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {

                    switch (protocol) {
                    case ApplicationProtocolNames.HTTP_2:
                        LOGGER.debug("ALPN led to HTTP/2 with remote {}", tx.request.getUri().getHost());
                        tx.listener.onProtocolAwareness(true);
                        Http2Connection connection = new DefaultHttp2Connection(false);

                        HttpToHttp2ConnectionHandler http2Handler = new HttpToHttp2ConnectionHandlerBuilder()
                                .initialSettings(Http2Settings.defaultSettings()) // FIXME override?
                                .connection(connection)
                                .frameListener(new DelegatingDecompressorFrameListener(connection,
                                        new ChunkedInboundHttp2ToHttpAdapter(connection, false, true,
                                                whenAlpn)))
                                .build();

                        ctx.pipeline().addLast(HTTP2_HANDLER, http2Handler).addLast(APP_HTTP2_HANDLER,
                                new Http2AppHandler(connection, http2Handler, channelPool, config));

                        channelPool.offer(channel);

                        SslHandler sslHandler = (SslHandler) ctx.pipeline().get(SSL_HANDLER);
                        Set<String> subjectAlternativeNames = Tls
                                .extractSubjectAlternativeNames(sslHandler.engine());
                        if (!subjectAlternativeNames.isEmpty()) {
                            channelPool.addCoalescedChannel(subjectAlternativeNames,
                                    (InetSocketAddress) channel.remoteAddress(), channel, tx.key);
                        }
                        break;

                    case ApplicationProtocolNames.HTTP_1_1:
                        LOGGER.debug("ALPN led to HTTP/1 with remote {}", tx.request.getUri().getHost());
                        if (tx.request.isHttp2PriorKnowledge()) {
                            IllegalStateException e = new IllegalStateException(
                                    "HTTP/2 Prior knowledge was set on host " + tx.request.getUri().getHost()
                                            + " but it only supports HTTP/1");
                            whenAlpn.setFailure(e);
                            throw e;
                        }
                        tx.listener.onProtocolAwareness(false);
                        ctx.pipeline()
                                .addBefore(CHUNKED_WRITER_HANDLER, HTTP_CLIENT_CODEC, newHttpClientCodec())
                                .addBefore(CHUNKED_WRITER_HANDLER, INFLATER_HANDLER,
                                        newHttpContentDecompressor())
                                .addAfter(CHUNKED_WRITER_HANDLER, APP_HTTP_HANDLER,
                                        new HttpAppHandler(DefaultHttpClient.this, channelPool, config));
                        whenAlpn.setSuccess(ctx.channel());
                        break;

                    default:
                        IllegalStateException e = new IllegalStateException("Unknown protocol: " + protocol);
                        whenAlpn.setFailure(e);
                        ctx.close();
                        // FIXME do we really need to throw?
                        throw e;
                    }
                }
            });

    whenAlpn.addListener(f -> {
        if (!f.isSuccess()) {
            tx.listener.onThrowable(f.cause());
        }
    });

    return whenAlpn;
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolver.java

License:Apache License

private Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query0(InetSocketAddress nameServerAddr,
        DnsQuestion question, Iterable<DnsRecord> additional,
        Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {

    final Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> castPromise = cast(
            checkNotNull(promise, "promise"));
    try {/* w w  w. j  a v a  2 s.c  o m*/
        new DnsQueryContext(this, nameServerAddr, question, additional, castPromise).query();
        return castPromise;
    } catch (Exception e) {
        return castPromise.setFailure(e);
    }
}

From source file:me.ferrybig.javacoding.teamspeakconnector.internal.TeamspeakIO.java

License:Open Source License

public Future<ComplexResponse> sendPacket(ComplexRequest req, SendBehaviour sendBehaviour) {
    if (closed) {
        if (sendBehaviour != SendBehaviour.NORMAL) {
            return this.closeFuture;
        }//  w w w.  j a va 2 s . c o  m
        return channel.eventLoop().newFailedFuture(new TeamspeakException("Channel closed"));
    }
    Promise<ComplexResponse> prom = channel.eventLoop().newPromise();
    ChannelFuture future;
    synchronized (incomingQueue) {
        if (closed) {
            if (sendBehaviour != SendBehaviour.NORMAL) {
                return this.closeFuture;
            }
            return prom.setFailure(new TeamspeakException("Channel closed"));
        }
        incomingQueue.offer(new PendingPacket(prom, req, sendBehaviour));
        future = channel.writeAndFlush(req);
    }
    future.addListener(upstream -> {
        assert upstream == future;
        if (sendBehaviour == SendBehaviour.FORCE_CLOSE_CONNECTION) {
            channel.eventLoop().schedule(() -> {
                if (channel.isActive()) {
                    LOG.fine("Closing channel by timeout");
                    channel.close();
                }
            }, 10, TimeUnit.SECONDS);
        }
        if (!upstream.isSuccess()) {
            synchronized (incomingQueue) {
                if (incomingQueue.removeIf(prom::equals)) {
                    prom.setFailure(new TeamspeakException("Exception during sending", upstream.cause()));
                }
            }
        }
    });
    if (sendBehaviour == SendBehaviour.CLOSE_CONNECTION
            || sendBehaviour == SendBehaviour.FORCE_CLOSE_CONNECTION) {
        prom.addListener(upstream -> {
            assert upstream == prom;
            if (prom.isSuccess()) {
                synchronized (incomingQueue) {
                    this.closed = true;
                }
                channel.close();
                LOG.fine("Closing channel because sendmessage asked it");
            }
        });
    }

    return prom;
}

From source file:me.ferrybig.javacoding.teamspeakconnector.TeamspeakApi.java

License:Open Source License

public Future<TeamspeakConnection> connect(SocketAddress addr) {
    Promise<TeamspeakConnection> prom = this.group.next().newPromise();
    ChannelFuture channel = openChannel(addr, new TeamspeakConnectionInitizer(prom, 20000), 20000);
    channel.addListener(future -> {/*from  w  w  w .ja  v  a  2 s  . c o  m*/
        if (!channel.isSuccess()) {
            prom.setFailure(new TeamspeakException("Connection failed", channel.cause()));
        }
    });
    return prom;
}

From source file:me.ferrybig.javacoding.teamspeakconnector.util.FutureUtil.java

License:Open Source License

private static <T, R> Future<R> delegateFutureResult(Future<T> future, Promise<R> prom, Function<T, R> map) {
    future.addListener(ignored -> {//from w w w  .  ja v a  2s  .  c  o m
        assert ignored == future;
        try {
            if (future.isSuccess()) {
                prom.setSuccess(map.apply(future.getNow()));
            } else {
                prom.setFailure(future.cause());
            }
        } catch (Throwable e) {
            prom.setFailure(e);
        }
    });
    return prom;
}

From source file:me.ferrybig.javacoding.teamspeakconnector.util.FutureUtil.java

License:Open Source License

public static <T, I, R> Future<R> chainFutureFlat(Promise<R> result, Future<T> future,
        Function<T, Future<I>> mapping, Function<I, R> secondary) {
    future.addListener(ignored -> {// w  ww.  j a v a 2  s  .c  o m
        assert ignored == future;
        try {
            if (future.isSuccess()) {
                delegateFutureResult(mapping.apply(future.getNow()), result, secondary);
            } else {
                result.setFailure(future.cause());
            }
        } catch (Throwable e) {
            result.setFailure(e);
        }
    });
    return result;
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public Future<?> pingAddress(Address addr) {
    int packetNumber = pingPacketCounter.getAndIncrement();
    byte[] data = new byte[4];
    ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(data);
    wrappedBuffer.writerIndex(0);//from w ww.  ja  va2s  .  c om
    wrappedBuffer.writeInt(packetNumber);
    assert wrappedBuffer.array() == data;
    Promise<PongPacket> promise = events.newPromise();
    pingListeners.put(packetNumber, promise);
    promise.addListener(e -> pingListeners.remove(packetNumber));
    boolean send = routePacket(addr, new PingPacket(data));
    if (!send) {
        promise.setFailure(new IllegalArgumentException("Unknown address"));
    }
    return promise;
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannel.java

License:Apache License

/**
 * Calls method on channel//from  www.  j a  v a 2  s  . c  o  m
 * @param method to call
 * @param controller to run call with
 * @param request to send
 * @param responsePrototype to construct response with
 */
public Promise<Message> callMethod(final Descriptors.MethodDescriptor method,
        final PayloadCarryingRpcController controller, final Message request, final Message responsePrototype) {
    final AsyncCall call = new AsyncCall(channel.eventLoop(), client.callIdCnt.getAndIncrement(), method,
            request, controller, responsePrototype);
    controller.notifyOnCancel(new RpcCallback<Object>() {
        @Override
        public void run(Object parameter) {
            // TODO: do not need to call AsyncCall.setFailed?
            synchronized (pendingCalls) {
                pendingCalls.remove(call.id);
            }
        }
    });
    // TODO: this should be handled by PayloadCarryingRpcController.
    if (controller.isCanceled()) {
        // To finish if the call was cancelled before we set the notification (race condition)
        call.cancel(true);
        return call;
    }

    synchronized (pendingCalls) {
        if (closed) {
            Promise<Message> promise = channel.eventLoop().newPromise();
            promise.setFailure(new ConnectException());
            return promise;
        }
        pendingCalls.put(call.id, call);
        // Add timeout for cleanup if none is present
        if (cleanupTimer == null && call.getRpcTimeout() > 0) {
            cleanupTimer = client.newTimeout(timeoutTask, call.getRpcTimeout(), TimeUnit.MILLISECONDS);
        }
        if (!connected) {
            return call;
        }
    }
    writeRequest(call);
    return call;
}

From source file:org.apache.hive.spark.client.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*ww w  . ja va 2  s  .c om*/
public static Promise<Rpc> createClient(Map<String, String> config, final NioEventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    final RpcConfiguration rpcConf = new RpcConfiguration(config);
    int connectTimeoutMs = (int) rpcConf.getConnectTimeoutMs();

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, rpcConf.getServerConnectTimeoutMs(),
            TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(rpcConf, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(rpcConf, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:org.apache.hive.spark.client.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation./*w w  w  .  j a  va 2 s . c  o m*/
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Preconditions.checkArgument(msg != null);
    Preconditions.checkState(channel.isActive(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = createPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}