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: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();//  www .  j  a  v  a  2 s .  c  o  m
        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.DnsNameResolverContext.java

License:Apache License

private void finishResolve() {
    if (!queriesInProgress.isEmpty()) {
        // If there are queries in progress, we should cancel it because we already finished the resolution.
        for (Iterator<Future<AddressedEnvelope<DnsResponse, InetSocketAddress>>> i = queriesInProgress
                .iterator(); i.hasNext();) {
            Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> f = i.next();
            i.remove();/*  w ww  . j av a  2s.c  o m*/

            if (!f.cancel(false)) {
                f.addListener(RELEASE_RESPONSE);
            }
        }
    }

    if (resolvedEntries != null) {
        // Found at least one resolved address.
        for (InternetProtocolFamily f : resolveAddressTypes) {
            if (finishResolve(f.addressType(), resolvedEntries)) {
                return;
            }
        }
    }

    // No resolved address found.
    final int tries = maxAllowedQueries - allowedQueries;
    final StringBuilder buf = new StringBuilder(64);

    buf.append("failed to resolve '").append(hostname).append('\'');
    if (tries > 1) {
        if (tries < maxAllowedQueries) {
            buf.append(" after ").append(tries).append(" queries ");
        } else {
            buf.append(". Exceeded max queries per resolve ").append(maxAllowedQueries).append(' ');
        }
    }
    if (trace != null) {
        buf.append(':').append(trace);
    }
    final UnknownHostException cause = new UnknownHostException(buf.toString());

    resolveCache.cache(hostname, cause, parent.ch.eventLoop());
    promise.tryFailure(cause);
}

From source file:io.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext)
        throws Exception {
    SslHandler sslHandler = null;//  ww w . j  a v  a2s  . com
    try {
        SSLEngine engine = helper.createEngine(sslContext);
        sslHandler = new SslHandler(engine);
        ctx.pipeline().replace(this, "ssl", sslHandler);
        Future<Channel> fut = sslHandler.handshakeFuture();
        fut.addListener(future -> {
            if (future.isSuccess()) {
                Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
                val.set(hostname);
                handshakeFuture.setSuccess(ctx.channel());
            } else {
                handshakeFuture.setFailure(future.cause());
            }
        });
        sslHandler = null;
    } finally {
        // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
        // transferred to the SslHandler.
        // See https://github.com/netty/netty/issues/5678
        if (sslHandler != null) {
            ReferenceCountUtil.safeRelease(sslHandler.engine());
        }
    }
}

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

License:Open Source License

@Override
public Future<?> addHandler(L handler) {
    Future<?> f;
    synchronized (this) {
        boolean wasEmpty = listeners.isEmpty();
        listeners.add(handler);// w  w w.j  a v  a2s  . c  om
        if (wasEmpty) {
            f = con.io().sendPacket(subscribe);
            lastFuture = f;
        } else {
            f = lastFuture;
        }
    }
    f.addListener(future -> {
        assert future == f;
        if (!future.isSuccess()) {
            removeHandler(handler);
        }
    });
    return f;

}

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

License:Open Source License

public Future<TeamspeakConnection> connect(SocketAddress addr, String username, String password) {
    final Future<TeamspeakConnection> connectFuture = connect(addr);
    final Future<TeamspeakConnection> result = FutureUtil.chainFutureFlat(this.group.next().newPromise(),
            connectFuture, con -> con.login(username, password));
    result.addListener(f -> {
        if (!f.isSuccess()) {

        }/*from  w  w w  .j  av a  2 s .c o m*/
    });
    return result;
}

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  www. j av a 2s . c  om*/
        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 -> {
        assert ignored == future;
        try {//from  w w w .j a v a2s .c  o  m
            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 -> {
        assert ignored == future;
        try {/* w  w w . j  a  v a2  s . co m*/
            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.melchor9000.net.NettyFuture.java

License:Open Source License

NettyFuture(@NotNull io.netty.util.concurrent.Future<ReturnType> future, @NotNull IOService service,
        @Nullable Procedure whenCancelled) {
    this.future = future;
    this.service = service;
    this.whenCancelled = whenCancelled;
    future.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super ReturnType>>() {
        @Override//  w  w w  .  j ava  2 s.  co  m
        public void operationComplete(io.netty.util.concurrent.Future<? super ReturnType> future)
                throws Exception {
            if (timeoutFuture != null)
                timeoutFuture.cancel(false);
        }
    });
}

From source file:me.melchor9000.net.NettyFuture.java

License:Open Source License

@NotNull
public Future<ReturnType> whenDone(@NotNull final Callback<Future<ReturnType>> cbk) {
    future.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super ReturnType>>() {
        @Override// w w w  . j  av  a  2s .  co m
        public void operationComplete(io.netty.util.concurrent.Future<? super ReturnType> future)
                throws Exception {
            try {
                cbk.call(NettyFuture.this);
            } catch (Exception exception) {
                throw exception;
            } catch (Throwable throwable) {
                System.err.println("Caught a Throwable in " + cbk.getClass().getName() + ".call()");
                throwable.printStackTrace();
            }
        }
    });
    return this;
}