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

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

Introduction

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

Prototype

Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);

Source Link

Document

Adds the specified listener to this future.

Usage

From source file:net.wessendorf.microprofile.service.PushSender.java

License:Apache License

public void sendPushs(final String payload) {

    final List<String> tokens = TokenDB.loadDeviceTokens();
    final String pushJobID = UUID.randomUUID().toString();

    ApnsClient apnsClient = null;/*from   w w  w.  ja  v a 2  s  .c  o m*/
    {
        try {
            apnsClient = receiveApnsConnection("net.wessendorf.something");
        } catch (IllegalArgumentException iae) {
            logger.error(iae.getMessage(), iae);
        }
    }

    if (apnsClient.isConnected()) {

        for (final String token : tokens) {

            final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token,
                    "net.wessendorf.something", payload);
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient
                    .sendNotification(pushNotification);

            notificationSendFuture.addListener(
                    new GenericFutureListener<Future<? super PushNotificationResponse<SimpleApnsPushNotification>>>() {
                        @Override
                        public void operationComplete(
                                Future<? super PushNotificationResponse<SimpleApnsPushNotification>> future)
                                throws Exception {

                            // we could submit "something" to APNs
                            if (future.isSuccess()) {
                                handlePushNotificationResponsePerToken(pushJobID, notificationSendFuture.get());
                            }
                        }
                    });
        }

    } else {
        logger.error("Unable to send notifications, client is not connected");
    }
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.SharedEventLoopGroup.java

License:Apache License

@Override
public Future<?> shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) {
    if (channelFactoryCount.decrementAndGet() == 0) {
        shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() {
            @Override/*from   ww w.ja  v  a2  s.c om*/
            public void run() {
                synchronized (SharedEventLoopGroup.class) {
                    if (shutdown.get() != null) {
                        Future<?> future = SharedEventLoopGroup.super.shutdownGracefully(l, l2, timeUnit);
                        future.addListener(new FutureListener<Object>() {
                            @Override
                            public void operationComplete(Future<Object> future) throws Exception {
                                if (future.isSuccess()) {
                                    terminationPromise.setSuccess(null);
                                } else {
                                    terminationPromise.setFailure(future.cause());
                                }
                            }
                        });
                        instance = null;
                    }
                }
            }

        }, 10, 10, TimeUnit.SECONDS));
    }
    return terminationPromise;
}

From source file:org.apache.activemq.artemis.core.remoting.impl.netty.SharedNioEventLoopGroup.java

License:Apache License

