Example usage for io.netty.channel ChannelPromise addListener

List of usage examples for io.netty.channel ChannelPromise addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise addListener.

Prototype

@Override
    ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:org.elasticsearch.transport.netty4.Netty4TcpChannel.java

License:Apache License

@Override
public void sendMessage(BytesReference reference, ActionListener<Void> listener) {
    ChannelPromise writePromise = channel.newPromise();
    writePromise.addListener(f -> {
        if (f.isSuccess()) {
            listener.onResponse(null);//ww w . j av  a2 s  . c o  m
        } else {
            final Throwable cause = f.cause();
            Netty4Utils.maybeDie(cause);
            if (cause instanceof Error) {
                listener.onFailure(new Exception(cause));
            } else {
                listener.onFailure((Exception) cause);
            }
        }
    });
    channel.writeAndFlush(Netty4Utils.toByteBuf(reference), writePromise);

    if (channel.eventLoop().isShutdown()) {
        listener.onFailure(new TransportException("Cannot send message, event loop is shutting down."));
    }
}

From source file:org.elasticsearch.transport.netty4.NettyTcpChannel.java

License:Apache License

@Override
public void sendMessage(BytesReference reference, ActionListener<Void> listener) {
    ChannelPromise writePromise = channel.newPromise();
    writePromise.addListener(f -> {
        if (f.isSuccess()) {
            listener.onResponse(null);//from w  w  w .ja  v  a  2  s  .c  o  m
        } else {
            final Throwable cause = f.cause();
            Netty4Utils.maybeDie(cause);
            assert cause instanceof Exception;
            listener.onFailure((Exception) cause);
        }
    });
    channel.writeAndFlush(Netty4Utils.toByteBuf(reference), writePromise);

    if (channel.eventLoop().isShutdown()) {
        listener.onFailure(new TransportException("Cannot send message, event loop is shutting down."));
    }
}

From source file:org.graylog2.inputs.transports.netty.PromiseFailureHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    promise.addListener(Listener.INSTANCE);
    super.write(ctx, msg, promise);
}

From source file:org.jupiter.transport.netty.handler.IdleStateChecker.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (writerIdleTimeMillis > 0 || allIdleTimeMillis > 0) {
        if (promise.isVoid()) {
            firstWriterIdleEvent = firstAllIdleEvent = true;
            lastWriteTime = SystemClock.millisClock().now(); // make hb for firstWriterIdleEvent and firstAllIdleEvent
        } else {/*from w w  w  .j  av a 2s  .co m*/
            promise.addListener(writeListener);
        }
    }
    ctx.write(msg, promise);
}

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a array of {@link Message}s and returns the {@link ChannelFuture}.
 *
 * @param messages The messages/*  w w w .java  2  s .c o  m*/
 * @return The channel future
 */
public ChannelFuture sendWithFuture(Message... messages) {
    checkNotNull(messages, "messages");
    checkArgument(messages.length != 0, "messages cannot be empty");
    final ChannelPromise promise = this.channel.newPromise();
    if (!this.channel.isActive()) {
        return promise;
    }
    promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    // Don't bother checking if we are in the event loop,
    // there is only one message.
    if (messages.length == 1) {
        this.channel.writeAndFlush(messages[0], promise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        final ChannelPromise voidPromise = this.channel.voidPromise();
        if (eventLoop.inEventLoop()) {
            final int last = messages.length - 1;
            for (int i = 0; i < last; i++) {
                ReferenceCountUtil.retain(messages[i]);
                this.channel.writeAndFlush(messages[i], voidPromise);
            }
            ReferenceCountUtil.retain(messages[last]);
            this.channel.writeAndFlush(messages[last], promise);
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation

            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            messages0.forEach(ReferenceCountUtil::retain);
            eventLoop.submit(() -> {
                final Iterator<Message> it0 = messages0.iterator();
                do {
                    final Message message0 = it0.next();
                    // Only use a normal channel promise for the last message
                    this.channel.writeAndFlush(message0, it0.hasNext() ? voidPromise : promise);
                } while (it0.hasNext());
            });
        }
    }
    return promise;
}

From source file:org.lanternpowered.server.network.NetworkSession.java

License:MIT License

/**
 * Sends a iterable of {@link Message}s.
 *
 * @param messages The messages/*from  w w  w .j  a va  2 s  . co m*/
 */
public ChannelFuture sendWithFuture(Iterable<Message> messages) {
    checkNotNull(messages, "messages");
    final Iterator<Message> it = messages.iterator();
    checkArgument(it.hasNext(), "messages cannot be empty");
    final ChannelPromise promise = this.channel.newPromise();
    if (!this.channel.isActive()) {
        return promise;
    }
    promise.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    Message message = it.next();
    // Don't bother checking if we are in the event loop,
    // there is only one message.
    if (!it.hasNext()) {
        this.channel.writeAndFlush(message, promise);
    } else {
        final EventLoop eventLoop = this.channel.eventLoop();
        final ChannelPromise voidPromise = this.channel.voidPromise();
        if (eventLoop.inEventLoop()) {
            while (true) {
                final boolean next = it.hasNext();
                // Only use a normal channel promise for the last message
                this.channel.writeAndFlush(message, next ? voidPromise : promise);
                if (!next) {
                    break;
                }
                message = it.next();
                ReferenceCountUtil.retain(message);
            }
        } else {
            // If there are more then one message, combine them inside the
            // event loop to reduce overhead of wakeup calls and object creation

            // Create a copy of the list, to avoid concurrent modifications
            final List<Message> messages0 = ImmutableList.copyOf(messages);
            messages0.forEach(ReferenceCountUtil::retain);
            eventLoop.submit(() -> {
                final Iterator<Message> it0 = messages0.iterator();
                do {
                    final Message message0 = it0.next();
                    // Only use a normal channel promise for the last message
                    this.channel.writeAndFlush(message0, it0.hasNext() ? voidPromise : promise);
                } while (it0.hasNext());
            });
        }
    }
    return promise;
}

From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.SshHandler.java

License:Open Source License

@Override
public void connect(final ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) {
    ctx.connect(remoteAddress, localAddress, promise);

    promise.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) {
            sshClientAdapter.start(ctx);
        }/*from  w  ww .  j a  va 2s . com*/
    });
}

