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.vmware.xenon.common.http.netty.NettyChannelPool.java

License:Open Source License

/**
 * When using HTTP/2, we have to wait for the settings to be negotiated before we can send
 * data. We wait for a promise that comes from the HTTP client channel pipeline
 *///from   w  w w  .  j  ava  2 s. c  om
private void waitForSettings(Channel ch, NettyChannelContext contextFinal, Operation request,
        NettyChannelGroup group) {
    ChannelPromise settingsPromise = ch.attr(NettyChannelContext.SETTINGS_PROMISE_KEY).get();
    settingsPromise.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {

            if (future.isSuccess()) {

                // retrieve pending operations
                List<Operation> pendingOps = new ArrayList<>();
                synchronized (group) {
                    contextFinal.setOpenInProgress(false);
                    contextFinal.setChannel(future.channel()).setOperation(request);
                    pendingOps.addAll(group.pendingRequests);
                    group.pendingRequests.clear();
                }

                sendAfterConnect(future.channel(), contextFinal, request, group);

                // trigger pending operations
                for (Operation pendingOp : pendingOps) {
                    pendingOp.setSocketContext(contextFinal);
                    pendingOp.complete();
                }

            } else {
                returnOrClose(contextFinal, true);
                fail(request, future.cause());
            }
        }
    });
}

From source file:com.vmware.xenon.common.test.websockets.JsWebSocket.java

License:Open Source License

/**
 * Standard constructor WebSocket(uri) available in JavaScript API
 *
 * @param endpointUri Websocket endpoint URI
 *//*from  w  ww  .ja  v  a 2 s .c o  m*/
public JsWebSocket(String endpointUri) throws Exception {
    URI uri = new URI(endpointUri);
    String scheme = uri.getScheme() == null ? WS_SCHEME : uri.getScheme();
    final String host = uri.getHost() == null ? ServiceHost.LOCAL_HOST : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if (WS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (WSS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!WS_SCHEME.equalsIgnoreCase(scheme) && !WSS_SCHEME.equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = WSS_SCHEME.equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    this.group = new NioEventLoopGroup();

    // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
    // If you change it to V00, ping is not supported and remember to change
    // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
    DefaultHttpHeaders headers = new DefaultHttpHeaders();
    if (OperationContext.getAuthorizationContext() != null
            && OperationContext.getAuthorizationContext().getToken() != null) {
        headers.add(HttpHeaderNames.COOKIE,
                CookieJar.encodeCookies(
                        Collections.singletonMap(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE,
                                OperationContext.getAuthorizationContext().getToken())));
    }
    final WebSocketClientHandler handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, headers));
    Bootstrap b = new Bootstrap();
    b.group(this.group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
            }
            p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
        }
    });

    this.channel = b.connect(uri.getHost(), port).sync().channel();
    handler.handshakeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                JsExecutor.executeSynchronously(() -> {
                    if (future.isSuccess()) {
                        if (JsWebSocket.this.onopen != null) {
                            JsWebSocket.this.onopen.call(Context.getCurrentContext(), getParentScope(),
                                    JsWebSocket.this, new Object[] { null });
                        }
                    } else {
                        throw new RuntimeException(future.cause());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.weibo.api.motan.transport.netty.NettyChannel.java

License:Apache License

@Override
public Response request(Request request) throws TransportException {
    int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(),
            URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.",
                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }//from  www  . ja  va  2 s  .com
    NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient);
    this.nettyClient.registerCallback(request.getRequestId(), response);

    ChannelFuture writeFuture = this.channel.writeAndFlush(request);

    boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);

    if (result && writeFuture.isSuccess()) {
        response.addListener(new FutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()
                        || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
                    // ? 
                    nettyClient.resetErrorCount();
                } else {
                    //  
                    nettyClient.incrErrorCount();
                }
            }
        });
        return response;
    }

    writeFuture.cancel(false);
    response = this.nettyClient.removeCallback(request.getRequestId());

    if (response != null) {
        response.cancel();
    }

    //  
    nettyClient.incrErrorCount();

    if (writeFuture.cause() != null) {
        throw new MotanServiceException(
                "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local="
                        + localAddress + " " + MotanFrameworkUtil.toString(request),
                writeFuture.cause());
    } else {
        throw new MotanServiceException(
                "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local="
                        + localAddress + " " + MotanFrameworkUtil.toString(request));
    }
}

From source file:com.weibo.api.motan.transport.netty.NettyChannel.java

License:Apache License

