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:net.hasor.rsf.remoting.transport.customer.RsfRequestManager.java

License:Apache License

/**???*/
private void sendRequest(RsfFuture rsfFuture) {
    //???/*from   w  w  w  .j a  v  a 2  s .  com*/
    RsfSettings rsfSettings = this.getRsfContext().getSettings();
    if (this.requestCount.get() >= rsfSettings.getMaximumRequest()) {
        SendLimitPolicy sendPolicy = rsfSettings.getSendLimitPolicy();
        String errorMessage = "maximum number of requests, apply SendPolicy = " + sendPolicy.name();
        LoggerHelper.logWarn(errorMessage);
        if (sendPolicy == SendLimitPolicy.Reject) {
            throw new RsfException(ProtocolStatus.ClientError, errorMessage);
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    //RsfFilter
    final RsfRequestImpl request = (RsfRequestImpl) rsfFuture.getRequest();
    final RequestMsg rsfMessage = request.getMsg();
    //??
    final AbstractRsfClient rsfClient = this.getClientManager().getClient(request.getBindInfo());
    final long beginTime = System.currentTimeMillis();
    final long timeout = rsfMessage.getClientTimeout();
    //
    if (rsfClient == null) {
        rsfFuture.failed(new IllegalStateException("The lack of effective service provider."));
        return;
    }
    if (rsfClient.isActive() == false) {
        rsfFuture.failed(new IllegalStateException("client is closed."));
        return;
    }
    this.startRequest(
            rsfFuture);/* timeout ???request*/
    //
    ChannelFuture future = rsfClient.getChannel().writeAndFlush(rsfMessage);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                return;
            }
            String errorMsg = null;
            //
            if (System.currentTimeMillis() - beginTime >= timeout) {
                errorMsg = "send request too long time(" + (System.currentTimeMillis() - beginTime)
                        + "),requestID:" + rsfMessage.getRequestID();
            }
            //?
            if (future.isCancelled()) {
                errorMsg = "send request to cancelled by user,requestID:" + rsfMessage.getRequestID();
            }
            //
            if (!future.isSuccess()) {
                if (rsfClient.isActive()) {
                    // maybe some exception, so close the channel
                    getClientManager().unRegistered(rsfClient.getHostAddress());
                }
                errorMsg = "send request error " + future.cause();
            }
            LoggerHelper.logSevere(RsfRequestManager.this + ":" + errorMsg);
            //Response
            putResponse(request.getRequestID(), new RsfException(ProtocolStatus.ClientError, errorMsg));
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**  */
public void connectionTo(final InterAddress hostAddress, final BasicFuture<RsfChannel> result) {
    ////from  w  ww  .j  a  v  a 2  s .  com
    //
    Bootstrap boot = new Bootstrap();
    boot.group(this.workLoopGroup);
    boot.channel(NioSocketChannel.class);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    ChannelFuture future = configBoot(boot).connect(hostAddress.toSocketAddress());
    //
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                logger.error("connect to {} error.", hostAddress, future.cause());
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                logger.info("connect to {} Success.", hostAddress);
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Out));
            }
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**
 * ??//from w w w .  j  ava 2 s . c  om
 * @param listenLoopGroup ?
 */
public void startListener(NioEventLoopGroup listenLoopGroup) {
    //
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(listenLoopGroup, this.workLoopGroup);
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress());
    //
    final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>();
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener));
            }
        }
    });
    try {
        this.localListener = result.get();
        logger.info("rsf Server started at {}", this.bindAddress);
    } catch (Exception e) {
        logger.error("rsf start listener error: " + e.getMessage(), e);
        throw new RsfException(ProtocolStatus.NetworkError,
                this.bindAddress.toString() + " -> " + e.getMessage());
    }
    //
}

From source file:net.hasor.rsf.rpc.net.RsfChannel.java

License:Apache License

