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:divconq.bus.Bus.java

License:Open Source License

public void connect() {
    // never try to connect until init has run
    if (Hub.instance.isStopping())
        return;//ww  w  .  j av  a  2 s .  c  om

    // if connect method is already running then skip - it will try again later 
    if (!this.connectLock.tryLock())
        return;

    try {
        // ==========================================================================
        //   Add client connections when not enough
        // ==========================================================================

        for (final SocketInfo info : this.connectors.values()) {
            HubRouter router = this.allocateOrGetHub(info.getHubId(), info.isGateway());

            if (router.isLocal())
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            int conncount = router.getCountSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                pipeline.addLast("http-codec", new HttpClientCodec());
                                pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); // TODO is this too small?

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("ws-handler", new ClientHandler(info));
                            }
                        });

                Logger.debug("dcBus Client connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want channel init (above) to complete before we try connect again
                    b.connect(info.getAddress()).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client unable to connect: " + x);
                }
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            conncount = router.getCountStreamSessions(info);

            // add a coonection only once per call to connect (should be between 2 - 15 seconds between calls)
            if (conncount < info.getStreamCount()) {
                Bootstrap b = new Bootstrap();

                b.group(this.getEventLoopGroup()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 250)
                        .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();

                                if (info.isUseSsl())
                                    pipeline.addLast("ssl",
                                            new SslHandler(SslContextFactory.getClientEngine()));

                                // TODO consider compression

                                pipeline.addLast("decoder", new StreamDecoder());
                                pipeline.addLast("encoder", new StreamEncoder());

                                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                                pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                                pipeline.addLast("handler", new StreamHandler(info, false));
                            }
                        });

                Logger.debug("dcBus Client stream connecting");

                try {
                    // must wait here to make sure we don't release connectLock too soon
                    // we want chanel init (above) to complete before we try connect again
                    b.connect(info.getStreamAddress()).addListener(new GenericFutureListener<ChannelFuture>() {
                        @Override
                        public void operationComplete(ChannelFuture cf) throws Exception {
                            if (!cf.isSuccess()) {
                                Logger.debug("dcBus Stream unable to connect: " + cf.cause());
                                return;
                            }

                            // client starts the HELLO thing once connected!
                            StreamMessage icmd = Hub.instance.getBus().getLocalHub()
                                    .buildStreamHello(info.getHubId());
                            cf.channel().writeAndFlush(icmd);
                        }
                    }).sync();
                } catch (InterruptedException x) {
                    Logger.warn("dcBus Client stream interrupted while connecting: " + x);
                } catch (Exception x) {
                    Logger.debug("dcBus Client stream unable to connect: " + x);
                }
            }
        }

        // ==========================================================================
        //   Add server binding when missing
        // ==========================================================================

        for (final SocketInfo info : this.listeners) {
            // only if not currently bound
            if (this.activelisteners.containsKey(info))
                continue;

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            pipeline.addLast("codec-http", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new ServerHandler(info));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Message Server listening - now listening for dcMessages on TCP port "
                            + info.getPort());
                    this.activelisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Server unable to bind: " + x);
            }

            // -------------------------------------------------
            // stream port
            // -------------------------------------------------
            b = new ServerBootstrap();

            b.group(this.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (info.isUseSsl())
                                pipeline.addLast("ssl", new SslHandler(SslContextFactory.getServerEngine()));

                            // TODO consider compression

                            pipeline.addLast("decoder", new StreamDecoder());
                            pipeline.addLast("encoder", new StreamEncoder());

                            pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(60)); // TODO config
                            pipeline.addLast("writeTimeoutHandler", new WriteTimeoutHandler(30)); // TODO config

                            pipeline.addLast("handler", new StreamHandler(info, true));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(info.getStreamAddress()).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("dcBus Stream Server listening - now listening for dcStreams on TCP port "
                            + info.getPort());
                    this.activestreamlisteners.put(info, bfuture.channel());
                } else
                    Logger.error("dcBus Stream Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.warn("dcBus Stream Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("dcBus Stream Server unable to bind: " + x);
            }
        }

        // ==========================================================================
        //   Remove server binding as needed
        // ==========================================================================

        for (final SocketInfo info : this.activelisteners.keySet()) {
            // all is well if in the listeners list
            if (this.listeners.contains(info))
                continue;

            // otherwise we don't want to bind anymore
            this.stopSocketListener(info);
        }
    } finally {
        this.connectLock.unlock();
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private Future<Channel> handshake() {
    final ScheduledFuture<?> timeoutFuture;
    if (handshakeTimeoutMillis > 0) {
        timeoutFuture = ctx.executor().schedule(new Runnable() {
            @Override/*  w  ww.  j a v a 2s .  c  om*/
            public void run() {
                if (handshakePromise.isDone()) {
                    return;
                }
                notifyHandshakeFailure(HANDSHAKE_TIMED_OUT);
            }
        }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
    } else {
        timeoutFuture = null;
    }

    handshakePromise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(Future<Channel> f) throws Exception {
            if (timeoutFuture != null) {
                timeoutFuture.cancel(false);
            }
        }
    });
    try {
        engine.beginHandshake();
        wrapNonAppData(ctx, false);
        ctx.flush();
    } catch (Exception e) {
        notifyHandshakeFailure(e);
    }
    return handshakePromise;
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    if (!startTls && engine.getUseClientMode()) {
        // issue and handshake and add a listener to it which will fire an exception event if
        // an exception was thrown while doing the handshake
        handshake().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override/*from  w  w w.  j  a  v a2 s  . c  o  m*/
            public void operationComplete(Future<Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    logger.debug("Failed to complete handshake", future.cause());
                    ctx.close();
                }
            }
        });
    }
    ctx.fireChannelActive();
}

