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.jdiameter.client.impl.transport.tls.netty.StartTlsInitiator.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*  w  ww.ja  v a 2  s.  c  om*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof IMessage) {
        IMessage m = (IMessage) msg;
        logger.debug("StartTlsInitiator");
        if (m.getCommandCode() == IMessage.CAPABILITIES_EXCHANGE_ANSWER
                && this.tlsTransportClient.getTlsHandshakingState() == TlsHandshakingState.INIT) {
            AvpSet set = m.getAvps();
            Avp inbandAvp = set.getAvp(Avp.INBAND_SECURITY_ID);
            if (inbandAvp != null && inbandAvp.getUnsigned32() == 1) {
                this.tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKING);

                final ChannelPipeline pipeline = ctx.pipeline();
                pipeline.remove("decoder");
                pipeline.remove("msgHandler");
                pipeline.remove(this);
                pipeline.remove("encoder");
                pipeline.remove("inbandWriter");

                pipeline.addLast("startTlsClientHandler", new StartTlsClientHandler(this.tlsTransportClient));

                logger.debug("Sending StartTlsRequest");
                ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsRequest".getBytes()))
                        .addListener(new GenericFutureListener() {

                            @Override
                            public void operationComplete(Future f) throws Exception {
                                if (!f.isSuccess()) {
                                    logger.error(f.cause().getMessage(), f.cause());
                                }
                            }
                        });

            }
        }
    }

    ReferenceCountUtil.release(msg);
}

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

License:Open Source License

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

    if ("StartTlsRequest".equals(new String(bytes))) {
        logger.debug("Received StartTlsRequest");
        SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
        SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine, false);

        final ChannelPipeline pipeline = ctx.pipeline();

        pipeline.remove("decoder");
        pipeline.remove("msgHandler");
        pipeline.remove("encoder");
        pipeline.remove("inbandWriter");
        pipeline.remove(this);

        pipeline.addLast("sslHandler", sslHandler);

        sslHandler.handshakeFuture().addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    logger.debug("StartTls server handshake succesfull");

                    tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);

                    logger.debug("restoring all handlers");

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

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

                }
            }
        });

        ReferenceCountUtil.release(msg);
        logger.debug("Sending StartTlsResponse");
        ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes()))
                .addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(Future f) throws Exception {
                        if (!f.isSuccess()) {
                            logger.error(f.cause().getMessage(), f.cause());
                        }

                    }
                });
    } else {
        ctx.fireChannelRead(msg);
    }

}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.DefaultHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final AbstractCommand msg) throws Exception {
    Callable<AbstractCommand> callable = msg;

    final Future<AbstractCommand> future = executor.submit(callable);

    future.addListener(new GenericFutureListener<Future<Object>>() {
        @Override/*from   w w  w . j  av a2 s.c om*/
        public void operationComplete(final Future<Object> future) throws Exception {
            LOG.trace("DefaultHandler().operationComplete...");
            if (future.isSuccess()) {
                ctx.writeAndFlush(future.get());
            } else {
                ctx.fireExceptionCaught(future.cause());
            }
        }
    });
}

From source file:org.kaaproject.kaa.server.transports.tcp.transport.TcpHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, AbstractKaaTcpCommandProcessor msg) throws Exception {
    MqttFrame frame = msg.getRequest();/*  w  w w. java 2s  .  c  o m*/
    LOG.trace("[{}] Processing {}", uuid, frame);
    if (frame.getMessageType() == MessageType.CONNECT) {
        ChannelFuture closeFuture = ctx.channel().closeFuture();
        closeFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!sessionDisconnected) {
                    if (session != null) {
                        handler.process(new NettyTcpDisconnectMessage(session));
                        LOG.trace("[{}] Channel is closed - sending disconnect", uuid);
                    } else {
                        LOG.trace("[{}] Session is not yet established. Skip sending disconnect", uuid);
                    }
                    sessionDisconnected = true;
                } else {
                    LOG.trace("[{}] Channel is closed and disconnect is already sent", uuid);
                }
            }
        });

        if (session == null) {
            handler.process(new NettyTcpConnectMessage(uuid, new NettyChannelContext(ctx), (Connect) frame,
                    ChannelType.ASYNC, this, connectResponseConverter, connectErrorConverter));
        } else {
            LOG.info("[{}] Ignoring duplicate {} message ", uuid, MessageType.CONNECT);
        }
    } else {
        if (session != null) {
            switch (frame.getMessageType()) {
            case KAASYNC:
                if (((KaaSync) frame).getKaaSyncMessageType() == KaaSyncMessageType.SYNC) {
                    handler.process(new NettyTcpSyncMessage((SyncRequest) frame, session, syncResponseConverter,
                            syncErrorConverter));
                }
                break;
            case PINGREQ:
                handler.process(new NettyTcpPingMessage(session));
                break;
            case DISCONNECT:
                sessionDisconnected = true;
                handler.process(new NettyTcpDisconnectMessage(session));
                break;
            default:
                break;
            }
        } else {
            LOG.info("[{}] Ignoring {} message due to incomplete CONNECT sequence", uuid,
                    frame.getMessageType());
            ctx.writeAndFlush(new ConnAck(ReturnCode.REFUSE_BAD_PROTOCOL));
        }
    }
}

