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:com.twitter.http2.HttpConnectionHandler.java

License:Apache License

private void sendGoAwayFrame(ChannelHandlerContext ctx, ChannelPromise promise) {
    ChannelFuture future = sendGoAwayFrame(HttpErrorCode.NO_ERROR);
    if (httpConnection.noActiveStreams()) {
        future.addListener(new ClosingChannelFutureListener(ctx, promise));
    } else {// ww  w  . ja v  a 2s .c om
        closingChannelFutureListener = new ClosingChannelFutureListener(ctx, promise);
    }
}

From source file:com.uber.tchannel.channels.Peer.java

License:Open Source License

public Connection connect(Bootstrap bootstrap, Connection.Direction preferredDirection) {
    Connection conn = getConnection(ConnectionState.IDENTIFIED, preferredDirection);
    if (conn != null && (conn.satisfy(preferredDirection) || preferredDirection == Connection.Direction.IN)) {
        return conn;
    }/*from w w  w .ja  va 2  s . co  m*/

    final ChannelFuture f = bootstrap.connect(remoteAddress);
    Channel channel = f.channel();
    final Connection connection = add(channel, Connection.Direction.OUT);

    // handle connection errors
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                connection.setIndentified(new TChannelConnectionFailure(future.cause()));
            }
        }
    });

    return connection;
}

From source file:com.uber.tchannel.codecs.MessageCodec.java

License:Open Source License

public static ChannelFuture write(ChannelHandlerContext ctx, Frame frame) {
    ChannelFuture f = ctx.writeAndFlush(encode(ctx.alloc(), encode(ctx.alloc(), frame)));
    f.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
    return f;/*from  w w w.  j  av  a2s . com*/
}

From source file:com.ura.proxy.HexDumpProxyInboundHandler.java

License:Apache License

@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable(false);/*from w  ww.j av  a 2  s . co  m*/

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));

    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection attempt succeeded:
                // Begin to accept incoming traffic.
                inboundChannel.setReadable(true);
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}

From source file:com.vmware.admiral.compute.container.HealthChecker.java

License:Open Source License

private void healthCheckTcp(ContainerState containerState, HealthConfig healthConfig, String[] hostPortBindings,
        Consumer<ContainerStats> callback) {
    if (hostPortBindings == null) {
        determineContainerHostPort(containerState, healthConfig,
                (bindings) -> healthCheckTcp(containerState, healthConfig, bindings, callback));
        return;/*from   www .ja  v a 2 s. co m*/
    }

    Integer configPort = Integer.valueOf(hostPortBindings[1]);
    int port = configPort > 0 ? configPort : 80;
    Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress(hostPortBindings[0], port))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, healthConfig.timeoutMillis)
            .handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel arg0) throws Exception {
                    // Nothing to setup
                }
            });

    ChannelFuture channelFuture = bootstrap.connect();
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture result) throws Exception {
            handleHealthResponse(containerState, result.cause(), callback);
            result.channel().close();
        }

    });
}

From source file:com.vmware.dcp.common.http.netty.NettyChannelPool.java

License:Open Source License

public void connectOrReuse(String host, int port, boolean doNotReUse, Operation request) {

    if (request == null) {
        throw new IllegalArgumentException("request is required");
    }//from   w w  w.  ja  v  a 2 s  .  c  o m

    if (host == null) {
        request.fail(new IllegalArgumentException("host is required"));
        return;
    }

    if (port <= 0) {
        port = UriUtils.HTTP_DEFAULT_PORT;
    }

    try {
        String key = toConnectionKey(host, port);
        NettyChannelGroup group = getChannelGroup(key);
        NettyChannelContext context = null;

        synchronized (group) {
            if (!group.availableChannels.isEmpty() && !doNotReUse) {
                context = group.availableChannels.remove(group.availableChannels.size() - 1);
                context.updateLastUseTime();
            } else if (group.inUseChannels.size() >= this.connectionLimit) {
                group.pendingRequests.add(request);
                return;
            } else {
                context = new NettyChannelContext(host, port, key);
            }

            if (context.getChannel() != null) {
                if (!context.getChannel().isOpen()) {
                    context.close();
                    context = new NettyChannelContext(host, port, key);
                }
            }

            group.inUseChannels.add(context);
        }

        NettyChannelContext contextFinal = context;

        if (context.getChannel() != null) {
            context.setOperation(request);
            request.complete();
            return;
        }

        ChannelFuture connectFuture = this.bootStrap.connect(context.host, context.port);
        connectFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {

                if (future.isSuccess()) {
                    Channel ch = future.channel();
                    contextFinal.setChannel(ch).setOperation(request);
                    request.complete();
                } else {
                    returnOrClose(contextFinal, true);
                    fail(request, future.cause());
                }
            }

        });

    } catch (Throwable e) {
        fail(request, e);
    }
}

