Example usage for io.netty.channel ChannelFuture addListener

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * RowDescription (B)/*from www  . j  a va 2 s. co m*/
 * <p>
 * | 'T' | int32 len | int16 numCols
 * <p>
 * For each field:
 * <p>
 * | string name | int32 table_oid | int16 attr_num | int32 oid | int16 typlen | int32 type_modifier | int16 format_code
 * <p>
 * See https://www.postgresql.org/docs/current/static/protocol-message-formats.html
 */
static void sendRowDescription(Channel channel, Collection<Field> columns,
        @Nullable FormatCodes.FormatCode[] formatCodes) {
    int length = 4 + 2;
    int columnSize = 4 + 2 + 4 + 2 + 4 + 2;
    ByteBuf buffer = channel.alloc().buffer(length + (columns.size() * (10 + columnSize))); // use 10 as an estimate for columnName length

    buffer.writeByte('T');
    buffer.writeInt(0); // will be set at the end
    buffer.writeShort(columns.size());

    int idx = 0;
    for (Field column : columns) {
        byte[] nameBytes = column.path().outputName().getBytes(StandardCharsets.UTF_8);
        length += nameBytes.length + 1;
        length += columnSize;

        writeCString(buffer, nameBytes);
        buffer.writeInt(0); // table_oid
        buffer.writeShort(0); // attr_num

        PGType pgType = PGTypes.get(column.valueType());
        buffer.writeInt(pgType.oid());
        buffer.writeShort(pgType.typeLen());
        buffer.writeInt(pgType.typeMod());
        buffer.writeShort(FormatCodes.getFormatCode(formatCodes, idx).ordinal());

        idx++;
    }

    buffer.setInt(1, length);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace("sentRowDescription"));
    }
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * Send a message that just contains the msgType and the msg length
 */// ww w.  j a  v a2s . co  m
private static void sendShortMsg(Channel channel, char msgType, final String traceLogMsg) {
    ByteBuf buffer = channel.alloc().buffer(5);
    buffer.writeByte(msgType);
    buffer.writeInt(4);

    ChannelFuture channelFuture = channel.write(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener((ChannelFutureListener) future -> LOGGER.trace(traceLogMsg));
    }
}

From source file:io.crate.protocols.postgres.Messages.java

License:Apache License

/**
 * AuthenticationCleartextPassword (B)// w  ww .j a v a2 s. c o  m
 *
 * Byte1('R')
 * Identifies the message as an authentication request.
 *
 * Int32(8)
 * Length of message contents in bytes, including self.
 *
 * Int32(3)
 * Specifies that a clear-text password is required.
 *
 * @param channel The channel to write to.
 */
static void sendAuthenticationCleartextPassword(Channel channel) {
    ByteBuf buffer = channel.alloc().buffer(9);
    buffer.writeByte('R');
    buffer.writeInt(8);
    buffer.writeInt(3);
    ChannelFuture channelFuture = channel.writeAndFlush(buffer);
    if (LOGGER.isTraceEnabled()) {
        channelFuture.addListener(
                (ChannelFutureListener) future -> LOGGER.trace("sentAuthenticationCleartextPassword"));
    }
}

From source file:io.dyn.net.tcp.TcpClient.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override// w ww  .j a v a  2s .  c om
public T start() {
    if (!started.get()) {
        on(Lifecycle.STOP, new CompletionHandler() {
            @Override
            protected void complete() {
                if (channelFuture.awaitUninterruptibly(15, TimeUnit.SECONDS)) {
                    channelFuture.getChannel().close();
                }
                started.set(false);
            }
        });
        bootstrap.setOption("child.keepAlive", keepAlive);
        bootstrap.setOption("child.receiveBufferSize", Buffer.SMALL_BUFFER_SIZE);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                final ChannelPipeline pipeline = Channels.pipeline();
                TcpClient.this.configurePipeline(pipeline);
                return pipeline;
            }
        });

        try {
            channelFuture = bootstrap.connect(new InetSocketAddress(InetAddress.getByName(host), port));
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        started.set(true);
                        event(Lifecycle.START);
                    } else {
                        Throwable t = channelFuture.getCause();
                        event(Events.classToEventExpression(t.getClass()), t);
                    }
                }
            });
        } catch (UnknownHostException e) {
            event(Events.classToEventExpression(e.getClass()), e);
        }
    }
    return (T) this;
}

From source file:io.enforcer.deathstar.ws.WebSocketServerHandler.java

License:Apache License

/**
 * Sends http response to clients//from   w ww .jav a2 s.co  m
 *
 * @param ctx handler context
 * @param req http request
 * @param res http response
 */
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.status().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaderUtil.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:io.flood.rpc.network.ConnectorImpl.java

