Example usage for io.netty.channel ChannelFuture cause

List of usage examples for io.netty.channel ChannelFuture cause

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

From source file:com.zextras.modules.chat.server.xmpp.netty.TransparentProxy.java

License:Open Source License

public Future<Channel> connect() {
    final Promise<Channel> channelFuture = new DefaultProgressivePromise<Channel>(
            ImmediateEventExecutor.INSTANCE);

    if (mServerChannel == null) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(mNettyService.getEventLoopGroup()).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(mAccount.getMailHost(), mPort)).handler(new Initializer());

        ChannelFuture serverChannelFuture = bootstrap.connect();
        serverChannelFuture.addListener(new ChannelFutureListener() {
            @Override/*from   w ww .  j a  va 2s  .c o  m*/
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ChatLog.log.info(
                            "Proxy xmpp requests for " + mAccount.getName() + " to " + mAccount.getMailHost());
                    mServerChannel = future.channel();

                    mServerChannel.write(Unpooled.wrappedBuffer(mStreamInit.getBytes()));
                    mServerChannel.writeAndFlush(Unpooled.wrappedBuffer(mInitialPayload.getBytes()));

                    mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

                    mClientChannel.pipeline().addLast("proxyToServer", new Proxy(mServerChannel));

                    mServerChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mClientChannel.close();
                        }
                    });

                    mClientChannel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            mServerChannel.close();
                        }
                    });

                    future.channel().closeFuture();

                    channelFuture.setSuccess(mServerChannel);
                } else {
                    ChatLog.log.info("Cannot proxy xmpp requests for " + mAccount.getName() + " to "
                            + mAccount.getMailHost() + ": " + Utils.exceptionToString(future.cause()));
                    sendInternalError(mClientChannel);
                    mClientChannel.flush().close();
                    channelFuture.setFailure(future.cause());
                }
            }
        });

        return channelFuture;
    } else {
        mServerChannel.pipeline().addLast("proxyToClient", new Proxy(mClientChannel));

        mServerChannel.writeAndFlush(mInitialPayload.getBytes());

        channelFuture.setSuccess(mServerChannel);
        return channelFuture;
    }
}

From source file:com.zextras.modules.chat.services.LocalXmppService.java

License:Open Source License

@Override
public void run() {
    ChatLog.log.info("Listening on port " + DEFAULT_LOCAL_XMPP_PORT);
    EventLoopGroup acceptorGroup = new NioEventLoopGroup(4);
    EventLoopGroup channelWorkerGroup = new NioEventLoopGroup(8);

    Channel channel;//from w ww  .ja  va 2  s . c  o m
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptorGroup, channelWorkerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                try {
                    SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    ch.pipeline().addFirst("ssl", sslHandler);
                    ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer());
                    ch.pipeline().addLast(null, "XmlTagTokenizer", new XmlTagTokenizer());
                    ch.pipeline().addAfter("XmlTagTokenizer", "StanzaProcessor",
                            new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                    mLocalXmppReceiver.processStanza((String) msg);
                                }
                            });
                } catch (Throwable t) {
                    ChatLog.log.warn("Unable to initializer XMPP connection: " + Utils.exceptionToString(t));
                    ch.close();
                }
            }
        };

        ChannelFuture channelFuture = bootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0).bind(DEFAULT_LOCAL_XMPP_PORT).sync();

        if (!channelFuture.isSuccess()) {
            throw channelFuture.cause();
        }

        channel = channelFuture.channel();
        mInitializationPromise.setSuccess(null);
    } catch (Throwable e) {
        mInitializationPromise.setFailure(e);
        return;
    }

    mLock.lock();
    try {
        while (!mStopRequested) {
            try {
                mWaitStopRequest.await();
            } catch (InterruptedException ignored) {
            }
        }

        channel.close().sync();

        acceptorGroup.shutdownGracefully().sync();
        channelWorkerGroup.shutdownGracefully().sync();
    } catch (InterruptedException ignored) {
    } finally {
        mLock.unlock();
    }
}

From source file:com.zhang.pool.NettyChannelPool.java

License:Apache License