From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandler.java

License:Apache License

private void cleanupPipeline0(final int idleTimeout, final ChannelHandler connection, final Channel channel,
        final ChannelPromise channelPromise, final boolean isTcp) {
    final ChannelPipeline pipeline = channel.pipeline();

    // have to explicitly remove handlers based on the input type. Cannot use this.getClass()....
    boolean isClient = registrationWrapper.isClient();
    if (isClient) {
        if (isTcp) {
            pipeline.remove(RegistrationRemoteHandlerClientTCP.class);
        } else {/*from   w  ww  .ja  v a 2s  . c  o  m*/
            pipeline.remove(RegistrationRemoteHandlerClientUDP.class);
        }
    } else {
        if (isTcp) {
            pipeline.remove(RegistrationRemoteHandlerServerTCP.class);
        } else {
            pipeline.remove(RegistrationRemoteHandlerServerUDP.class);
        }
    }

    pipeline.remove(ConnectionRegistrationImpl.class);

    if (idleTimeout > 0) {
        pipeline.replace(IDLE_HANDLER, IDLE_HANDLER_FULL,
                new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS));
    } else {
        pipeline.remove(IDLE_HANDLER);
    }

    pipeline.addLast(CONNECTION_HANDLER, connection);

    // we also DEREGISTER from the HANDSHAKE event-loop and run on the worker event-loop!
    ChannelFuture future = channel.deregister();
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(final Future<? super Void> f) throws Exception {
            if (f.isSuccess()) {
                // TCP and UDP register on DIFFERENT event loops. The channel promise ONLY runs on 1 of them...
                if (channelPromise.channel() == channel) {
                    workerEventLoop.register(channelPromise);
                } else {
                    workerEventLoop.register(channel);
                }
            }
        }
    });
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

/**
 * Main functions//www  .jav a  2 s .c o  m
 */

private void tractReadGet(ChannelHandlerContext ctx, String zipPath) {
    // Parse params
    String path = DPFManagerProperties.getReportsDir() + zipPath;
    if (!zipPath.endsWith(".zip")) {
        String hash = zipPath.substring(1, zipPath.length());
        StatusMessage sm = (StatusMessage) context.sendAndWaitResponse(BasicConfig.MODULE_DATABASE,
                new PostMessage(PostMessage.Type.ASK, hash));
        path = sm.getFolder().substring(0, sm.getFolder().length() - 1) + ".zip";
    }

    // Send the zip report
    File file = new File(path);
    if (file.exists()) {
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");

            long fileLength = raf.length();

            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            HttpUtil.setContentLength(response, fileLength);
            setContentTypeHeader(response, file);
            setDateAndCacheHeaders(response, file);
            response.headers().remove(HttpHeaderNames.CONNECTION);

            // Write the initial line and the header.
            ctx.write(response);

            // Write the content.
            ChannelFuture lastContentFuture;
            if (ctx.pipeline().get(SslHandler.class) == null) {
                ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
                // Write the end marker.
                lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            } else {
                lastContentFuture = ctx.writeAndFlush(
                        new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                        ctx.newProgressivePromise());
            }

            // Delete the zip after download?
            lastContentFuture.addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    //            file.delete();
                }
            });
            // Decide whether to close the connection or not.
            if (!HttpUtil.isKeepAlive(request)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (Exception ignore) {
            sendError(ctx, NOT_FOUND);
        }
    } else {
        // No exists
        sendError(ctx, NOT_FOUND);
    }
}

From source file:freddo.dtalk2.client.netty.NettyClient.java

License:Apache License