@Override
public synchronized boolean open() {
    if (isAvailable()) {
        LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress
                + " url: " + nettyClient.getUrl().getUri());
        return true;
    }//from   www .  j  a  va2s .  c  o m

    try {
        ChannelFuture channleFuture = nettyClient.getBootstrap()
                .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));

        long start = System.currentTimeMillis();

        int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(),
                URLParamType.connectTimeout.getIntValue());
        if (timeout <= 0) {
            throw new MotanFrameworkException(
                    "NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.",
                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
        // ??connectTimeout
        boolean result = channleFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
        boolean success = channleFuture.isSuccess();

        if (result && success) {
            channel = channleFuture.channel();
            if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) {
                localAddress = (InetSocketAddress) channel.localAddress();
            }

            state = ChannelState.ALIVE;
            return true;
        }
        boolean connected = false;
        if (channleFuture.channel() != null) {
            connected = channleFuture.channel().isActive();
        }

        if (channleFuture.cause() != null) {
            channleFuture.cancel(false);
            throw new MotanServiceException(
                    "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri()
                            + ", result: " + result + ", success: " + success + ", connected: " + connected,
                    channleFuture.cause());
        } else {
            channleFuture.cancel(false);
            throw new MotanServiceException("NettyChannel connect to server timeout url: "
                    + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start)
                    + ", result: " + result + ", success: " + success + ", connected: " + connected);
        }
    } catch (MotanServiceException e) {
        throw e;
    } catch (Exception e) {
        throw new MotanServiceException(
                "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e);
    } finally {
        if (!state.isAliveState()) {
            nettyClient.incrErrorCount();
        }
    }
}

From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java

License:Apache License

@Override
public Response request(Request request) throws TransportException {
    int timeout = nettyClient.getUrl().getMethodParameter(request.getMethodName(), request.getParamtersDesc(),
            URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.",
                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }/*from   w w  w  . j  a va 2 s. c o m*/
    NettyResponseFuture response = new NettyResponseFuture(request, timeout, this.nettyClient);
    this.nettyClient.registerCallback(request.getRequestId(), response);

    ChannelFuture writeFuture = this.channel.writeAndFlush(request);

    boolean result = writeFuture.awaitUninterruptibly(timeout, TimeUnit.SECONDS);

    if (result && writeFuture.isSuccess()) {
        response.addListener(new FutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()
                        || (future.isDone() && ExceptionUtil.isBizException(future.getException()))) {
                    // ? 
                    nettyClient.resetErrorCount();
                } else {
                    //  
                    nettyClient.incrErrorCount();
                }
            }
        });
        return response;
    }

    writeFuture.cancel(true);
    response = this.nettyClient.removeCallback(request.getRequestId());

    if (response != null) {
        response.cancel();
    }

    //  
    nettyClient.incrErrorCount();

    if (writeFuture.cause() != null) {
        throw new MotanServiceException(
                "NettyChannel send request to server Error: url=" + nettyClient.getUrl().getUri() + " local="
                        + localAddress + " " + MotanFrameworkUtil.toString(request),
                writeFuture.cause());
    } else {
        throw new MotanServiceException(
                "NettyChannel send request to server Timeout: url=" + nettyClient.getUrl().getUri() + " local="
                        + localAddress + " " + MotanFrameworkUtil.toString(request));
    }
}

From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java

License:Apache License

@Override
public synchronized boolean open() {
    if (isAvailable()) {
        LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress
                + " url: " + nettyClient.getUrl().getUri());
        return true;
    }/*from  w w  w  .  j a v a2s.co m*/

    try {
        ChannelFuture channelFuture = nettyClient.getBootstrap()
                .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort()));

        long start = System.currentTimeMillis();

        int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(),
                URLParamType.connectTimeout.getIntValue());
        if (timeout <= 0) {
            throw new MotanFrameworkException(
                    "Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.",
                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
        // ??connectTimeout
        boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
        boolean success = channelFuture.isSuccess();

        if (result && success) {
            channel = channelFuture.channel();
            if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) {
                localAddress = (InetSocketAddress) channel.localAddress();
            }

            state = ChannelState.ALIVE;
            return true;
        }
        boolean connected = false;
        if (channelFuture.channel() != null) {
            connected = channelFuture.channel().isOpen();
        }

        if (channelFuture.cause() != null) {
            channelFuture.cancel(true);
            throw new MotanServiceException(
                    "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri()
                            + ", result: " + result + ", success: " + success + ", connected: " + connected,
                    channelFuture.cause());
        } else {
            channelFuture.cancel(true);
            throw new MotanServiceException("NettyChannel connect to server timeout url: "
                    + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start)
                    + ", result: " + result + ", success: " + success + ", connected: " + connected);
        }
    } catch (MotanServiceException e) {
        throw e;
    } catch (Exception e) {
        throw new MotanServiceException(
                "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e);
    } finally {
        if (!state.isAliveState()) {
            nettyClient.incrErrorCount();
        }
    }
}

From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java

License:Open Source License

/**
 * Start the discovery process.//from  w  ww . j a  v  a 2  s .  c o  m
 *
 * @throws IOException on failure
 */