License:Apache License

private ChannelFuture connect0(final SocketAddress address, final int retryTime) {
    id = SocketIdGenerator.nextId();// w ww.  ja  v a  2s  .c  om
    final ChannelFuture future = boot.connect(address);
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(io.netty.util.concurrent.Future<? super Void> completeFuture)
                throws Exception {

            broadcastComplete(future);

            if (completeFuture.isSuccess()) {
                channel = future.channel();
                LOG.info(LogHelper.format(id, "connected to server ({}=>{})"), channel.localAddress(),
                        channel.remoteAddress());
                ConnectionManager.put(id, Connection.Type.Client, channel);

                future.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> completeFuture) throws Exception {
                        LOG.info(
                                LogHelper.format(id,
                                        "connection closed ,after {} millisecond  will be reconnect"),
                                retryTime);
                        if (!isInitiative.get()) {
                            Thread.sleep(retryTime);
                            connect0(address, retryTime);
                        }
                    }
                });

            } else {
                LOG.info(LogHelper.format(id, "connet to server failed({})"), address);
            }
        }
    });
    return future;
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private void openNewChannelRec(List<InetSocketAddress> remoteAddresses, InetSocketAddress localAddress, int i,
        Promise<Channel> channelPromise, Bootstrap bootstrap, HttpListener listener,
        RequestTimeout requestTimeout) {

    if (isClosed()) {
        return;/*  w  w w  .  j a  v a2  s  .  c o m*/
    }

    InetSocketAddress remoteAddress = remoteAddresses.get(i);

    listener.onTcpConnectAttempt(remoteAddress);
    ChannelFuture whenChannel = bootstrap.connect(remoteAddress, localAddress);

    whenChannel.addListener(f -> {
        if (f.isSuccess()) {
            Channel channel = whenChannel.channel();
            listener.onTcpConnectSuccess(remoteAddress, channel);
            channelPromise.setSuccess(channel);

        } else {
            listener.onTcpConnectFailure(remoteAddress, f.cause());

            if (requestTimeout.isDone()) {
                channelPromise.setFailure(IGNORE_REQUEST_TIMEOUT_REACHED_WHILE_TRYING_TO_CONNECT);
                return;
            }

            int nextI = i + 1;
            if (nextI < remoteAddresses.size()) {
                openNewChannelRec(remoteAddresses, localAddress, nextI, channelPromise, bootstrap, listener,
                        requestTimeout);

            } else {
                requestTimeout.cancel();
                listener.onThrowable(f.cause());
                channelPromise.setFailure(f.cause());
            }
        }
    });
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void doStart(int attempt) {
    assert Thread.holdsLock(mux) : "Thread must hold lock.";

    ServerBootstrap boot = new ServerBootstrap();

    if (acceptors instanceof EpollEventLoopGroup) {
        if (DEBUG) {
            log.debug("Using EPOLL server socket channel.");
        }// w  w w  .j av a 2  s  .  c om

        boot.channel(EpollServerSocketChannel.class);
    } else {
        if (DEBUG) {
            log.debug("Using NIO server socket channel.");
        }

        boot.channel(NioServerSocketChannel.class);
    }

    boot.group(acceptors, workers);

    setOpts(boot);
    setChildOpts(boot);

    boot.handler(new ChannelInboundHandlerAdapter() {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            mayBeRetry(ctx.channel(), attempt, cause);
        }
    });

    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            InetSocketAddress remoteAddress = channel.remoteAddress();
            InetSocketAddress localAddress = channel.localAddress();

            synchronized (mux) {
                if (state == STOPPING || state == STOPPED) {
                    if (DEBUG) {
                        log.debug("Closing connection since server is in {} state [address={}].", state,
                                remoteAddress);
                    }

                    channel.close();

                    return;
                }

                // Setup pipeline.
                ChannelPipeline pipe = channel.pipeline();

                // Configure SSL.
                if (ssl != null) {
                    pipe.addLast(ssl.newHandler(channel.alloc()));
                }

                // Message codecs.
                NetworkProtocolCodec codec = new NetworkProtocolCodec(codecs);

                pipe.addLast(new NetworkProtocolVersion.Decoder());
                pipe.addLast(codec.encoder());
                pipe.addLast(codec.decoder());

                // Client handler.
                NettyServerClient client = new NettyServerClient(remoteAddress, localAddress, ssl != null,
                        hbInterval, hbLossThreshold, hbDisabled, handlers, workers);

                pipe.addLast(client);

                // Register client to this server.
                clients.put(channel, client);

                // Unregister client on disconnect.
                channel.closeFuture().addListener(close -> {
                    if (DEBUG) {
                        log.debug("Removing connection from server registry [address={}]", remoteAddress);
                    }

                    synchronized (mux) {
                        clients.remove(channel);
                    }
                });
            }
        }
    });

    ChannelFuture bindFuture = boot.bind(address);

    server = bindFuture.channel();

    bindFuture.addListener((ChannelFutureListener) bind -> {
        if (bind.isSuccess()) {
            synchronized (mux) {
                failoverInProgress = false;

                if (state == STARTING) {
                    state = STARTED;

                    // Updated since port can be automatically assigned by the underlying OS.
                    address = (InetSocketAddress) bind.channel().localAddress();

                    if (DEBUG) {
                        log.debug("Started [address={}]", address);
                    }

                    if (!startFuture.isDone() && callback != null) {
                        callback.onStart(this);
                    }

                    startFuture.complete(this);
                }
            }
        } else {
            mayBeRetry(bind.channel(), attempt, bind.cause());
        }
    });
}