@Override
public Future<?> shutdownGracefully(final long l, final long l2, final TimeUnit timeUnit) {
    if (nioChannelFactoryCount.decrementAndGet() == 0) {
        shutdown.compareAndSet(null, next().scheduleAtFixedRate(new Runnable() {
            @Override/*from  w  w  w . jav a  2s.  co  m*/
            public void run() {
                synchronized (SharedNioEventLoopGroup.class) {
                    if (shutdown.get() != null) {
                        Future<?> future = SharedNioEventLoopGroup.super.shutdownGracefully(l, l2, timeUnit);
                        future.addListener(new FutureListener<Object>() {
                            @Override
                            public void operationComplete(Future future) throws Exception {
                                if (future.isSuccess()) {
                                    terminationPromise.setSuccess(null);
                                } else {
                                    terminationPromise.setFailure(future.cause());
                                }
                            }
                        });
                        instance = null;
                    }
                }
            }

        }, 10, 10, TimeUnit.SECONDS));
    }
    return terminationPromise;
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static FanOutOneBlockAsyncDFSOutput createOutput(DistributedFileSystem dfs, String src,
        boolean overwrite, boolean createParent, short replication, long blockSize, EventLoop eventLoop)
        throws IOException {
    Configuration conf = dfs.getConf();
    FSUtils fsUtils = FSUtils.getInstance(dfs, conf);
    DFSClient client = dfs.getClient();//from w  ww.ja va  2 s .c  om
    String clientName = client.getClientName();
    ClientProtocol namenode = client.getNamenode();
    HdfsFileStatus stat;
    try {
        stat = FILE_CREATER.create(namenode, src,
                FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(conf)), clientName,
                new EnumSetWritable<CreateFlag>(overwrite ? EnumSet.of(CREATE, OVERWRITE) : EnumSet.of(CREATE)),
                createParent, replication, blockSize);
    } catch (Exception e) {
        if (e instanceof RemoteException) {
            throw (RemoteException) e;
        } else {
            throw new NameNodeException(e);
        }
    }
    beginFileLease(client, src, stat.getFileId());
    boolean succ = false;
    LocatedBlock locatedBlock = null;
    List<Future<Channel>> futureList = null;
    try {
        DataChecksum summer = createChecksum(client);
        locatedBlock = BLOCK_ADDER.addBlock(namenode, src, client.getClientName(), null, null, stat.getFileId(),
                null);
        List<Channel> datanodeList = new ArrayList<>();
        futureList = connectToDataNodes(conf, client, clientName, locatedBlock, 0L, 0L, PIPELINE_SETUP_CREATE,
                summer, eventLoop);
        for (Future<Channel> future : futureList) {
            // fail the creation if there are connection failures since we are fail-fast. The upper
            // layer should retry itself if needed.
            datanodeList.add(future.syncUninterruptibly().getNow());
        }
        CryptoCodec cryptocodec = createCryptoCodec(conf, stat, client);
        FanOutOneBlockAsyncDFSOutput output = new FanOutOneBlockAsyncDFSOutput(conf, fsUtils, dfs, client,
                namenode, clientName, src, stat.getFileId(), locatedBlock, cryptocodec, eventLoop, datanodeList,
                summer, ALLOC);
        succ = true;
        return output;
    } finally {
        if (!succ) {
            if (futureList != null) {
                for (Future<Channel> f : futureList) {
                    f.addListener(new FutureListener<Channel>() {

                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                future.getNow().close();
                            }
                        }
                    });
                }
            }
            endFileLease(client, src, stat.getFileId());
            fsUtils.recoverFileLease(dfs, new Path(src), conf, new CancelOnClose(client));
        }
    }
}

From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputHelper.java

License:Apache License

private static FanOutOneBlockAsyncDFSOutput createOutput(DistributedFileSystem dfs, String src,
        boolean overwrite, boolean createParent, short replication, long blockSize, EventLoop eventLoop)
        throws IOException {
    Configuration conf = dfs.getConf();
    FSUtils fsUtils = FSUtils.getInstance(dfs, conf);
    DFSClient client = dfs.getClient();/*from   w  w w .  j av  a 2  s.c  om*/
    String clientName = client.getClientName();
    ClientProtocol namenode = client.getNamenode();
    HdfsFileStatus stat;
    try {
        stat = FILE_CREATER.create(namenode, src,
                FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(conf)), clientName,
                new EnumSetWritable<CreateFlag>(overwrite ? EnumSet.of(CREATE, OVERWRITE) : EnumSet.of(CREATE)),
                createParent, replication, blockSize);
    } catch (Exception e) {
        if (e instanceof RemoteException) {
            throw (RemoteException) e;
        } else {
            throw new NameNodeException(e);
        }
    }
    beginFileLease(client, src, stat.getFileId());
    boolean succ = false;
    LocatedBlock locatedBlock = null;
    List<Future<Channel>> futureList = null;
    try {
        DataChecksum summer = createChecksum(client);
        locatedBlock = namenode.addBlock(src, client.getClientName(), null, null, stat.getFileId(), null);
        List<Channel> datanodeList = new ArrayList<>();
        futureList = connectToDataNodes(conf, clientName, locatedBlock, 0L, 0L, PIPELINE_SETUP_CREATE, summer,
                eventLoop);
        for (Future<Channel> future : futureList) {
            // fail the creation if there are connection failures since we are fail-fast. The upper
            // layer should retry itself if needed.
            datanodeList.add(future.syncUninterruptibly().getNow());
        }
        succ = true;
        return new FanOutOneBlockAsyncDFSOutput(conf, fsUtils, dfs, client, namenode, clientName, src,
                stat.getFileId(), locatedBlock, eventLoop, datanodeList, summer, ALLOC);
    } finally {
        if (!succ) {
            if (futureList != null) {
                for (Future<Channel> f : futureList) {
                    f.addListener(new FutureListener<Channel>() {

                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                future.getNow().close();
                            }
                        }
                    });
                }
            }
            endFileLease(client, src, stat.getFileId());
            fsUtils.recoverFileLease(dfs, new Path(src), conf, new CancelOnClose(client));
        }
    }
}