public void start() throws IOException {
    searchRequestRunnable = new SearchRequestRunnable(this);

    // set up the inbound channel handler
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new DatagramToByteBufHandler()); // convert an incoming DatagramPacket into a ByteBuf
            pipeline.addLast(new OrderDecoder()); // convert an incoming ByteBuf into an Order
            pipeline.addLast(new InboundOrderHandler(listener)); // handle incoming Orders
        }
    });

    // bind to the address
    ChannelFuture cf = bootstrap.bind(new InetSocketAddress(0));
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = (DatagramChannel) channelFuture.channel();

                // perform initial search request
                group.execute(searchRequestRunnable);

                // schedule two quick follow-up search requests to make sure a camera didn't miss the first request
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS,
                        TimeUnit.SECONDS);
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2,
                        TimeUnit.SECONDS);

                // set up a recurring search request so we can keep track of cameras coming/going
                searchFuture = group.scheduleAtFixedRate(searchRequestRunnable,
                        SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2 + getSearchRequestFrequencySeconds,
                        getSearchRequestFrequencySeconds, TimeUnit.SECONDS);
            } else {
                logger.error("Bind attempt failed", channelFuture.cause());
            }
        }
    });
}

From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java

License:Open Source License

/**
 * Connect the channel.// w  w  w .  ja v a  2  s  .c o  m
 *
 * @param b a Netty Bootstrap object
 */
synchronized private void connect(Bootstrap b) {
    logger.debug("connect()");
    if (connectionState == State.NOT_CONNECTED) {
        logger.debug("Attempting to connect");
        connectionState = State.CONNECTING;
        b.connect(socketAddress).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    logger.debug("Connection established");
                    connectionState = State.CONNECTED;

                    // save the channel
                    AbstractChannelObjectPlugin.this.channel = channelFuture.channel();

                    // set a close listener to notify the plugin subclass when the channel has closed
                    channel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
                            logger.info("Connection was closed");
                            channel = null;
                            connectionState = State.NOT_CONNECTED;
                            executeInEventLoop(new Runnable() {
                                @Override
                                public void run() {
                                    onChannelDisconnected();
                                }
                            });
                            if (isRunning) {
                                scheduleReconnect(channelFuture.channel().eventLoop());
                            }
                        }
                    });

                    executeInEventLoop(new Runnable() {
                        @Override
                        public void run() {
                            onChannelConnected();
                        }
                    });
                } else {
                    logger.warn("Connection attempt to " + socketAddress.toString() + " failed",
                            channelFuture.cause());
                    connectionState = State.NOT_CONNECTED;
                    if (isRunning) {
                        scheduleReconnect(channelFuture.channel().eventLoop());
                    }
                }
            }
        });
    } else {
        logger.debug("Ignoring connect request due to state: " + connectionState);
    }
}

From source file:com.whizzosoftware.wzwave.controller.netty.NettyZWaveController.java

License:Open Source License

public void start() {
    if (channel == null) {
        // set up Netty bootstrap
        bootstrap = new Bootstrap();
        bootstrap.group(new OioEventLoopGroup());
        bootstrap.channel(RxtxChannel.class);
        bootstrap.handler(new ChannelInitializer<RxtxChannel>() {
            @Override//from   w  w  w  . jav a2  s .com
            protected void initChannel(RxtxChannel channel) throws Exception {
                NettyZWaveController.this.channel = channel;
                channel.config().setBaudrate(115200);
                channel.config().setDatabits(RxtxChannelConfig.Databits.DATABITS_8);
                channel.config().setParitybit(RxtxChannelConfig.Paritybit.NONE);
                channel.config().setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
                channel.pipeline().addLast("decoder", new ZWaveFrameDecoder());
                channel.pipeline().addLast("ack", new ACKInboundHandler());
                channel.pipeline().addLast("encoder", new ZWaveFrameEncoder());
                channel.pipeline().addLast("writeQueue", new FrameQueueHandler());
                channel.pipeline().addLast("transaction", new TransactionInboundHandler());
                channel.pipeline().addLast("handler", inboundHandler);
            }
        });

        bootstrap.connect(new RxtxDeviceAddress(serialPort)).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    sendDataFrame(new Version());
                    sendDataFrame(new MemoryGetId());
                    sendDataFrame(new InitData());
                } else {
                    onZWaveConnectionFailure(future.cause());
                }
            }
        });
    }
}

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java

License:Apache License

/**
 * ?????/*from  w ww.j  a  va 2  s .co  m*/
 * @param channel
 * @param request
 * @param timeoutMillis
 * @return
 * @throws InterruptedException
 * @throws RemotingSendRequestException
 * @throws RemotingTimeoutException
 */
public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    final int opaque = request.getOpaque();

    try {
        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                plog.warn("send a request command to channel <" + addr + "> failed.");
            }
        });
        // ?responseFuture.putResponse
        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}