From source file:io.hekate.network.netty.NettyServerClient.java

License:Apache License

@Override
public NetworkFuture<Object> disconnect() {
    NetworkFuture<Object> future = new NetworkFuture<>();

    ChannelHandlerContext localCtx = this.handlerCtx;

    if (localCtx == null) {
        future.complete(this);
    } else {/*from   w w  w .j av  a2 s .  c  om*/
        this.handlerCtx = null;

        ChannelFuture closeFuture = localCtx.close();

        closeFuture.addListener(completed -> future.complete(this));
    }

    return future;
}

From source file:io.hydramq.network.client.AbstractConnection.java

License:Open Source License

@Override
public CompletableFuture<Void> connect(final InetSocketAddress endpoint) {
    Assert.argumentNotNull(endpoint, "endpoint");
    final CompletableFuture<Void> connectFuture = new CompletableFuture<>();

    // Already connected, or a connection is in progress.  Keep the existing endpoint.
    if (isConnected() || connecting.compareAndSet(true, false)) {
        connectFuture.completeExceptionally(
                new HydraRuntimeException("Already connected or connecting to " + this.endpoint));
        return connectFuture;
    }//from  w  w w.j a  v  a 2 s. c om

    this.endpoint = endpoint;

    final ChannelFuture bootstrapConnect = bootstrap().connect(endpoint);
    channel = bootstrapConnect.channel();
    channel.attr(ChannelAttributes.COMMAND_FUTURES).set(new ConcurrentHashMap<>());
    bootstrapConnect.addListener(f -> {
        if (f.isSuccess()) {
            handshake().whenComplete((aVoid, throwable) -> {
                List<ConnectionStateListener> handshakeListeners = new ArrayList<>();
                try {
                    connectionLock.lock();

                    if (throwable != null) {
                        // We connected, but there was a handshake error.
                        channel().disconnect().addListener(closeFuture -> {
                            connecting.set(false);
                            connectFuture.completeExceptionally(
                                    new HydraRuntimeException("Handshaking error", throwable));
                            handshakeListeners.addAll(toNotify());
                        });
                    } else { // We successfully connected, and handshake was also successful.
                        channel().closeFuture().addListener(closeFuture -> { // Register disconnect future.  Disconnect can happen for any reason.
                            List<ConnectionStateListener> closeListeners = new ArrayList<>();
                            try {
                                connectionLock.lock();
                                // Clean up pending futures.
                                for (CompletableFuture<Command> pendingResponse : channel()
                                        .attr(ChannelAttributes.COMMAND_FUTURES).get().values()) {
                                    pendingResponse
                                            .completeExceptionally(new HydraDisconnectException(endpoint));
                                }
                                closeListeners.addAll(toNotify());
                            } finally {
                                connectionLock.unlock();
                            }
                            closeListeners.forEach(
                                    listener -> listener.onStateChanged(this, ConnectionState.DISCONNECTED));
                        });
                        connecting.set(false);
                        connectedCondition.signalAll();

                        logger.info("Connected to {}!", endpoint);
                        connectFuture.complete(null);
                    }
                } finally {
                    connectionLock.unlock();
                }
                handshakeListeners.forEach(disconnectionListener -> disconnectionListener.onStateChanged(this,
                        ConnectionState.DISCONNECTED));
            });
        } else {
            List<ConnectionStateListener> connectFailureListeners = new ArrayList<>();
            try {
                connectionLock.lock();
                connecting.set(false);
                connectFuture.completeExceptionally(new HydraConnectionException(endpoint, f.cause()));
                connectFailureListeners.addAll(toNotify());
            } finally {
                connectionLock.unlock();
            }
            connectFailureListeners
                    .forEach(listener -> listener.onStateChanged(this, ConnectionState.DISCONNECTED));
        }

    });
    return connectFuture;
}