private boolean sendRequestUseNewChannel(final InetSocketAddress route, final HttpRequest request,
        final NettyHttpResponseFuture responseFuture, boolean forceConnect) {
    ChannelFuture future = createChannelFuture(route, forceConnect);
    if (null != future) {
        NettyHttpResponseFutureUtil.attributeResponse(future.channel(), responseFuture);
        NettyHttpResponseFutureUtil.attributeRoute(future.channel(), route);
        future.addListener(new ChannelFutureListener() {

            @Override//from   w  w w . j  a va 2  s  .co m
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {

                    future.channel().closeFuture().addListener(new ChannelFutureListener() {

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

                            logger.log(Level.SEVERE,
                                    future.channel() + " closed, exception: " + future.cause());
                            removeChannel(future.channel(), future.cause());
                        }

                    });
                    future.channel().writeAndFlush(request).addListener(CLOSE_ON_FAILURE);
                } else {
                    logger.log(Level.SEVERE,
                            future.channel() + " connect failed, exception: " + future.cause());

                    NettyHttpResponseFutureUtil.cancel(future.channel(), future.cause());
                    if (!NettyHttpResponseFutureUtil.getForceConnect(future.channel())) {
                        releaseCreatePerRoute(future.channel());
                    }
                }
            }

        });
        return true;
    }
    return false;
}

From source file:com.zhucode.longio.transport.netty.NettyClient.java

License:Open Source License

@Override
public void send(MessageBlock mb) {
    long sid = channel.attr(NettyConnector.sessionKey).get();
    mb.setSessionId(sid);/*  w  ww.j  a  v a 2  s.c  om*/
    ChannelFuture f = this.connector.send(mb);
    f.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isCancelled() || future.cause() != null) {
                throw new Exception("service maybe unavailable");
            }
        }
    });

}

From source file:de.felix_klauke.pegasus.client.network.NettyClient.java

License:Apache License

/**
 *
 * You can send a new Object (would be cool when you choose a
 * {@link de.felix_klauke.pegasus.protocol.Packet}).
 *
 * @param object the object to send through our pipeline
 *///from  ww  w .  ja  v a 2 s . c om
public void send(Object object) {
    System.out.println("Sending a packet");
    ChannelFuture future = getChannel().writeAndFlush(object);
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                future.cause().printStackTrace();
            }
        }
    });
}

From source file:de.felix_klauke.pegasus.server.handler.listener.PacketMessageListener.java

License:Apache License

/**
 * Handle any incoming PacketMessage.//  www  .ja  v  a  2  s.  c o m
 *
 * @param channel the channel the message cam from
 * @param packet  the packet
 */
public void handlePacket(Channel channel, PacketMessage packet) {
    PacketMessage packetMessage = new PacketMessage(packet.getMessage());
    packetMessage.setAuthor(userManager.getUser(channel).getUsername());
    for (User user : userManager.getUsers()) {
        if (user.getChannel().id() == channel.id())
            continue;
        System.out.println("Sending Packet to: " + user.getUsername() + " -> " + packetMessage.getMessage());
        ChannelFuture future = user.getChannel().writeAndFlush(packetMessage);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    future.cause().printStackTrace();
                }
            }
        });
    }
}

From source file:de.felix_klauke.pegasus.server.handler.PacketHandler.java

License:Apache License

/**
 *
 *  The Method everything is about. All incoming data will be handled by this method.
 *  It will check all received data. When the object containing this data is an instance
 *  of {@link de.felix_klauke.pegasus.protocol.Packet}.
 *
 *  This is the Main Handler for Handshakes.
 *
 *  The other packets will be//from   w w w .java 2 s.  c  o m
 *  passed to the method that will handle all incoming packets:
 *  {@link de.felix_klauke.pegasus.server.handler.PacketHandler#handlePacket(Channel, Packet)}
 *
 * @param ctx the context of the channel that received the data
 * @param msg the data the channel received
 * @throws Exception the exception that occurs when receiving data fails
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    logger.info("Handling incoming data.");

    User user = userManager.getUser(ctx.pipeline().channel());
    if (user == null) {
        System.out.println(msg.getClass());
        if (msg instanceof PacketHandshake) {
            PacketHandshake packetHandshake = (PacketHandshake) msg;

            logger.info("Authenticating: " + packetHandshake.getUsername() + " with password "
                    + packetHandshake.getPassword());

            boolean success = userManager.authUser(packetHandshake.getUsername(),
                    packetHandshake.getPassword());

            PacketHandshakeResponse response = new PacketHandshakeResponse();
            response.setResult(success ? HandshakeResult.SUCCESS : HandshakeResult.FAILURE);
            if (success) {
                userManager.createUser(packetHandshake.getUsername(), ctx.channel());
            }
            ChannelFuture future = ctx.channel().writeAndFlush(response);
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (!future.isSuccess()) {
                        future.cause().printStackTrace();
                    }
                }
            });
            return;
        }
        ctx.pipeline().channel().close();
        return;
    }

    if (msg instanceof Packet) {
        handlePacket(ctx.pipeline().channel(), (Packet) msg);
    }
}

From source file:de.saxsys.synchronizefx.netty.base.client.NettyBasicClient.java

License:Open Source License

@Override
public void connect() throws SynchronizeFXException {
    this.eventLoopGroup = new NioEventLoopGroup();
    BasicChannelInitializerClient channelInitializer = createChannelInitializer();
    channelInitializer.setTopologyCallback(callback);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).handler(channelInitializer);

    LOG.info("Connecting to server");
    try {/*from  w  ww .j  a  v a  2 s . co  m*/
        ChannelFuture future = bootstrap.connect(address);
        if (!future.await(TIMEOUT)) {
            disconnect();
            throw new SynchronizeFXException("Timeout while trying to connect to the server.");
        }
        if (!future.isSuccess()) {
            disconnect();
            throw new SynchronizeFXException("Connection to the server failed.", future.cause());
        }
        this.channel = future.channel();
        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(final Future<? super Void> future) throws Exception {
                // stop the event loop
                eventLoopGroup.shutdownGracefully();
            }
        });
    } catch (InterruptedException e) {
        disconnect();
        throw new SynchronizeFXException(e);
    }
}

