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:org.eclipse.californium.elements.tcp.TlsClientConnector.java

License:Open Source License

/**
 * {@inheritDoc}/*  w ww .ja  v  a  2s . c  o m*/
 * 
 * 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/* w  w  w  . j  a v a2 s.  c  o m*/
 *
 * @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//ww w .j a v a2  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// w w w .  j  a  v  a2s  .co  m
 *
 * @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.eclipse.neoscada.protocol.iec60870.client.Client.java

License:Open Source License

@Override
public void close() throws Exception {
    synchronized (this) {
        if (this.channel != null) {
            this.channel.close();
            this.channel = null;
        }/*  w  w  w  .ja  va  2  s . c  o  m*/

        for (final Module module : this.modules) {
            module.dispose();
        }
    }

    logger.debug("Shutting down main group");
    final Future<?> f = this.group.shutdownGracefully();
    f.addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(final Future<Object> arg0) throws Exception {
            disposeExecutor();
        }
    });
}

From source file:org.fiware.kiara.netty.ListenableConstantFutureAdapter.java

License:Open Source License

@Override
public void addListener(final Runnable r, final Executor exctr) {
    future.addListener(new GenericFutureListener() {
        @Override//from  w w w  . j  a  v a  2s  .  c  o  m
        public void operationComplete(Future future) throws Exception {
            exctr.execute(r);
        }
    });
}

From source file:org.jboss.aerogear.unifiedpush.message.sender.apns.PushyApnsSender.java

License:Apache License

@Override
public void sendPushMessage(final Variant variant, final Collection<String> tokens,
        final UnifiedPushMessage pushMessage, final String pushMessageInformationId,
        final NotificationSenderCallback senderCallback) {
    // no need to send empty list
    if (tokens.isEmpty()) {
        return;//w  w  w.  ja  v  a2  s.c  om
    }

    final iOSVariant iOSVariant = (iOSVariant) variant;

    final String payload;
    {
        try {
            payload = createPushPayload(pushMessage.getMessage(), pushMessageInformationId);
        } catch (IllegalArgumentException iae) {
            logger.info(iae.getMessage(), iae);
            senderCallback.onError("Nothing sent to APNs since the payload is too large");
            return;
        }
    }

    final ApnsClient apnsClient;
    {
        try {
            apnsClient = receiveApnsConnection(iOSVariant);
        } catch (IllegalArgumentException iae) {
            logger.error(iae.getMessage(), iae);
            senderCallback.onError(String.format("Unable to connect to APNs (%s))", iae.getMessage()));
            return;
        }
    }

    if (apnsClient.isConnected()) {

        // we have managed to connect and will send tokens ;-)
        senderCallback.onSuccess();

        final String defaultApnsTopic = ApnsUtil.readDefaultTopic(iOSVariant.getCertificate(),
                iOSVariant.getPassphrase().toCharArray());
        logger.debug("sending payload for all tokens for {} to APNs ({})", iOSVariant.getVariantID(),
                defaultApnsTopic);

        tokens.forEach(token -> {
            final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token,
                    defaultApnsTopic, payload);
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient
                    .sendNotification(pushNotification);

            notificationSendFuture.addListener(future -> {

                if (future.isSuccess()) {
                    handlePushNotificationResponsePerToken(notificationSendFuture.get());
                }
            });
        });

    } else {
        logger.error("Unable to send notifications, client is not connected. Removing from cache pool");
        senderCallback.onError("Unable to send notifications, client is not connected");
        variantUpdateEventEvent.onNext(new iOSVariantUpdateEvent(iOSVariant));
    }
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.DefaultHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final AbstractCommand msg) throws Exception {
    Callable<AbstractCommand> callable = msg;

    final Future<AbstractCommand> future = executor.submit(callable);

    future.addListener(new GenericFutureListener<Future<Object>>() {
        @Override//from ww  w  .  j  a  va2 s  .  c  o  m
        public void operationComplete(final Future<Object> future) throws Exception {
            LOG.trace("DefaultHandler().operationComplete...");
            if (future.isSuccess()) {
                ctx.writeAndFlush(future.get());
            } else {
                ctx.fireExceptionCaught(future.cause());
            }
        }
    });
}

From source file:org.opendaylight.bgpcep.pcep.topology.provider.AbstractTopologySessionListener.java

License:Open Source License

protected final synchronized ListenableFuture<OperationResult> sendMessage(final Message message,
        final S requestId, final Metadata metadata) {
    final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
    this.listenerState.updateStatefulSentMsg(message);
    final PCEPRequest req = new PCEPRequest(metadata);
    this.requests.put(requestId, req);
    final int rpcTimeout = serverSessionManager.getRpcTimeout();
    LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
    if (rpcTimeout > 0) {
        setupTimeoutHandler(requestId, req, rpcTimeout);
    }//w  w w .  j a  v  a2s.c om

    f.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(final io.netty.util.concurrent.Future<Void> future) {
            if (!future.isSuccess()) {
                synchronized (AbstractTopologySessionListener.this) {
                    AbstractTopologySessionListener.this.requests.remove(requestId);
                }
                req.done(OperationResults.UNSENT);
                LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
            } else {
                req.sent();
                LOG.trace("Request {} sent to peer (object {})", requestId, req);
            }
        }
    });

    return req.getFuture();
}

From source file:org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator.java

License:Open Source License

@Override
protected final void startNegotiation() {
    final Optional<SslHandler> sslHandler = getSslHandler(channel);
    if (sslHandler.isPresent()) {
        Future<Channel> future = sslHandler.get().handshakeFuture();
        future.addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//from  w  ww .  j a va  2s  . c om
            public void operationComplete(final Future<? super Channel> future) {
                Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
                LOG.debug("Ssl handshake complete");
                start();
            }
        });
    } else {
        start();
    }
}