Example usage for io.netty.channel ChannelFuture isSuccess

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:com.zaradai.distributor.messaging.netty.NettyClient.java

License:Apache License

private void connect(final RetryPolicy retryPolicy) {
    ChannelFuture future = bootstrap.connect(endpoint);
    future.addListener(new ChannelFutureListener() {
        @Override//from w ww .j a  v a  2s . c  om
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final ChannelFuture fut = channelFuture;

            if (channelFuture.isSuccess()) {
                connected();
            } else {
                eventLoopGroups.getClientGroup().submit(new Runnable() {
                    @Override
                    public void run() {
                        if (retryPolicy.retry()) {
                            connect(retryPolicy);
                        } else {
                            failed(fut.cause());
                        }
                    }
                });
            }
        }
    });
}

From source file:com.zaradai.distributor.messaging.netty.NettyServer.java

License:Apache License

private void bindComplete(ChannelFuture channelFuture) {
    if (channelFuture.isSuccess()) {
        LOGGER.info("Listening on {}", channelFuture.channel().localAddress());
        serverChannelGroup.add(channelFuture.channel());
    } else {//from w ww.jav  a 2s .  c o  m
        LOGGER.warn("Unable to listen", channelFuture.cause());
    }
}

From source file:com.zextras.modules.chat.server.EventSenderImpl.java

License:Open Source License

public void tryDelivery(String stanza) throws Throwable {
    Channel channel = getChannel();
    ChannelFuture channelFuture = channel
            .writeAndFlush(Unpooled.wrappedBuffer(stanza.getBytes(Charset.defaultCharset()))).sync();
    if (!channelFuture.isSuccess()) {
        throw channelFuture.cause();
    }/*w w w  .  java  2 s  .  co m*/
}

From source file:com.zextras.modules.chat.server.EventSenderImpl.java

License:Open Source License

@Override
public void stop() throws InterruptedException {
    if (mChannel != null && mChannel.isOpen()) {
        ChannelFuture future = mChannel.close().sync();
        if (!future.isSuccess()) {
            throw new RuntimeException(future.cause());
        }/*  w  w  w .j  a  v a 2  s .  com*/
    }
    if (mThread == null) {
        throw new RuntimeException("Invalid Thread state");
    }
    mRequestStop = true;
    mThread.interrupt();
    mThread = null;
}

From source file:com.zextras.modules.chat.server.LocalXmppConnectionProviderImpl.java

License:Open Source License

@Override
public Channel openConnection(String host, int port, final ChannelHandler channelHandler) throws IOException {
    ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
        @Override/*from  w w w .ja v  a2 s . c  o  m*/
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine();
            sslEngine.setUseClientMode(true);
            SslHandler sslHandler = new SslHandler(sslEngine);
            socketChannel.pipeline().addFirst("ssl", sslHandler);
            socketChannel.pipeline().addLast("handler", channelHandler);
        }
    };
    ChannelFuture channelFuture = new Bootstrap().channel(NioSocketChannel.class).group(new NioEventLoopGroup())
            .handler(handler).connect(host, port);

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

        return channelFuture.channel();
    } catch (Throwable t) {
        throw new IOException(t);
    }
}

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

License:Open Source License

@Override
public void onEventQueued(EventQueue eventQueue) {
    try {//from w ww .  jav  a  2 s.com
        final ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        for (Event event : eventQueue.popAllEvents()) {
            LogContext logContext = CurrentLogContext.begin();
            if (event.getTarget().getAddresses().size() == 1) {
                logContext.setAccountName(event.getTarget().toSingleAddress());
            }
            logContext.freeze();
            try {
                out.reset();
                XmppEncoder encoder = (XmppEncoder) event.interpret(mEncoderFactory);
                if (encoder == null) {
                    ChatLog.log.debug("No encoder found for event " + event.getClass().getName());
                    continue;
                }

                final SpecificAddress exposedAddress = mXmppConnectionHandler.getSession().getExposedAddress();

                encoder.encode(out, exposedAddress);

                String stanzaDebug = new String(out.toByteArray(), "UTF-8");
                ChatLog.log.debug("writing: " + event.getClass().getName());
                ChatLog.log.debug("writing stanza(" + stanzaDebug.length() + "): " + stanzaDebug);
                ByteBuf stanza = Unpooled.copiedBuffer(out.toByteArray());
                ChannelFuture writeFuture = mXmppConnectionHandler.write(stanza);

                final Event eventToNotify = event;

                writeFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            EventInterceptor interceptor = eventToNotify
                                    .interpret(mXmppEventInterceptorFactory);
                            interceptor.intercept(mEventManager, exposedAddress);
                        }
                    }
                });
            } finally {
                CurrentLogContext.end();
            }
        }
    } catch (Throwable ex) {
        ChatLog.log.warn("Exception: " + Utils.exceptionToString(ex));
    }
}

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 w  w.  j  a  va2s. 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 w w. j  a v a 2s  . 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/* w  w w  .j  a v  a2  s  .  c o  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.ConnectionListener.java

License:Open Source License

@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
    if (!channelFuture.isSuccess()) {
        final EventLoop loop = channelFuture.channel().eventLoop();
        loop.schedule(new Runnable() {
            @Override/*  www. j  av a2 s  .  c o  m*/
            public void run() {
                client.connect();
            }
        }, 1L, TimeUnit.SECONDS);
    } else {
        client.setConnected(true);
    }

}