From source file:org.apache.qpid.jms.transports.netty.NettySslTransport.java

License:Apache License

@Override
protected void handleConnected(final Channel channel) throws Exception {
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);

    Future<Channel> channelFuture = sslHandler.handshakeFuture();
    channelFuture.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from   w w  w.  j a v  a  2s.c om*/
        public void operationComplete(Future<Channel> future) throws Exception {
            if (future.isSuccess()) {
                LOG.trace("SSL Handshake has completed: {}", channel);
                connectionEstablished(channel);
            } else {
                LOG.trace("SSL Handshake has failed: {}", channel);
                connectionFailed(IOExceptionSupport.create(future.cause()));
            }
        }
    });
}

From source file:org.apache.tinkerpop.gremlin.server.handler.IteratorHandler.java

License:Apache License

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    if (msg instanceof Pair) {
        try {//from ww  w  .j a va  2 s. c  o m
            final Pair pair = (Pair) msg;
            final Iterator itty = (Iterator) pair.getValue1();
            final RequestMessage requestMessage = (RequestMessage) pair.getValue0();

            // the batch size can be overriden by the request
            final int resultIterationBatchSize = (Integer) requestMessage.optionalArgs(Tokens.ARGS_BATCH_SIZE)
                    .orElse(settings.resultIterationBatchSize);

            // timer for the total serialization time
            final StopWatch stopWatch = new StopWatch();

            final EventExecutorGroup executorService = ctx.executor();
            final Future<?> iteration = executorService.submit((Callable<Void>) () -> {
                logger.debug("Preparing to iterate results from - {} - in thread [{}]", requestMessage,
                        Thread.currentThread().getName());

                stopWatch.start();

                List<Object> aggregate = new ArrayList<>(resultIterationBatchSize);
                while (itty.hasNext()) {
                    aggregate.add(itty.next());

                    // send back a page of results if batch size is met or if it's the end of the results being
                    // iterated
                    if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) {
                        final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT
                                : ResponseStatusCode.SUCCESS;
                        ctx.writeAndFlush(
                                ResponseMessage.build(requestMessage).code(code).result(aggregate).create());
                        aggregate = new ArrayList<>(resultIterationBatchSize);
                    }

                    stopWatch.split();
                    if (stopWatch.getSplitTime() > settings.serializedResponseTimeout)
                        throw new TimeoutException(
                                "Serialization of the entire response exceeded the serializeResponseTimeout setting");

                    stopWatch.unsplit();
                }

                return null;
            });

            iteration.addListener(f -> {
                stopWatch.stop();

                if (!f.isSuccess()) {
                    final String errorMessage = String.format(
                            "Response iteration and serialization exceeded the configured threshold for request [%s] - %s",
                            msg, f.cause().getMessage());
                    logger.warn(errorMessage);
                    ctx.writeAndFlush(
                            ResponseMessage.build(requestMessage).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT)
                                    .statusMessage(errorMessage).create());
                }
            });
        } finally {
            ReferenceCountUtil.release(msg);
        }

    } else {
        ctx.write(msg, promise);
    }
}

From source file:org.asynchttpclient.resolver.RequestHostnameResolver.java

License:Open Source License

