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.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java

License:Open Source License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) {//from w  ww.  ja  v a  2  s  . co m
    ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess())
                exceptionCaught(ctx, future.cause());
        }
    }));
}

From source file:com.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    ctx.write(msg, promise.addListener(new ChannelFutureListener() {
        @Override/*  w  w  w. j  a v a  2 s .c o  m*/
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess())
                exceptionCaught(ctx, future.cause());
        }
    }));
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void openAsync(final AsyncCompletionHandler<Void> handler) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);//w ww  .  j  a  v a  2  s  .c  om
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS));
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive());

    if (settings.getReceiveBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize());
    }
    if (settings.getSendBufferSize() > 0) {
        bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize());
    }
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(final SocketChannel ch) throws Exception {
            if (sslSettings.isEnabled()) {
                SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(),
                        address.getPort());
                engine.setUseClientMode(true);
                if (!sslSettings.isInvalidHostNameAllowed()) {
                    engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters()));
                }
                ch.pipeline().addFirst("ssl", new SslHandler(engine, false));
            }
            ch.pipeline().addLast("readTimeoutHandler",
                    new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS));
            ch.pipeline().addLast(new InboundBufferHandler());
        }
    });
    final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = channelFuture.channel();
                handler.completed(null);
            } else {
                handler.failed(future.cause());
            }
        }
    });
}

From source file:com.mongodb.connection.netty.NettyStream.java

License:Apache License

@Override
public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) {
    CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (ByteBuf cur : buffers) {
        io.netty.buffer.ByteBuf byteBuf = ((NettyByteBuf) cur).asByteBuf();
        composite.addComponent(byteBuf.retain());
        composite.writerIndex(composite.writerIndex() + byteBuf.writerIndex());
    }//w  ww. j av a  2 s.com

    channel.writeAndFlush(composite).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handler.failed(future.cause());
            } else {
                handler.completed(null);
            }
        }
    });
}

From source file:com.moshi.receptionist.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public void processRequestCommand(final ChannelHandlerContext ctx, final RemotingCommand cmd) {
    final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());
    final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor
            : matched;/*from   w ww .  jav a2  s.c  o  m*/

    if (pair != null) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    RPCHook rpcHook = NettyRemotingAbstract.this.getRPCHook();
                    if (rpcHook != null) {
                        rpcHook.doBeforeRequest(RemotingHelper.parseChannelRemoteAddr(ctx.channel()), cmd);
                    }

                    final RemotingCommand response = pair.getObject1().processRequest(ctx, cmd);
                    if (rpcHook != null) {
                        rpcHook.doAfterResponse(cmd, response);
                    }

                    // Oneway?
                    if (!cmd.isOnewayRPC()) {
                        if (response != null) {
                            response.setOpaque(cmd.getOpaque());
                            response.markResponseType();
                            try {
                                ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        if (!future.isSuccess()) {
                                            plog.error("response to "
                                                    + RemotingHelper.parseChannelRemoteAddr(future.channel())
                                                    + " failed", future.cause());
                                            plog.error(cmd.toString());
                                            plog.error(response.toString());
                                        }
                                    }
                                });
                            } catch (Throwable e) {
                                plog.error("process request over, but response failed", e);
                                plog.error(cmd.toString());
                                plog.error(response.toString());
                            }
                        } else {
                            // ?processRequest?
                        }
                    }
                } catch (Throwable e) {
                    plog.error("process request exception", e);
                    plog.error(cmd.toString());

                    if (!cmd.isOnewayRPC()) {
                        final RemotingCommand response = RemotingCommand.createResponseCommand(
                                RemotingSysResponseCode.SYSTEM_ERROR, //
                                RemotingHelper.exceptionSimpleDesc(e));
                        response.setOpaque(cmd.getOpaque());
                        ctx.writeAndFlush(response);
                    }
                }
            }
        };

        try {
            // ??????
            pair.getObject2().submit(run);
        } catch (RejectedExecutionException e) {
            plog.warn(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) //
                    + ", too many requests and system thread pool busy, RejectedExecutionException " //
                    + pair.getObject2().toString() //
                    + " request code: " + cmd.getCode());
            if (!cmd.isOnewayRPC()) {
                final RemotingCommand response = RemotingCommand.createResponseCommand(
                        RemotingSysResponseCode.SYSTEM_BUSY,
                        "too many requests and system thread pool busy, please try another server");
                response.setOpaque(cmd.getOpaque());
                ctx.writeAndFlush(response);
            }
        }
    } else {
        String error = " request type " + cmd.getCode() + " not supported";
        final RemotingCommand response = RemotingCommand
                .createResponseCommand(RemotingSysResponseCode.REQUEST_CODE_NOT_SUPPORTED, error);
        response.setOpaque(cmd.getOpaque());
        ctx.writeAndFlush(response);
        plog.error(RemotingHelper.parseChannelRemoteAddr(ctx.channel()) + error);
    }
}

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/*w w  w .  j  a v a2 s .  com*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.connection.NettyConnection.java

License:Apache License

@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        lastWriteTime = System.currentTimeMillis();
    } else {//www . j  a  va 2 s  .  c o m
        LOGGER.error("connection send msg error", future.cause());
        Logs.CONN.error("connection send msg error={}, conn={}", future.cause().getMessage(), this);
    }
}

From source file:com.mpush.netty.server.NettyServer.java

License:Apache License

private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work,
        Class<? extends ServerChannel> clazz) {
    /***//from w w  w .  j a v a  2 s .co  m
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channel(clazz);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Logs.Console.error("server start success on:{}", port);
                    if (listener != null)
                        listener.onSuccess(port);
                } else {
                    Logs.Console.error("server start failure on:{}", port, future.cause());
                    if (listener != null)
                        listener.onFailure(future.cause());
                }
            }
        });
        if (f.isSuccess()) {
            serverState.set(State.Started);
            /**
             * socket
             */
            f.channel().closeFuture().sync();
        }

    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    } finally {
        /***
         * 
         */
        stop(null);
    }
}

From source file:com.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

SettableFuture<Boolean> connect() {
    state.set(State.CONNECTING);//from   w  ww . j av  a 2s.c  o  m
    final SettableFuture<Boolean> sf = SettableFuture.create();
    b.connect(ip, port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            connectionComplete(cf);

            if (cf.cause() != null) {
                sf.setException(cf.cause());
            } else {
                sf.set(true);
            }
        }
    });
    return sf;
}

From source file:com.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

private void connectionComplete(ChannelFuture cf) {
    if (cf.cause() != null) {
        eventLoop.getEventLoopGroup().schedule(reconnectJob, reconnectInterval, TimeUnit.MILLISECONDS);
        return;//from ww w  .j a v  a 2 s .com
    }
    gw.increaseActive();
    ch = cf.channel();
    channelConnected = true;
    setState(CONNECTED);
}