/**? Netty*/
private void sendData(final long requestID, Object sendData, final SendCallBack callBack) {
    if (!this.channel.isActive()) {
        RsfException e = new RsfException(ProtocolStatus.NetworkError,
                "send (" + requestID + ") an error, socket Channel is close.");
        if (callBack != null) {
            callBack.failed(requestID, e);
        }//from  w w  w.  j  ava 2 s.  c  om
        return;
    }
    /*???*/
    this.sendPackets++;
    ChannelFuture future = this.channel.writeAndFlush(sendData);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                if (callBack != null) {
                    callBack.complete(requestID);
                }
                return;
            }
            lastSendTime = System.currentTimeMillis();
            RsfException e = null;
            if (future.isCancelled()) {
                //?
                String errorMsg = "send request(" + requestID + ") to cancelled by user.";
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            } else if (!future.isSuccess()) {
                //
                Throwable ex = future.cause();
                String errorMsg = "send request(" + requestID + ") an error ->" + ex.getMessage();
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg, ex);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            }
        }
    });
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);//from  www  .  j av  a  2s  . c om
        return future;
    }

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {
            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup group = new NioEventLoopGroup(protocol.getThreads());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslContext != null) {
                pipeline.addLast(
                        sslContext.newHandler(channel.alloc(), protocol.getHost(), protocol.getPort()));
            }
            pipeline.addLast(new ObjectEncoder(),
                    new ObjectDecoder(
                            ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                    new TcpProtocolClientHandler(TcpProtocolClient.this));
        }
    });

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> close() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override/*from   w w  w.j a v a2 s .c  o  m*/
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                channel = null;
                if (channelFuture.isSuccess()) {
                    future.complete(null);
                } else {
                    future.completeExceptionally(channelFuture.cause());
                }
            }
        });
    } else {
        future.complete(null);
    }
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*  w w w.  ja v a  2s.  c  o  m*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> stop() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override/*w  ww  .  ja  va2s  . c  om*/
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    future.complete(null);
                } else {
                    future.completeExceptionally(channelFuture.cause());
                }
            }
        });
    } else {
        future.complete(null);
    }
    return future;
}

From source file:net.sourceforge.entrainer.socket.EntrainerSocketManager.java

License:Open Source License

/**
 * Binds the socket to the port specified in {@link Settings}.
 *
 * @throws IOException/*from  w w  w .  ja  v  a 2 s. com*/
 *           Signals that an I/O exception has occurred.
 * @throws InvalidPortNumberException
 *           if the port number <= 0.
 */
public void bind() throws IOException, InvalidPortNumberException {
    if (isBound())
        return;

    String ipAddress = Settings.getInstance().getSocketIPAddress();
    if (ipAddress == null || ipAddress.trim().length() == 0)
        initIPAddress();

    ipAddress = Settings.getInstance().getSocketIPAddress();

    if (bootstrap == null)
        initAcceptor();

    int port = Settings.getInstance().getSocketPort();
    if (port <= 0)
        throw new InvalidPortNumberException(port);

    ChannelFuture cf = bootstrap.bind(ipAddress, port).syncUninterruptibly();
    if (cf.isSuccess()) {
        channel = cf.channel();
    } else {
        throw new RuntimeException("Could not bind to host " + ipAddress + " and port " + port, cf.cause());
    }
}

From source file:net.tomp2p.connection.ChannelServer.java

License:Apache License

/**
 * Handles the waiting and returning the channel.
 * /* w  w w. j  av a  2s.  c o  m*/
 * @param future
 *            The future to wait for
 * @return The channel or null if we failed to bind.
 */
private boolean handleFuture(final ChannelFuture future) {
    try {
        future.await();
    } catch (InterruptedException e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("could not start UPD server", e);
        }
        return false;
    }
    boolean success = future.isSuccess();
    if (success) {
        return true;
    } else {
        LOG.debug("binding not successful", future.cause());
        return false;
    }

}