Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

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

Prototype

ChannelFutureListener

Source Link

Usage

From source file:org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput.java

License:Open Source License

public JerseyChunkedInput(Channel ctx) {
    this.ctx = ctx;
    ctx.closeFuture().addListener(new ChannelFutureListener() {
        @Override/* ww  w  .  jav a2  s. c  om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            // forcibly closed connection.
            open = false;
            queue.clear();
            JerseyChunkedInput.this.close();
        }
    });
}

From source file:org.glowroot.central.SyntheticMonitorService.java

License:Apache License

private static ListenableFuture<HttpResponseStatus> runPing(String url) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new IllegalStateException("URI missing scheme");
    }/*from  w  ww . j a  v a  2  s.  c  o m*/
    final boolean ssl = uri.getScheme().equalsIgnoreCase("https");
    final String host = uri.getHost();
    if (host == null) {
        throw new IllegalStateException("URI missing host");
    }
    final int port;
    if (uri.getPort() == -1) {
        port = ssl ? 443 : 80;
    } else {
        port = uri.getPort();
    }
    final EventLoopGroup group = new NioEventLoopGroup();
    final HttpClientHandler httpClientHandler = new HttpClientHandler();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (ssl) {
                SslContext sslContext = SslContextBuilder.forClient().build();
                p.addLast(sslContext.newHandler(ch.alloc(), host, port));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpObjectAggregator(1048576));
            p.addLast(httpClientHandler);
        }
    });
    final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    request.headers().set("Glowroot-Transaction-Type", "Synthetic");
    ChannelFuture future = bootstrap.connect(host, port);
    final SettableFuture<HttpResponseStatus> settableFuture = SettableFuture.create();
    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            Channel ch = future.channel();
            if (future.isSuccess()) {
                ch.writeAndFlush(request);
            }
            ch.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) {
                    if (future.isSuccess()) {
                        HttpResponseStatus responseStatus = httpClientHandler.responseStatus;
                        if (HttpResponseStatus.OK.equals(responseStatus)) {
                            settableFuture.set(responseStatus);
                        } else {
                            settableFuture.setException(
                                    new Exception("Unexpected http response status: " + responseStatus));
                        }
                    } else {
                        settableFuture.setException(future.cause());
                    }
                    group.shutdownGracefully();
                }
            });
        }
    });
    return settableFuture;
}

From source file:org.glowroot.local.ui.HttpServices.java

License:Apache License

@SuppressWarnings("argument.type.incompatible")
static void addErrorListener(ChannelFuture future) {
    future.addListener(new ChannelFutureListener() {
        @Override//from   w ww.  j  a v a  2  s  . co m
        public void operationComplete(ChannelFuture future) throws Exception {
            Throwable cause = future.cause();
            if (cause == null) {
                return;
            }
            if (shouldLogException(cause)) {
                logger.error(cause.getMessage(), cause);
            }
            future.channel().close();
        }
    });
}

From source file:org.graylog2.gelfclient.transport.GelfTcpTransport.java

License:Apache License

@Override
protected void createBootstrap(final EventLoopGroup workerGroup) {
    final Bootstrap bootstrap = new Bootstrap();
    final GelfSenderThread senderThread = new GelfSenderThread(queue);

    bootstrap.group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout())
            .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())
            .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive())
            .remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() {
                @Override//from ww w  . ja  va  2  s . c o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (config.isTlsEnabled()) {
                        LOG.debug("TLS enabled.");
                        final SslContext sslContext;

                        if (!config.isTlsCertVerificationEnabled()) {
                            // If the cert should not be verified just use an insecure trust manager.
                            LOG.debug("TLS certificate verification disabled!");
                            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
                        } else if (config.getTlsTrustCertChainFile() != null) {
                            // If a cert chain file is set, use it.
                            LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile());
                            sslContext = SslContext.newClientContext(config.getTlsTrustCertChainFile());
                        } else {
                            // Otherwise use the JVM default cert chain.
                            sslContext = SslContext.newClientContext();
                        }

                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    }

                    // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then.
                    // The graylog2-server uses '\0'-bytes as delimiter for TCP frames.
                    ch.pipeline().addLast(new GelfMessageJsonEncoder());
                    ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                            // We do not receive data.
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            senderThread.start(ctx.channel());
                        }

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            LOG.info("Channel disconnected!");
                            senderThread.stop();
                            scheduleReconnect(ctx.channel().eventLoop());
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            LOG.error("Exception caught", cause);
                        }
                    });
                }
            });

    if (config.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize());
    }

    bootstrap.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOG.debug("Connected!");
            } else {
                LOG.error("Connection failed: {}", future.cause().getMessage());
                scheduleReconnect(future.channel().eventLoop());
            }
        }
    });
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    @SuppressWarnings("unchecked")
    final List<SingleMetric> in = (List<SingleMetric>) msg;
    LOG.trace("Received some metrics: {}", in);

    fifo.addAll(in);//from w w w . ja va2 s .  c  o  m

    synchronized (connectingMutex) {
        // make sure to only open one connection at a time
        if (isConnecting)
            return;
    }

    if (senderChannel != null) {
        sendToChannel(senderChannel);
        return;
    }

    ChannelFuture cf = connectRestServer(ctx.channel().eventLoop().parent());

    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            synchronized (connectingMutex) {
                isConnecting = false;
            }
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                if (cause instanceof ConnectException) {
                    LOG.warn("Sending failed: " + cause.getLocalizedMessage());
                } else {
                    LOG.warn("Something went wrong: " + cause);
                }
            } else {
                //   the remote is up.
                senderChannel = future.channel();
                sendToChannel(senderChannel);
            }
        }
    });
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandler.java

