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

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

Introduction

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

Prototype

V getNow();

Source Link

Document

Return the result without blocking.

Usage

From source file:org.asynchttpclient.netty.SimpleFutureListener.java

License:Open Source License

@Override
public final void operationComplete(Future<V> future) throws Exception {
    if (future.isSuccess()) {
        onSuccess(future.getNow());
    } else {//w w  w  .ja  v a2 s  .c o m
        onFailure(future.cause());
    }
}

From source file:org.asynchttpclient.providers.netty.request.NettyConnectListener.java

License:Apache License

public void onFutureSuccess(final Channel channel) throws ConnectException {
    Channels.setDefaultAttribute(channel, future);
    final HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
    final SslHandler sslHandler = Channels.getSslHandler(channel);
    if (hostnameVerifier != null && sslHandler != null) {
        final String host = future.getURI().getHost();
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//from   w w  w  . j a  v  a 2 s  .com
            public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception {
                if (handshakeFuture.isSuccess()) {
                    Channel channel = (Channel) handshakeFuture.getNow();
                    SSLEngine engine = sslHandler.engine();
                    SSLSession session = engine.getSession();

                    LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}",
                            session.toString(), Base64.encode(session.getId()), session.isValid(), host);
                    if (!hostnameVerifier.verify(host, session)) {
                        ConnectException exception = new ConnectException("HostnameVerifier exception");
                        future.abort(exception);
                        throw exception;
                    } else {
                        requestSender.writeRequest(future, channel);
                    }
                }
            }
        });
    } else {
        requestSender.writeRequest(future, channel);
    }
}

From source file:org.asynchttpclient.providers.netty4.request.NettyConnectListener.java

License:Open Source License

private void onFutureSuccess(final Channel channel) throws ConnectException {
    Channels.setAttribute(channel, future);
    final HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
    final SslHandler sslHandler = ChannelManager.getSslHandler(channel.pipeline());
    if (hostnameVerifier != null && sslHandler != null) {
        final String host = future.getUri().getHost();
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override/*from  w  w w .  ja va 2s  .c  o m*/
            public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception {
                if (handshakeFuture.isSuccess()) {
                    Channel channel = (Channel) handshakeFuture.getNow();
                    SSLEngine engine = sslHandler.engine();
                    SSLSession session = engine.getSession();

                    LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}",
                            session.toString(), Base64.encode(session.getId()), session.isValid(), host);
                    if (hostnameVerifier.verify(host, session)) {
                        final AsyncHandler<T> asyncHandler = future.getAsyncHandler();
                        if (asyncHandler instanceof AsyncHandlerExtensions)
                            AsyncHandlerExtensions.class.cast(asyncHandler).onSslHandshakeCompleted();

                        writeRequest(channel);
                    } else {
                        onFutureFailure(channel, new ConnectException("HostnameVerifier exception"));
                    }
                } else {
                    onFutureFailure(channel, handshakeFuture.cause());
                }
            }
        });
    } else {
        writeRequest(channel);
    }
}

From source file:org.eclipse.californium.elements.tcp.TcpClientConnector.java

License:Open Source License

@Override
public void send(final RawData msg) {
    if (msg == null) {
        throw new NullPointerException("Message must not be null");
    }//  www . ja v a 2s .  co  m
    if (msg.isMulticast()) {
        LOGGER.warn("TcpConnector drops {} bytes to multicast {}:{}", msg.getSize(), msg.getAddress(),
                msg.getPort());
        msg.onError(new MulticastNotSupportedException("TCP doesn't support multicast!"));
        return;
    }
    if (workerGroup == null) {
        msg.onError(new IllegalStateException("TCP client connector not running!"));
        return;
    }
    InetSocketAddress addressKey = msg.getInetSocketAddress();
    final boolean connected = poolMap.contains(addressKey);
    final EndpointContextMatcher endpointMatcher = getEndpointContextMatcher();
    /* check, if a new connection should be established */
    if (endpointMatcher != null && !connected && !endpointMatcher.isToBeSent(msg.getEndpointContext(), null)) {
        LOGGER.warn("TcpConnector drops {} bytes to new {}:{}", msg.getSize(), msg.getAddress(), msg.getPort());
        msg.onError(new EndpointMismatchException("no connection"));
        return;
    }
    if (!connected) {
        msg.onConnecting();
    }
    final ChannelPool channelPool = poolMap.get(addressKey);
    Future<Channel> acquire = channelPool.acquire();
    acquire.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
            Throwable cause = null;
            if (future.isSuccess()) {
                Channel channel = future.getNow();
                try {
                    send(channel, endpointMatcher, msg);
                } catch (Throwable t) {
                    cause = t;
                } finally {
                    try {
                        channelPool.release(channel);
                    } catch (RejectedExecutionException e) {
                        LOGGER.debug("{}", e.getMessage());
                    }
                }
            } else if (future.isCancelled()) {
                cause = new CancellationException();
            } else {
                cause = future.cause();
            }
            if (cause != null) {
                if (cause instanceof ConnectTimeoutException) {
                    LOGGER.warn("{}", cause.getMessage());
                } else if (cause instanceof CancellationException) {
                    LOGGER.debug("{}", cause.getMessage());
                } else {
                    LOGGER.warn("Unable to open connection to {}", msg.getAddress(), future.cause());
                }
                msg.onError(future.cause());
            }
        }
    });
}