From source file:com.vmware.dcp.common.http.netty.NettyHttpClientRequestHandler.java

License:Open Source License

private void writeResponse(ChannelHandlerContext ctx, Operation request, FullHttpResponse response) {
    boolean isClose = !request.isKeepAlive() || response == null;
    Object rsp = Unpooled.EMPTY_BUFFER;
    if (response != null) {
        AsciiString v = isClose ? HttpHeaderValues.CLOSE : HttpHeaderValues.KEEP_ALIVE;
        response.headers().set(HttpHeaderNames.CONNECTION, v);
        rsp = response;/*from   w  ww  .jav a  2  s.com*/
    }

    ctx.channel().attr(NettyChannelContext.OPERATION_KEY).remove();

    ChannelFuture future = ctx.writeAndFlush(rsp);
    if (isClose) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.vmware.dcp.common.WebSocketService.java

License:Open Source License

@Override
public void handleRequest(Operation op) {
    prepareRequest(op);//from  ww  w  . j a va2 s .c  o m
    Operation.SerializedOperation serializedOperation = Operation.SerializedOperation.create(op);
    this.pendingOperations.put(op.getId(), op);
    ChannelFuture promise = this.ctx.writeAndFlush(new TextWebSocketFrame(
            "POST " + this.uri.toString() + Operation.CR_LF + Utils.toJson(serializedOperation)));
    promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                op.fail(future.cause());
                WebSocketService.this.pendingOperations.remove(op.getId());
            }
        }
    });
}

From source file:com.vmware.xenon.common.http.netty.NettyChannelPool.java

License:Open Source License

public void connectOrReuse(NettyChannelGroupKey key, Operation request) {

    if (request == null) {
        throw new IllegalArgumentException("request is required");
    }//from w w w . j av a2 s . c o m

    if (key == null) {
        request.fail(new IllegalArgumentException("connection key is required"));
        return;
    }

    try {
        NettyChannelGroup group = getChannelGroup(key);
        final NettyChannelContext context = selectContext(request, group);

        if (context == null) {
            // We have no available connections, request has been queued
            return;
        }

        // If the connection is open, send immediately
        if (context.getChannel() != null) {
            context.setOperation(request);
            request.complete();
            return;
        }

        // Connect, then wait for the connection to complete before either
        // sending data (HTTP/1.1) or negotiating settings (HTTP/2)
        ChannelFuture connectFuture = this.bootStrap.connect(key.host, key.port);
        connectFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {

                if (future.isSuccess()) {
                    Channel channel = future.channel();
                    if (NettyChannelPool.this.isHttp2Only) {
                        // We tell the channel what its channel context is, so we can use it
                        // later to manage the mapping between streams and operations
                        channel.attr(NettyChannelContext.CHANNEL_CONTEXT_KEY).set(context);

                        // We also note that this is an HTTP2 channel--it simplifies some other code
                        channel.attr(NettyChannelContext.HTTP2_KEY).set(true);
                        waitForSettings(channel, context, request, group);
                    } else {
                        context.setOpenInProgress(false);
                        context.setChannel(channel).setOperation(request);
                        sendAfterConnect(channel, context, request, null);
                    }
                } else {
                    returnOrClose(context, true);
                    fail(request, future.cause());
                }
            }

        });

    } catch (Throwable e) {
        fail(request, e);
    }
}

From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java

License:Open Source License

/**
 * Start the discovery process./*from w w  w. ja  v  a2 s .  c  o m*/
 *
 * @throws IOException on failure
 */
public void start() throws IOException {
    searchRequestRunnable = new SearchRequestRunnable(this);

    // set up the inbound channel handler
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new DatagramToByteBufHandler()); // convert an incoming DatagramPacket into a ByteBuf
            pipeline.addLast(new OrderDecoder()); // convert an incoming ByteBuf into an Order
            pipeline.addLast(new InboundOrderHandler(listener)); // handle incoming Orders
        }
    });

    // bind to the address
    ChannelFuture cf = bootstrap.bind(new InetSocketAddress(0));
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = (DatagramChannel) channelFuture.channel();

                // perform initial search request
                group.execute(searchRequestRunnable);

                // schedule two quick follow-up search requests to make sure a camera didn't miss the first request
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS,
                        TimeUnit.SECONDS);
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2,
                        TimeUnit.SECONDS);

                // set up a recurring search request so we can keep track of cameras coming/going
                searchFuture = group.scheduleAtFixedRate(searchRequestRunnable,
                        SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2 + getSearchRequestFrequencySeconds,
                        getSearchRequestFrequencySeconds, TimeUnit.SECONDS);
            } else {
                logger.error("Bind attempt failed", channelFuture.cause());
            }
        }
    });
}