From source file:org.kobeyoung81.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override/*from   www  .ja  v  a2 s . c  om*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                ctx.pipeline().remove(SocksServerConnectHandler.this);
                                outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                                ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                            }
                        });
                //System.out.println(request.toString());
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new DirectClientHandler(promise));
    //System.out.println(request.host() +":"+ request.port());
    //SocksCmdRequest re = new SocksCmdRequest(request.cmdType(), request.addressType(), "192.168.87.103", 8080);
    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}

From source file:org.nepu.chat.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {//

    //       System.out.println("channelactive!");

    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ///*from  w ww.  ja  v a  2s  . com*/
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}

From source file:org.onesec.raven.rtp.RtpInboundHandlerTest.java

License:Apache License

@Test
public void test() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(4);
    Bootstrap serverBootstrap = createServerBootstrap(group);
    Bootstrap clientBootstrap = createClientBootstrap(group);

    ChannelFuture future = serverBootstrap.bind(Inet4Address.getLocalHost(), BIND_PORT);
    future.await();// ww w . j  a v  a  2 s  .c o m
    serverChannel = future.channel();
    RtpInboundHandler handler = serverChannel.pipeline().get(RtpInboundHandler.class);
    assertNotNull(handler);
    handler.getInStream().setTransferHandler(new Handler());

    //        ChannelFuture clientFuture = clientBootstrap.connect(Inet4Address.getLocalHost(), BIND_PORT);
    ChannelFuture clientFuture = clientBootstrap.bind(Inet4Address.getLocalHost(), BIND_PORT + 1);
    clientChannel = clientFuture.await().channel();
    assertNotNull(clientChannel);
    InetSocketAddress addr = new InetSocketAddress(localhost, BIND_PORT);
    ByteBuf writeBuf = clientChannel.alloc().buffer(5).writeBytes(TEST_BUFFER);
    clientChannel.writeAndFlush(new DatagramPacket(writeBuf, addr)).addListener(new GenericFutureListener() {
        public void operationComplete(Future future) throws Exception {
            clientChannel.close();
        }
    });

    serverChannel.closeFuture().await();
    assertNotNull(receivedBuffer.get());
    assertArrayEquals(TEST_BUFFER, receivedBuffer.get());

}

From source file:org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator.java

License:Open Source License

@Override
protected final void startNegotiation() {
    final Optional<SslHandler> sslHandler = getSslHandler(channel);
    if (sslHandler.isPresent()) {
        Future<Channel> future = sslHandler.get().handshakeFuture();
        future.addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override/*  w  w  w . j a v  a  2  s  .com*/
            public void operationComplete(final Future<? super Channel> future) {
                Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
                LOG.debug("Ssl handshake complete");
                start();
            }
        });
    } else {
        start();
    }
}

From source file:org.opendaylight.controller.netconf.nettyutil.AbstractNetconfSessionNegotiator.java

License:Open Source License

private void start() {
    final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
    LOG.debug("Session negotiation started with hello message {} on channel {}", helloMessage, channel);

    channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());

    // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
    sendMessage((NetconfHelloMessage) helloMessage);

    replaceHelloMessageOutboundHandler();
    changeState(State.OPEN_WAIT);

    timeout = this.timer.newTimeout(new TimerTask() {
        @Override//  ww  w. j av a2  s  .c om
        public void run(final Timeout timeout) {
            synchronized (this) {
                if (state != State.ESTABLISHED) {

                    LOG.debug("Connection timeout after {}, session is in state {}", timeout, state);

                    // Do not fail negotiation if promise is done or canceled
                    // It would result in setting result of the promise second time and that throws exception
                    if (isPromiseFinished() == false) {
                        negotiationFailed(
                                new IllegalStateException("Session was not established after " + timeout));
                        changeState(State.FAILED);

                        channel.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                if (future.isSuccess()) {
                                    LOG.debug("Channel {} closed: success", future.channel());
                                } else {
                                    LOG.warn("Channel {} closed: fail", future.channel());
                                }
                            }
                        });
                    }
                } else if (channel.isOpen()) {
                    channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                }
            }
        }

        private boolean isPromiseFinished() {
            return promise.isDone() || promise.isCancelled();
        }

    }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
}

From source file:org.opendaylight.controller.netconf.ssh.RemoteNetconfCommand.java

License:Open Source License

@Override
public void start(final Environment env) throws IOException {
    LOG.trace("Establishing internal connection to netconf server for client: {}", getClientAddress());

    final Bootstrap clientBootstrap = new Bootstrap();
    clientBootstrap.group(clientEventGroup).channel(LocalChannel.class);

    clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
        @Override//from w  w  w.jav  a 2 s .c  om
        public void initChannel(final LocalChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
        }
    });
    clientChannelFuture = clientBootstrap.connect(localAddress);
    clientChannelFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                clientChannel = clientChannelFuture.channel();
            } else {
                LOG.warn("Unable to establish internal connection to netconf server for client: {}",
                        getClientAddress());
                Preconditions.checkNotNull(callback, "Exit callback must be set");
                callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
                        + getClientAddress());
            }
        }
    });
}