License:Apache License

private void sendToChannel(final Channel ch) {
    LOG.trace("Sending to channel {}", ch);

    final List<SingleMetric> metricsToSend = fifo.getList();

    String payload = Batcher.metricListToJson(metricsToSend);
    ByteBuf content = Unpooled.copiedBuffer(payload, CharsetUtil.UTF_8);
    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, restPrefix, content);
    HttpHeaders.setContentLength(request, content.readableBytes());
    HttpHeaders.setKeepAlive(request, true);
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=utf-8");
    // We need to send the list of metrics we are sending down the pipeline, so the status watcher
    // can later clean them out of the fifo
    ch.attr(listKey).set(metricsToSend);
    ch.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override/*from   w ww  .j a  va2s .c  o  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // and remove from connection pool if you have one etc...
                ch.close();
                senderChannel = null;
                LOG.error("Sending to the hawkular-metrics server failed: " + future.cause());

            } else {
                sendCounter++;
                if (sendCounter >= restCloseAfterRequests) {
                    SingleMetric perfMetric = new SingleMetric(localHostName + ".ptrans.counter",
                            System.currentTimeMillis(), (double) (numberOfMetrics + metricsToSend.size()));
                    fifo.offer(perfMetric);
                    LOG.trace("Doing a periodic close after {} requests and {} items", restCloseAfterRequests,
                            numberOfMetrics);
                    numberOfMetrics = 0;
                    ch.close();
                    senderChannel = null;
                    sendCounter = 0;
                }
            }
        }
    });
}

From source file:org.helios.octo.client.OctoShared.java

License:Open Source License

public ChannelFuture connect(String host, int port) {
    ChannelFuture cf = bootstrap.connect();
    cf.addListener(new ChannelFutureListener() {
        /**/*from w ww  .  jav a  2 s. com*/
         * {@inheritDoc}
         * @see io.netty.util.concurrent.GenericFutureListener#operationComplete(io.netty.util.concurrent.Future)
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            // TODO Auto-generated method stub

        }
    });
    return cf;
}

From source file:org.helios.octo.server.io.ChannelOutputStream.java

License:Open Source License

/**
 * Acquires an output stream for the passed channel
 * @param isStdOut true for std-out, false for std-err
 * @param channel The channel//from  ww w  .  j  a  va2 s  .  c o m
 * @return a channel output stream
 */
public static ChannelOutputStream getInstance(boolean isStdOut, Channel channel) {
    final Map<Channel, ChannelOutputStream> map = isStdOut ? OUT : ERR;
    ChannelOutputStream cos = map.get(channel);
    if (cos == null) {
        synchronized (map) {
            if (cos == null) {
                cos = new ChannelOutputStream(isStdOut, channel);
                map.put(channel, cos);
                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        map.remove(future.channel());
                    }
                });
            }
        }
    }
    return cos;
}

From source file:org.helios.octo.server.OctoServer.java

License:Open Source License

/**
 * <p>Starts the OctoServer</p>
 * @throws Exception Thrown on any error
 *//*from  w  w w  . java 2s . c  om*/
protected void startService() throws Exception {
    log.info(
            "\n\t===========================================\n\tStarting OctoServer\n\t===========================================");
    InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
    initClassLoader();
    log.info("Starting listener on [" + address + ":" + port + "]");
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    channelGroup = new DefaultChannelGroup(workerGroup.next());
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(address, port)).childHandler(new ChannelHandler() {
                @Override
                public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                    channelGroup.add(ctx.channel());
                }

                @Override
                public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                    /* No Op */
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    log.error("Exception caught in client pipeline", cause);

                }

            }).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    //ch.pipeline().addLast("logging", logging);
                    ch.pipeline().addLast("objectDecoder", new ObjectDecoder(classResolver));
                    //ch.pipeline().addLast("objectEncoder", objectEncoder);

                    ch.pipeline().addLast("logging", logging);

                    ch.pipeline().addLast("out", outAdapter);
                    ch.pipeline().addLast("stringEncoder", new StringEncoder());
                    //ch.pipeline().addLast("err", errAdapter);

                    ch.pipeline().addLast("invHandler", invocationHandler);
                }
            });

    b.bind().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (f.isSuccess()) {
                serverChannel = (NioServerSocketChannel) f.channel();
                closeFuture = serverChannel.closeFuture();
                log.info("Started and listening on " + serverChannel.localAddress());
                if (!SystemStreamRedirector.isInstalledOnCurrentThread()) {
                    SystemStreamRedirector.install();
                }
                log.info(
                        "\n\t===========================================\n\tStarted OctoServer\n\t===========================================");
            }
        }
    });

}

From source file:org.hongxi.whatsmars.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    final int opaque = request.getOpaque();

    try {//from   w  w  w  .  j a v  a 2 s . com
        final ResponseFuture responseFuture = new ResponseFuture(channel, opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                log.warn("send a request command to channel <" + addr + "> failed.");
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}