Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:org.glassfish.jersey.netty.httpserver.NettyHttpContainerProvider.java

License:Open Source License

/**
 * Create and start Netty HTTP/2 server.
 * <p>/*from   www  .  j a v  a 2 s .c  om*/
 * The server is capable of connection upgrade to HTTP/2. HTTP/1.x request will be server as they were used to.
 * <p>
 * Note that this implementation cannot be more experimental. Any contributions / feedback is welcomed.
 *
 * @param baseUri       base uri.
 * @param configuration Jersey configuration.
 * @param sslContext    Netty {@link SslContext}.
 * @return Netty channel instance.
 * @throws ProcessingException when there is an issue with creating new container.
 */
public static Channel createHttp2Server(final URI baseUri, final ResourceConfig configuration,
        SslContext sslContext) throws ProcessingException {

    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final NettyHttpContainer container = new NettyHttpContainer(configuration);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new JerseyServerInitializer(baseUri, sslContext, container, true));

        int port = getPort(baseUri);

        Channel ch = b.bind(port).sync().channel();

        ch.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                container.getApplicationHandler().onShutdown(container);

                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });

        return ch;

    } catch (InterruptedException e) {
        throw new ProcessingException(e);
    }
}

From source file:org.glowroot.agent.central.EventLoopGroups.java

License:Apache License

static EventLoopGroup create(String name) {
    final ExecutorService executor = Executors.newSingleThreadExecutor(ThreadFactories.create(name));
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1, executor);
    nioEventLoopGroup.terminationFuture().addListener(new GenericFutureListener<Future<Object>>() {
        @Override//  w w w.  j a va 2  s .com
        public void operationComplete(Future<Object> future) throws Exception {
            executor.shutdown();
            if (!executor.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate executor");
            }
        }
    });
    return nioEventLoopGroup;
}

From source file:org.glowroot.agent.it.harness.impl.EventLoopGroups.java

License:Apache License

static EventLoopGroup create(String name) {
    final ExecutorService executor = Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name).build());
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1, executor);
    nioEventLoopGroup.terminationFuture().addListener(new GenericFutureListener<Future<Object>>() {
        @Override//  w  w w.  j  a va2 s .c om
        public void operationComplete(Future<Object> future) throws Exception {
            executor.shutdown();
            if (!executor.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate executor");
            }
        }
    });
    return nioEventLoopGroup;
}

From source file:org.glowroot.agent.plugin.netty.Http1ServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        @SuppressWarnings("deprecation")
        String uri = request.getUri();
        if (uri.equals("/exception")) {
            throw new Exception("Test");
        }//from w  ww  . j  ava2 s  .c  o m
        if (uri.equals("/chunked")) {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.headers().set("transfer-encoding", "chunked");
            response.headers().set("content-type", "text/plain");
            ctx.write(response);
            final File file = File.createTempFile("glowroot-netty-plugin-it-", ".txt");
            final ChunkedFile chunkedFile = new ChunkedFile(file);
            Files.write(CONTENT, file);
            ctx.write(chunkedFile).addListener(ChannelFutureListener.CLOSE)
                    .addListener(new GenericFutureListener<Future<Void>>() {
                        @Override
                        public void operationComplete(Future<Void> arg0) throws Exception {
                            chunkedFile.close();
                            if (!file.delete()) {
                                throw new IllegalStateException("Could not delete file: " + file.getPath());
                            }
                        }
                    });
            return;
        }
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set("Content-Type", "text/plain");
        response.headers().set("Content-Length", response.content().readableBytes());
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    }
}

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

License:Apache License

static EventLoopGroup create(String name) {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(name + "-%d")
            .build();//from w  ww  .  j a va2  s.  c  om
    final ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);
    NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1, executor);
    nioEventLoopGroup.terminationFuture().addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(Future<Object> future) throws Exception {
            executor.shutdown();
            if (!executor.awaitTermination(10, SECONDS)) {
                throw new IllegalStateException("Could not terminate executor");
            }
        }
    });
    return nioEventLoopGroup;
}

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

License:Apache License

@SuppressWarnings("argument.type.incompatible")
static void addErrorListener(ChannelFuture future) {
    future.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override//from  w w  w  . ja  v a2 s  .  c om
        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.iotivity.cloud.base.CoapClient.java

License:Open Source License

public void startClient(final InetSocketAddress inetSocketAddress) throws InterruptedException {

    try {//  w ww . j a  va2 s.  c  o  m
        Bootstrap b = new Bootstrap();
        b.group(connectorGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.SO_REUSEADDR, true);

        b.handler(initializer);

        channelFuture = b.connect(inetSocketAddress).sync();

        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Logger.d("Connection status of TCP CoAP CLIENT  : " + future.isSuccess());
            }
        });
    } finally {
    }
}

From source file:org.iotivity.cloud.base.CoapServer.java

License:Open Source License

public void startServer(InetSocketAddress inetSocketAddress)
        throws CertificateException, SSLException, InterruptedException {

    try {//from  w w w . j a  v a2s  . com
        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(initializer);

        ChannelFuture channelFuture = b.bind(inetSocketAddress).sync();

        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // TODO Auto-generated method stub
                Logger.d("Connection status of TCP CoAP SERVER  : " + future.isSuccess());
            }
        });
    } finally {
    }
}

From source file:org.iotivity.cloud.base.HttpServer.java

License:Open Source License

public void startServer(InetSocketAddress inetSocketAddress)
        throws CertificateException, SSLException, InterruptedException {

    try {//from   w ww.  j  a va2 s  .  c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(initializer);

        ChannelFuture ch = b.bind(inetSocketAddress).sync();
        ch.addListener(new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("Connection status of TCP Http SERVER  : " + future.isSuccess());
            }

        });
    } finally {
    }

}

From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w w w.  j a  va2 s  . c  o  m
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("StartTlsClientHandler");
    ByteBuf buf = (ByteBuf) msg;
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);

    if ("StartTlsResponse".equals(new String(bytes))) {
        logger.debug("received StartTlsResponse");

        SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove("startTlsClientHandler");
        pipeline.addLast("sslHandler", sslHandler);

        logger.debug("StartTls starting handshake");

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

                    pipeline.addLast("decoder",
                            new DiameterMessageDecoder(
                                    StartTlsClientHandler.this.tlsTransportClient.getParent(),
                                    StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("msgHandler", new DiameterMessageHandler(
                            StartTlsClientHandler.this.tlsTransportClient.getParent(), true));

                    pipeline.addLast("encoder", new DiameterMessageEncoder(
                            StartTlsClientHandler.this.tlsTransportClient.getParser()));
                    pipeline.addLast("inbandWriter", new InbandSecurityHandler());
                }
            }
        });

    }
}