public NettyClient(String name, URI uri) {
    mName = name;/*from   w w  w.  j a  v a2 s . c  o  m*/

    // connect...
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        String protocol = uri.getScheme();
        if (!"ws".equals(protocol)) {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        HttpHeaders customHeaders = new DefaultHttpHeaders();
        // customHeaders.add("MyHeader", "MyValue");

        // Connect with V13 (RFC 6455 aka HyBi-17).
        final NettyClientHandler handler = new NettyClientHandler(this, WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders));

        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("http-codec", new HttpClientCodec());
                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                pipeline.addLast("ws-handler", handler);
            }
        });

        LOG.debug("WebSocket Client connecting...");
        mChannel = b.connect(uri.getHost(), uri.getPort())
                .addListener(new GenericFutureListener<ChannelFuture>() {
                    @Override
                    public void operationComplete(ChannelFuture f) throws Exception {
                        if (!f.isSuccess()) {
                            LOG.debug("Connection error", f.cause());
                        }
                    }
                }).sync().channel();

        LOG.debug("Handshake...");
        handler.handshakeFuture().sync();
    } catch (Exception e) {
        LOG.debug("Error: {}", e.getMessage());
        // e.printStackTrace();

        group.shutdownGracefully();
        group = null;
    }
}

From source file:herddb.network.netty.NettyChannel.java

License:Apache License

@Override
public void sendOneWayMessage(ByteBuf message, SendResultCallback callback) {

    io.netty.channel.Channel _socket = this.socket;
    if (_socket == null || !_socket.isOpen()) {
        callback.messageSent(new Exception(this + " connection is closed"));
        return;/*w w w  . ja va2 s.c o  m*/
    }
    if (LOGGER.isLoggable(Level.FINEST)) {
        StringBuilder dumper = new StringBuilder();
        ByteBufUtil.appendPrettyHexDump(dumper, message);
        LOGGER.log(Level.FINEST, "Sending to {}: {}", new Object[] { _socket, dumper });
    }
    _socket.writeAndFlush(message).addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                callback.messageSent(null);
            } else {
                LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause());
                callback.messageSent(future.cause());
                close();
            }
        }
    });
    unflushedWrites.incrementAndGet();
}

From source file:in.voidma.lemming.network.InternalLoginHandler.java

License:Open Source License

@Override
public void handleEncryptionRequest(SPacketEncryptionRequest packet) {

    final SecretKey secretkey = CryptManager.createNewSharedKey();
    PublicKey publickey = packet.getPublicKey();
    String serverID = packet.getServerId();

    Packet response = new CPacketEncryptionResponse(secretkey, publickey, packet.getVerifyToken());
    networkManager.sendPacket(response, new GenericFutureListener<Future<? super Void>>() {
        @Override// ww w .  j  a  va 2  s  . c o m
        public void operationComplete(Future<? super Void> future) throws Exception {
            InternalLoginHandler.this.networkManager.enableEncryption(secretkey);
        }
    });
}

From source file:io.advantageous.conekt.impl.ConektImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private void deleteCacheDirAndShutdown(Handler<AsyncResult<Void>> completionHandler) {
    fileResolver.close(res -> {/*from  w  w w.ja  va 2s.  c  o  m*/

        workerPool.shutdownNow();
        internalBlockingPool.shutdownNow();

        acceptorEventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS)
                .addListener(new GenericFutureListener() {
                    @Override
                    public void operationComplete(io.netty.util.concurrent.Future future) throws Exception {
                        if (!future.isSuccess()) {
                            log.warn("Failure in shutting down acceptor event loop group", future.cause());
                        }
                        eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS)
                                .addListener(new GenericFutureListener() {
                                    @Override
                                    public void operationComplete(io.netty.util.concurrent.Future future)
                                            throws Exception {
                                        if (!future.isSuccess()) {
                                            log.warn("Failure in shutting down event loop group",
                                                    future.cause());
                                        }
                                        if (metrics != null) {
                                            metrics.close();
                                        }

                                        checker.close();

                                        if (completionHandler != null) {
                                            eventLoopThreadFactory.newThread(() -> {
                                                completionHandler.handle(
                                                        io.advantageous.conekt.Future.succeededFuture());
                                            }).start();
                                        }
                                    }
                                });
                    }
                });
    });
}

From source file:io.advantageous.conekt.net.impl.ConektEventLoopGroup.java

License:Open Source License

@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
    if (gracefulShutdown.compareAndSet(false, true)) {
        final AtomicInteger counter = new AtomicInteger(workers.size());
        for (EventLoopHolder holder : workers) {
            // We don't use a lambda here just to keep IntelliJ happy as it (incorrectly) flags a syntax error
            // here
            holder.worker.shutdownGracefully().addListener(new GenericFutureListener() {
                @Override/*from   w w  w .  j  av  a2  s  .c  o m*/
                public void operationComplete(Future future) throws Exception {
                    if (counter.decrementAndGet() == 0) {
                        terminationFuture.setSuccess(null);
                    }
                }
            });
        }
    }
    return terminationFuture;
}