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

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

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

License:Apache License

private void doResolveUncached(String hostname, Promise<InetAddress> promise, DnsCache resolveCache,
        boolean trySearchDomain) {
    if (trySearchDomain) {
        Promise<InetAddress> original = promise;
        promise = new DefaultPromise<>(executor());
        FutureListener<InetAddress> globalListener = future -> {
            if (future.isSuccess()) {
                original.setSuccess(future.getNow());
            } else {
                FutureListener<InetAddress> sdListener = new FutureListener<InetAddress>() {
                    int count;

                    @Override// w w  w  . j  a  va 2s .  c  o m
                    public void operationComplete(Future<InetAddress> future) throws Exception {
                        if (future.isSuccess()) {
                            original.trySuccess(future.getNow());
                        } else {
                            if (count < searchDomains.size()) {
                                String searchDomain = searchDomains.get(count++);
                                Promise<InetAddress> p = new DefaultPromise<>(executor());
                                doResolveUncached(hostname + "." + searchDomain, p, resolveCache, false);
                                p.addListener(this);
                            } else {
                                original.tryFailure(future.cause());
                            }
                        }
                    }
                };
                future.addListener(sdListener);
            }
        };
        promise.addListener(globalListener);
    }
    if (searchDomains(hostname)) {
        promise.tryFailure(new UnknownHostException(hostname));
    } else {
        final DnsNameResolverContext<InetAddress> ctx = new DnsNameResolverContext<InetAddress>(this, hostname,
                promise, resolveCache) {
            @Override
            protected boolean finishResolve(Class<? extends InetAddress> addressType,
                    List<DnsCacheEntry> resolvedEntries) {

                final int numEntries = resolvedEntries.size();
                for (int i = 0; i < numEntries; i++) {
                    final InetAddress a = resolvedEntries.get(i).address();
                    if (addressType.isInstance(a)) {
                        setSuccess(promise(), a);
                        return true;
                    }
                }
                return false;
            }
        };

        ctx.resolve();
    }
}

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

License:Apache License

private void query(InetSocketAddress nameServerAddr, final DnsQuestion question) {
    if (allowedQueries == 0 || promise.isCancelled()) {
        tryToFinishResolve();//from  ww  w . j  a v  a  2 s .  com
        return;
    }

    allowedQueries--;

    final Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> f = parent.query(nameServerAddr, question);
    queriesInProgress.add(f);

    f.addListener(new FutureListener<AddressedEnvelope<DnsResponse, InetSocketAddress>>() {
        @Override
        public void operationComplete(Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> future) {
            queriesInProgress.remove(future);

            if (promise.isDone() || future.isCancelled()) {
                return;
            }

            try {
                if (future.isSuccess()) {
                    onResponse(question, future.getNow());
                } else {
                    // Server did not respond or I/O error occurred; try again.
                    if (traceEnabled) {
                        addTrace(future.cause());
                    }
                    query(nameServerAddrs.next(), question);
                }
            } finally {
                tryToFinishResolve();
            }
        }
    });
}

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

License:Apache License