public Future<List<InetSocketAddress>> resolve(Request request, ProxyServer proxy,
        AsyncHandler<?> asyncHandler) {

    Uri uri = request.getUri();/*from   w  w w.jav  a 2s.c o  m*/
    final Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();

    if (request.getAddress() != null) {
        List<InetSocketAddress> resolved = Collections
                .singletonList(new InetSocketAddress(request.getAddress(), uri.getExplicitPort()));
        return promise.setSuccess(resolved);
    }

    // don't notify on explicit address
    final AsyncHandlerExtensions asyncHandlerExtensions = request.getAddress() == null
            ? toAsyncHandlerExtensions(asyncHandler)
            : null;
    final String name;
    final int port;

    if (proxy != null && !proxy.isIgnoredForHost(uri.getHost())) {
        name = proxy.getHost();
        port = uri.isSecured() ? proxy.getSecuredPort() : proxy.getPort();
    } else {
        name = uri.getHost();
        port = uri.getExplicitPort();
    }

    if (asyncHandlerExtensions != null)
        asyncHandlerExtensions.onHostnameResolutionAttempt(name);

    final Future<List<InetAddress>> whenResolved = request.getNameResolver().resolveAll(name);

    whenResolved.addListener(new SimpleFutureListener<List<InetAddress>>() {

        @Override
        protected void onSuccess(List<InetAddress> value) throws Exception {
            ArrayList<InetSocketAddress> socketAddresses = new ArrayList<>(value.size());
            for (InetAddress a : value) {
                socketAddresses.add(new InetSocketAddress(a, port));
            }
            if (asyncHandlerExtensions != null) {
                asyncHandlerExtensions.onHostnameResolutionSuccess(name, socketAddresses);
            }
            promise.trySuccess(socketAddresses);
        }

        @Override
        protected void onFailure(Throwable t) throws Exception {
            if (asyncHandlerExtensions != null) {
                asyncHandlerExtensions.onHostnameResolutionFailure(name, t);
            }
            promise.tryFailure(t);
        }
    });

    return promise;
}

From source file:org.asynchttpclient.resolver.RequestNameResolver.java

License:Open Source License

public Future<List<InetSocketAddress>> resolve(Request request, ProxyServer proxy,
        AsyncHandler<?> asyncHandler) {

    Uri uri = request.getUri();/*  w  ww.  ja v  a 2s .c  o m*/

    if (request.getAddress() != null) {
        List<InetSocketAddress> resolved = Collections
                .singletonList(new InetSocketAddress(request.getAddress(), uri.getExplicitPort()));
        Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();
        return promise.setSuccess(resolved);

    }

    // don't notify on explicit address
    final AsyncHandlerExtensions asyncHandlerExtensions = request.getAddress() == null
            ? toAsyncHandlerExtensions(asyncHandler)
            : null;
    final String name;
    final int port;

    if (proxy != null && !proxy.isIgnoredForHost(uri.getHost())) {
        name = proxy.getHost();
        port = uri.isSecured() ? proxy.getSecuredPort() : proxy.getPort();
    } else {
        name = uri.getHost();
        port = uri.getExplicitPort();
    }

    if (asyncHandlerExtensions != null)
        asyncHandlerExtensions.onDnsResolution(name);

    final Future<List<InetSocketAddress>> whenResolved = request.getNameResolver().resolve(name, port);

    if (asyncHandlerExtensions == null)
        return whenResolved;

    Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();

    whenResolved.addListener(new SimpleGenericFutureListener<List<InetSocketAddress>>() {

        @Override
        protected void onSuccess(List<InetSocketAddress> addresses) throws Exception {
            asyncHandlerExtensions.onDnsResolutionSuccess(name, addresses);
            promise.setSuccess(addresses);
        }

        @Override
        protected void onFailure(Throwable t) throws Exception {
            asyncHandlerExtensions.onDnsResolutionFailure(name, t);
            promise.setFailure(t);
        }
    });

    return promise;
}

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");
    }//  w w w .jav  a2  s.com
    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());
            }
        }
    });
}