From source file:divconq.api.HyperSession.java

License:Open Source License

public Channel allocateHttpChannel(final ChannelHandler handler, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w  w  w .j a v a  2 s . c o  m
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    if (HyperSession.this.info.isSecurel()) {
                        SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("decoder", new HttpResponseDecoder());
                    pipeline.addLast("encoder", new HttpRequestEncoder());

                    // TODO maybe
                    //pipeline.addLast("deflater", new HttpContentCompressor());

                    pipeline.addLast("handler", handler);
                }
            });

    or.info("Web 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
        ChannelFuture f = b.connect(this.info.getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }

        if (handler instanceof ClientHandler)
            ((ClientHandler) handler).waitConnect();

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }

    return null;
}

From source file:divconq.api.HyperSession.java

License:Open Source License

public Channel allocateWsChannel(final ChannelHandler handler, OperationResult or) {
    final AtomicReference<Future<Channel>> sslready = new AtomicReference<>();

    Bootstrap b = new Bootstrap();

    b.group(Hub.instance.getEventLoopGroup()).option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
            .channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  www  .  j av a  2s  .  c o  m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    HttpHeaders customHeaders = new DefaultHttpHeaders();
                    customHeaders.add("x-DivConq-Mode", Hub.instance.getResources().getMode());

                    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                            HyperSession.this.info.getUri(), WebSocketVersion.V13, null, false, customHeaders);

                    ChannelPipeline pipeline = ch.pipeline();

                    if (HyperSession.this.info.isSecurel()) {
                        SslHandler sh = new SslHandler(HyperSession.this.sslfac.getClientEngine());
                        sslready.set(sh.handshakeFuture());
                        pipeline.addLast("ssl", sh);
                    }

                    pipeline.addLast("http-codec", new HttpClientCodec());
                    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                    pipeline.addLast("ws-handler", new WebSocketClientProtocolHandler(handshaker));

                    pipeline.addLast("handler", handler);

                    /*
                    pipeline.addLast("handler", new SimpleChannelInboundHandler<Object>() {
                            
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                     System.out.println("read: " + msg);
                    }
                            
                            
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                      super.userEventTriggered(ctx, evt);
                              
                      Logger.debug("ue: " + evt);
                    }
                    });
                    */
                }
            });

    or.info("Web 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
        ChannelFuture f = b.connect(this.info.getAddress()).sync();

        if (!f.isSuccess()) {
            or.error(1, "Web Client unable to successfully connect: " + f.cause());
        }

        // it has appeared that sometimes we "overshoot" the ssl handshake in code - to prevent
        // that lets wait for the handshake to be done for sure
        if (sslready.get() != null) {
            Future<Channel> sf = sslready.get().sync();

            if (!sf.isSuccess()) {
                or.error(1, "Web Client unable to securely connect: " + sf.cause());
            }
        }

        if (handler instanceof ClientHandler)
            ((ClientHandler) handler).waitConnect();

        return f.channel();
    } catch (InterruptedException x) {
        or.error(1, "Web Client interrupted while connecting: " + x);
    } catch (Exception x) {
        or.error(1, "Web Client unable to connect: " + x);
    }

    return null;
}