private void sendQuery(final DnsQuery query) {
    if (parent.channelFuture.isDone()) {
        writeQuery(query);/* w w w.  j a v  a 2s  .c om*/
    } else {
        parent.channelFuture.addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (future.isSuccess()) {
                    writeQuery(query);
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
    }
}

From source file:jj.repl.ReplServer.java

License:Apache License

@Listener
void configurationLoaded(ConfigurationLoaded configurationLoaded) {
    if (configuration.activate()) {

        if (server != null && port != configuration.port()) {

            server.group().terminationFuture().addListener(new GenericFutureListener<Future<Object>>() {
                @Override//from www  .  ja v  a 2 s .  c  om
                public void operationComplete(Future<Object> future) throws Exception {
                    // if this failed what do we do?
                    // just publish an emergency
                    if (future.isSuccess()) {
                        start();
                    } else {
                        publisher.publish(new Emergency(
                                "couldn't restart the REPL server.  The server may need to be restarted",
                                future.cause()));
                    }
                }
            });

            shutdown();

        } else if (server == null) {
            start();
        }

    } else if (server != null) {
        shutdown();
    }
}

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

License:Open Source License

public void start() {
    this.io.registerConnection(this);
    this.io.start();
    this.io.getChannel().pipeline().addLast(new SimpleChannelInboundHandler<Response>() {

        private Response lastPacket = null;
        //notifyclientleftview cfid=1 ctid=0 reasonid=8 reasonmsg=leaving clid=1
        //notifycliententerview cfid=0 ctid=1 reasonid=0 clid=4 client_unique_identifier=P+m\/uXn4o2nLwN5gOimuQcfQZIQ= client_nickname=Ferrybig client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=0 client_output_hardware=1 client_meta_data client_is_recording=0 client_database_id=2 client_channel_group_id=5 client_servergroups=6,10 client_away=0 client_away_message client_type=0 client_flag_avatar=12f359409d033f5eebcc821a5dbcecf5 client_talk_power=75 client_talk_request=0 client_talk_request_msg client_description client_is_talker=0 client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic=Ferrybig client_needed_serverquery_view_power=75 client_icon_id=0 client_is_channel_commander=0 client_country client_channel_group_inherited_channel_id=1 client_badges=Overwolf=0
        //notifyclientleftview cfid=72 ctid=0 reasonid=8 reasonmsg=leaving clid=4
        //notifycliententerview cfid=0 ctid=1 reasonid=0 clid=5 client_unique_identifier=P+m\/uXn4o2nLwN5gOimuQcfQZIQ= client_nickname=Ferrybig client_input_muted=0 client_output_muted=0 client_outputonly_muted=0 client_input_hardware=0 client_output_hardware=1 client_meta_data client_is_recording=0 client_database_id=2 client_channel_group_id=5 client_servergroups=6,10 client_away=0 client_away_message client_type=0 client_flag_avatar=12f359409d033f5eebcc821a5dbcecf5 client_talk_power=75 client_talk_request=0 client_talk_request_msg client_description client_is_talker=0 client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic=Ferrybig client_needed_serverquery_view_power=75 client_icon_id=0 client_is_channel_commander=0 client_country client_channel_group_inherited_channel_id=1 client_badges=Overwolf=0

        @Override//from  ww w . ja va  2  s .  c o m
        protected void messageReceived(ChannelHandlerContext ctx, Response msg) throws Exception {
            final Map<String, String> options = msg.getOptions();
            LOG.log(Level.FINE, "Handling packet: {0}", msg);
            switch (msg.getCmd()) {
            case "notifytextmessage": {
                Future<User> whoami = io.whoAmI();
                if (whoami.isSuccess()) {
                    handleMessage(msg, whoami.get());
                } else {
                    whoami.addListener(f -> {
                        assert f == whoami;
                        LOG.fine("Handling delayed message delivery because whoami is not known");
                        handleMessage(msg, whoami.get());
                    });
                }
            }
                break;
            case "notifycliententerview": {
                if (msg.equals(lastPacket)) {
                    LOG.log(Level.FINE,
                            "Dropping packet {0} because teamspeak usually sends dublicate packets when both channel and server listener is active",
                            msg);
                    lastPacket = null;
                    return;
                }
                lastPacket = msg;
                options.put("cid", options.get("ctid"));
                ShallowUser client = io.mapShallowUser(options);
                UnresolvedChannel from = "0".equals(options.get("cfid")) ? null
                        : getUnresolvedChannelById(parseInt(options.get("cfid")));
                ChangeReason reason = ChangeReason.getById(parseInt(options.get("reasonid")));
                ClientEnterViewEvent event;
                if (true && from == null) {
                    event = new ClientEnterViewEvent(client, client.getChannel(), reason, null);
                    serverHandler.callAll(ServerListener::onClientEnterView, event);
                } else {
                    // TODO: channel change event
                }

            }
                break;
            case "notifyclientleftview": {
                // TODO: leave notification
            }
                break;
            case "notifyserveredited": {
                final int invokerId = Integer.parseInt(options.get("invokerid"));
                final String invokerName = options.get("invokername");
                final String invokeruid = options.get("invokeruid");
                serverHandler.callAll(ServerListener::onEditServer,
                        new ServerEditEvent(ChangeReason.getById(parseInt(options.get("reasonid"))),
                                getUnresolvedNamedUser(invokerId, invokerName, invokeruid)));
            }
                break;
            case "notifytokenused": {
                // clid=5 cldbid=4 cluid=zhPQ0oNLH8boM42jlbgTWC6G\\/64= token=4oquHhp03YKofI4dYVBLWZ9Ik+Mf0M6ogomh5RsU tokencustomset token1=7 token2=0
                final UnresolvedUser client = getUnresolvedUserById(parseInt(options.get("clid")));
                final int databaseId = parseInt(options.get("cldbid"));
                final String uniqueId = options.get("cluid");
                final String token = options.get("token");
                final String tokencustomset = options.get("tokencustomset");
                final String token1 = options.get("token1");
                final String token2 = options.get("token2");
                tokenUsedHandler.callAll(TokenListener::onTokenUsed, new TokenUsedEvent(client, databaseId,
                        uniqueId, token, tokencustomset, token1, token2));
            }
                break;
            default: {
                LOG.log(Level.WARNING, "Unhandled packet: {0}", msg);
            }
            }
        }

    });
}

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   ww  w. j  a 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 -> {/*from w  w w . ja 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:net.epsilony.utils.codec.modbus.ModbusClientMaster.java

License:Open Source License

public CompletableFuture<ModbusResponse> request(ModbusRequest req) {
    final CompletableFuture<ModbusResponse> result = new CompletableFuture<>();

    result.whenComplete((res, ex) -> {
        if (transectionIdDispatcher != null) {
            int transectionId = req.getTransectionId();
            if (transectionId >= 0) {
                transectionIdDispatcher.repay(transectionId);
            }/*from  w  ww .jav  a 2 s . c om*/
        }
    });

    lock.lock();
    try {
        if (connectFuture == null) {
            connectFuture = genConnectFuture();
            connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    lock.lock();
                    try {
                        if (future.isSuccess()) {
                            channel = connectFuture.channel();
                            channel.closeFuture()
                                    .addListener(new GenericFutureListener<Future<? super Void>>() {

                                        @Override
                                        public void operationComplete(Future<? super Void> future)
                                                throws Exception {
                                            lock.lock();
                                            try {
                                                connectFuture = null;
                                                initializer.clearExceptionally(
                                                        new ConnectException("connection is closed!"));
                                                transectionIdDispatcher.reset();
                                            } finally {
                                                lock.unlock();
                                            }
                                        }
                                    });
                        } else {
                            connectFuture = null;
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }

        connectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                ChannelFuture channelFuture = (ChannelFuture) future;
                if (future.isSuccess()) {
                    if (null != transectionIdDispatcher) {
                        int transectionId = transectionIdDispatcher.borrow();
                        req.setTransectionId(transectionId);
                        if (transectionId < 0) {
                            result.completeExceptionally(new TransectionDispatcherEmptyException());
                            return;
                        }
                    }

                    try {
                        initializer.register(result, req);
                    } catch (Throwable ex) {
                        result.completeExceptionally(ex);
                        return;
                    }

                    ChannelFuture writeFuture = channelFuture.channel().writeAndFlush(req);
                    writeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {

                        @Override
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            if (!future.isSuccess()) {
                                if (future.isCancelled()) {
                                    initializer.removeExceptionally(req.getTransectionId(),
                                            new ConnectException("connection is canncelled"));
                                } else {
                                    initializer.removeExceptionally(req.getTransectionId(), future.cause());
                                }
                            }
                        }
                    });
                } else if (future.isCancelled()) {
                    result.completeExceptionally(new ConnectException("connection is canncelled"));
                } else {
                    result.completeExceptionally(future.cause());
                }
            }

        });
    } finally {
        lock.unlock();
    }

    return result;

}

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;/* w ww  .  ja  va  2  s. co  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.NettyConnector.java

License:Apache License

public Connection createConnection() {
    if (channelClazz == null) {
        return null;
    }//from   ww  w.j  av a 2s .c om

    // HORNETQ-907 - strip off IPv6 scope-id (if necessary)
    SocketAddress remoteDestination = new InetSocketAddress(host, port);
    InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress();
    if (inetAddress instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) inetAddress;
        if (inet6Address.getScopeId() != 0) {
            try {
                remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()),
                        ((InetSocketAddress) remoteDestination).getPort());
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

    ChannelFuture future;
    //port 0 does not work so only use local address if set
    if (localPort != 0) {
        SocketAddress localDestination;
        if (localAddress != null) {
            localDestination = new InetSocketAddress(localAddress, localPort);
        } else {
            localDestination = new InetSocketAddress(localPort);
        }
        future = bootstrap.connect(remoteDestination, localDestination);
    } else {
        future = bootstrap.connect(remoteDestination);
    }

    future.awaitUninterruptibly();

    if (future.isSuccess()) {
        final Channel ch = future.channel();
        SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000)) {
                if (handshakeFuture.isSuccess()) {
                    ChannelPipeline channelPipeline = ch.pipeline();
                    ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
                    channelHandler.active = true;
                } else {
                    ch.close().awaitUninterruptibly();
                    ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                    return null;
                }
            } else {
                //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
                ch.close().awaitUninterruptibly();
                return null;
            }

        }
        if (httpUpgradeEnabled) {
            // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
            try {
                //get this first incase it removes itself
                HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                URI uri = new URI("http", null, host, port, null, null, null);
                HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                        uri.getRawPath());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                final String endpoint = ConfigurationHelper.getStringProperty(
                        TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration);
                if (endpoint != null) {
                    request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                }

                // Get 16 bit nonce and base 64 encode it
                byte[] nonce = randomBytes(16);
                String key = base64(nonce);
                request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key);
                ch.attr(REMOTING_KEY).set(key);

                ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                // Send the HTTP request.
                ch.writeAndFlush(request);

                if (!httpUpgradeHandler.awaitHandshake()) {
                    return null;
                }
            } catch (URISyntaxException e) {
                ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                return null;
            }
        } else {
            ChannelPipeline channelPipeline = ch.pipeline();
            ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class);
            channelHandler.active = true;
        }

        // No acceptor on a client connection
        Listener connectionListener = new Listener();
        NettyConnection conn = new NettyConnection(configuration, ch, connectionListener,
                !httpEnabled && batchDelay > 0, false);
        connectionListener.connectionCreated(null, conn, protocolManager.getName());
        return conn;
    } else {
        Throwable t = future.cause();

        if (t != null && !(t instanceof ConnectException)) {
            ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
        }

        return null;
    }
}