From source file:org.eclipse.californium.elements.tcp.TlsClientConnector.java

License:Open Source License

/**
 * {@inheritDoc}/* ww  w .j av a2 s  . com*/
 * 
 * Delay message sending after TLS handshake is completed.
 */
@Override
protected void send(final Channel channel, final EndpointContextMatcher endpointMatcher, final RawData msg) {
    final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler == null) {
        msg.onError(new IllegalStateException("Missing SslHandler"));
    } else {
        /*
         * Trigger handshake.
         */
        Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
        handshakeFuture.addListener(new GenericFutureListener<Future<Channel>>() {

            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                if (future.isSuccess()) {
                    EndpointContext context = contextUtil.buildEndpointContext(channel);
                    if (context == null || context.get(TlsEndpointContext.KEY_SESSION_ID) == null) {
                        msg.onError(new IllegalStateException("Missing TlsEndpointContext " + context));
                        return;
                    }
                    /*
                     * Handshake succeeded! 
                     * Call super.send() to actually send the message.
                     */
                    TlsClientConnector.super.send(future.getNow(), endpointMatcher, msg);
                } else if (future.isCancelled()) {
                    msg.onError(new CancellationException());
                } else {
                    msg.onError(future.cause());
                }
            }
        });
    }
}

From source file:org.eclipse.moquette.spi.impl.ProtocolProcessor.java

License:Open Source License

/**
 * ?token/*from   w w w.  j a  v  a  2s.com*/
 *
 * @param session
 * @param name
 * @param pwd
 * @param clientID
 */
private void authAsync(final ServerChannel session, final String name, final String pwd,
        final String clientID) {
    //??token
    //username?token
    Future<Boolean> f = taskExecutors.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return m_authenticator.checkValid(name, pwd, clientID);
        }
    });

    f.addListener(new GenericFutureListener<Future<Boolean>>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            boolean pass = future.getNow();
            if (!pass) {
                authFail(session);
            }
        }
    });
}

From source file:org.eclipse.moquette.spi.impl.ProtocolProcessor.java

License:Open Source License

/**
 * redis?topicack//from  w w  w.  j a  v a 2 s . c o  m
 *
 * @param session
 * @param msg
 * @param ackMessage
 */
private void unSubscribeAsync(final ServerChannel session, final UnsubscribeMessage msg,
        final UnsubAckMessage ackMessage) {
    Future<Boolean> f = taskExecutors.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            for (String topic : msg.topicFilters()) {
                TopicRouterRepository.clean(topic);
            }
            return true;
        }
    });

    f.addListener(new GenericFutureListener<Future<Boolean>>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            boolean result = future.getNow();
            if (result) {
                session.write(ackMessage);
            }
        }
    });
}

From source file:org.eclipse.moquette.spi.impl.ProtocolProcessor.java

License:Open Source License

/**
 * topicredisack/*from   w  w w  .  j av a 2s.com*/
 *
 * @param session
 * @param msg
 * @param ackMessage
 */
private void subscribeAsync(final ServerChannel session, final SubscribeMessage msg,
        final SubAckMessage ackMessage) {
    Future<Boolean> f = taskExecutors.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            for (SubscribeMessage.Couple req : msg.subscriptions()) {
                TopicRouterRepository.add(req.getTopicFilter());
            }
            return true;
        }
    });

    f.addListener(new GenericFutureListener<Future<Boolean>>() {
        @Override
        public void operationComplete(Future<Boolean> future) throws Exception {
            boolean result = future.getNow();
            if (result) {
                session.write(ackMessage);
            }
        }
    });
}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override//w  w w  . j av a 2  s  .c om
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
                //System.out.println(request.toString());
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:org.redisson.BaseRemoteService.java

License:Apache License

protected void awaitResultAsync(final RemoteInvocationOptions optionsCopy, final RemotePromise<Object> result,
        final RemoteServiceRequest request, final String responseName) {
    // poll for the response only if expected
    if (!optionsCopy.isResultExpected()) {
        return;//from   w w w.j a  v  a2s .c om
    }

    RBlockingQueue<RRemoteServiceResponse> responseQueue = redisson.getBlockingQueue(responseName, getCodec());
    RFuture<RRemoteServiceResponse> responseFuture = responseQueue
            .pollAsync(optionsCopy.getExecutionTimeoutInMillis(), TimeUnit.MILLISECONDS);
    responseFuture.addListener(new FutureListener<RRemoteServiceResponse>() {

        @Override
        public void operationComplete(Future<RRemoteServiceResponse> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }

            if (future.getNow() == null) {
                RemoteServiceTimeoutException e = new RemoteServiceTimeoutException("No response after "
                        + optionsCopy.getExecutionTimeoutInMillis() + "ms for request: " + request);
                result.tryFailure(e);
                return;
            }

            if (future.getNow() instanceof RemoteServiceCancelResponse) {
                result.doCancel();
                return;
            }

            RemoteServiceResponse response = (RemoteServiceResponse) future.getNow();
            if (response.getError() != null) {
                result.tryFailure(response.getError());
                return;
            }

            result.trySuccess(response.getResult());
        }
    });
}