From source file:org.opendaylight.controller.netconf.util.handler.ssh.SshHandler.java

License:Open Source License

@Override
public void connect(final ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {
    ctx.connect(remoteAddress, localAddress, promise);

    promise.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            sshClientAdapter.start(ctx);
        }//w w  w .j a va 2 s.  co m
    });
}

From source file:org.opendaylight.netconf.client.TcpClientChannelInitializer.java

License:Open Source License

@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
    final Future<NetconfClientSession> negotiationFuture = promise;

    //We have to add this channel outbound handler to channel pipeline, in order
    //to get notifications from netconf negotiatior. Set connection promise to
    //success only after successful negotiation.
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
        ChannelPromise connectPromise;//ww  w .  j a  va 2s .c o m
        GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;

        @Override
        public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
                final SocketAddress localAddress, final ChannelPromise channelPromise) throws Exception {
            connectPromise = channelPromise;
            ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);

            negotiationFutureListener = new GenericFutureListener<Future<NetconfClientSession>>() {
                @Override
                public void operationComplete(final Future<NetconfClientSession> future) throws Exception {
                    if (future.isSuccess()) {
                        connectPromise.setSuccess();
                    }
                }
            };

            tcpConnectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(final Future<? super Void> future) throws Exception {
                    if (future.isSuccess()) {
                        //complete connection promise with netconf negotiation future
                        negotiationFuture.addListener(negotiationFutureListener);
                    } else {
                        connectPromise.setFailure(future.cause());
                    }
                }
            });
            ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
        }

        @Override
        public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
            // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
            if (connectPromise.isSuccess()) {
                ctx.fireChannelInactive();
            }

            //If connection promise is not already set, it means negotiation failed
            //we must set connection promise to failure
            if (!connectPromise.isDone()) {
                connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
            }

            //Remove listener from negotiation future, we don't want notifications
            //from negotiation anymore
            negotiationFuture.removeListener(negotiationFutureListener);

            super.disconnect(ctx, promise);
            promise.setSuccess();
        }
    });

    super.initialize(ch, promise);
}

From source file:org.teiid.transport.PgBackendProtocol.java

License:Open Source License

@Override
public void sendSslResponse() {
    SSLEngine engine = null;//from w  w w  . j  av  a 2  s.  c o  m
    try {
        if (config != null) {
            engine = config.getServerSSLEngine();
        }
    } catch (IOException e) {
        LogManager.logError(LogConstants.CTX_ODBC, e, RuntimePlugin.Util
                .gs(secureData() ? RuntimePlugin.Event.TEIID40122 : RuntimePlugin.Event.TEIID40016));
    } catch (GeneralSecurityException e) {
        LogManager.logError(LogConstants.CTX_ODBC, e, RuntimePlugin.Util
                .gs(secureData() ? RuntimePlugin.Event.TEIID40122 : RuntimePlugin.Event.TEIID40016));
    }
    ByteBuf buffer = Unpooled.buffer(1);
    ChannelPromise promise = this.ctx.newPromise();
    if (engine == null) {
        if (secureData()) {
            sendErrorResponse(RuntimePlugin.Util.gs(RuntimePlugin.Event.TEIID40124));
            return;
        }
        buffer.writeByte('N');
    } else {
        promise.addListener(new SSLEnabler(engine));
        buffer.writeByte('S');
    }
    this.ctx.writeAndFlush(buffer, promise);
}