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:org.wso2.carbon.transport.http.netty.contractimpl.HttpClientConnectorImpl.java

License:Open Source License

@Override
public HttpResponseFuture send(HTTPCarbonMessage httpCarbonRequest) {
    HttpResponseFuture httpResponseFuture = new HttpResponseFutureImpl();

    SourceHandler srcHandler = (SourceHandler) httpCarbonRequest.getProperty(Constants.SRC_HANDLER);
    if (srcHandler == null) {
        if (log.isDebugEnabled()) {
            log.debug(Constants.SRC_HANDLER + " property not found in the message."
                    + " Message is not originated from the HTTP Server connector");
        }//www.java2  s  . co  m
    }

    try {
        final HttpRoute route = getTargetRoute(httpCarbonRequest);
        Util.setupTransferEncodingForRequest(httpCarbonRequest, chunkDisabled);
        TargetChannel targetChannel = connectionManager.borrowTargetChannel(route, srcHandler, sslConfig,
                httpTraceLogEnabled, chunkDisabled, followRedirect, maxRedirectCount, proxyServerConfiguration);
        targetChannel.getChannelFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (isValidateChannel(channelFuture)) {
                    targetChannel.setChannel(channelFuture.channel());
                    targetChannel.configTargetHandler(httpCarbonRequest, httpResponseFuture);
                    targetChannel.setEndPointTimeout(socketIdleTimeout, followRedirect);
                    targetChannel.setCorrelationIdForLogging();
                    targetChannel.setChunkDisabled(chunkDisabled);
                    targetChannel.setRequestWritten(true);
                    if (followRedirect) {
                        setChannelAttributes(channelFuture.channel(), httpCarbonRequest, httpResponseFuture,
                                targetChannel);
                    }
                    targetChannel.writeContent(httpCarbonRequest);
                } else {
                    notifyErrorState(channelFuture);
                }
            }

            private boolean isValidateChannel(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isDone() && channelFuture.isSuccess()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Created the connection to address: {}", route.toString() + " "
                                + "Original Channel ID is : " + channelFuture.channel().id());
                    }
                    return true;
                }
                return false;
            }

            private void notifyErrorState(ChannelFuture channelFuture) {
                ClientConnectorException cause;

                if (channelFuture.isDone() && channelFuture.isCancelled()) {
                    cause = new ClientConnectorException("Request Cancelled, " + route.toString(),
                            HttpResponseStatus.BAD_GATEWAY.code());
                } else if (!channelFuture.isDone() && !channelFuture.isSuccess() && !channelFuture.isCancelled()
                        && (channelFuture.cause() == null)) {
                    cause = new ClientConnectorException("Connection timeout, " + route.toString(),
                            HttpResponseStatus.BAD_GATEWAY.code());
                } else {
                    cause = new ClientConnectorException("Connection refused, " + route.toString(),
                            HttpResponseStatus.BAD_GATEWAY.code());
                }

                if (channelFuture.cause() != null) {
                    cause.initCause(channelFuture.cause());
                }

                httpResponseFuture.notifyHttpListener(cause);
            }
        });
        Util.prepareBuiltMessageForTransfer(httpCarbonRequest);
    } catch (Exception failedCause) {
        httpResponseFuture.notifyHttpListener(failedCause);
    }

    return httpResponseFuture;
}

From source file:org.wso2.carbon.transport.http.netty.sender.channel.TargetChannelListener.java

License:Open Source License

private void notifyErrorState(ChannelFuture channelFuture) {
    if (channelFuture.isDone() && channelFuture.isCancelled()) {
        ConnectException cause = new ConnectException("Request Cancelled, " + httpRoute.toString());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }// w  w  w .j a v a2s.co m
        this.targetChannel.getTargetHandler().getHttpResponseFuture().notifyHttpListener(cause);
    } else if (!channelFuture.isDone() && !channelFuture.isSuccess() && !channelFuture.isCancelled()
            && (channelFuture.cause() == null)) {
        ConnectException cause = new ConnectException("Connection timeout, " + httpRoute.toString());
        this.targetChannel.getTargetHandler().getHttpResponseFuture().notifyHttpListener(cause);
    } else {
        ConnectException cause = new ConnectException("Connection refused, " + httpRoute.toString());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }
        this.targetChannel.getTargetHandler().getHttpResponseFuture().notifyHttpListener(cause);
    }
}

From source file:org.wso2.carbon.transport.http.netty.sender.RedirectHandler.java

License:Open Source License

/**
 * Register channel future listener on channel future.
 *
 * @param channelHandlerContext Channel handler context
 * @param channelFuture         Chanel future
 * @param httpCarbonRequest     Carbon request
 * @param httpRequest           http request
 */// w ww .j av  a  2 s  . com
private void registerListener(ChannelHandlerContext channelHandlerContext, ChannelFuture channelFuture,
        HTTPCarbonMessage httpCarbonRequest, HttpRequest httpRequest) {
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess() && future.isDone()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Connected to the new channel " + future.channel().id() + " and getting ready to "
                            + "write request.");
                }
                long channelStartTime = channelHandlerContext.channel()
                        .attr(Constants.ORIGINAL_CHANNEL_START_TIME).get();
                int timeoutOfOriginalRequest = channelHandlerContext.channel()
                        .attr(Constants.ORIGINAL_CHANNEL_TIMEOUT).get();
                setChannelAttributes(channelHandlerContext, future, httpCarbonRequest, channelStartTime,
                        timeoutOfOriginalRequest);
                long remainingTimeForRedirection = getRemainingTimeForRedirection(channelStartTime,
                        timeoutOfOriginalRequest);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Remaining time for redirection is : " + remainingTimeForRedirection);
                }
                future.channel().pipeline().addBefore(Constants.REDIRECT_HANDLER, Constants.IDLE_STATE_HANDLER,
                        new IdleStateHandler(remainingTimeForRedirection, remainingTimeForRedirection, 0,
                                TimeUnit.MILLISECONDS));
                future.channel().write(httpRequest);
                future.channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
                /* if the previous channel is not original channel, closes it after sending the request through
                 new channel*/
                if (channelHandlerContext != originalChannelContext) {
                    channelHandlerContext.close();
                }
            } else {
                LOG.error("Error occurred while trying to connect to redirect channel.", future.cause());
                exceptionCaught(channelHandlerContext, future.cause());
            }
        }
    });
}

From source file:org.wso2.carbon.transport.http.netty.sender.websocket.WebSocketClient.java

License:Open Source License

/**
 * Handle the handshake with the server.
 *
 * @return handshake future for connection.
 *///from   w  w w .j  a v  a  2s . c  o m
public HandshakeFuture handshake() {
    HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl();
    try {
        URI uri = new URI(url);
        String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final int port;
        if (uri.getPort() == -1) {
            if ("ws".equalsIgnoreCase(scheme)) {
                port = 80;
            } else if ("wss".equalsIgnoreCase(scheme)) {
                port = 443;
            } else {
                port = -1;
            }
        } else {
            port = uri.getPort();
        }

        if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
            log.error("Only WS(S) is supported.");
            throw new SSLException("");
        }

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

        group = new NioEventLoopGroup();
        HttpHeaders httpHeaders = new DefaultHttpHeaders();

        // Adding custom headers to the handshake request.

        if (headers != null) {
            headers.entrySet().forEach(entry -> httpHeaders.add(entry.getKey(), entry.getValue()));
        }

        WebSocketClientHandshaker websocketHandshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                WebSocketVersion.V13, subProtocols, true, httpHeaders);
        handler = new WebSocketTargetHandler(websocketHandshaker, ssl, url, target, connectorListener);

        Bootstrap b = new Bootstrap();
        b.group(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());
                p.addLast(new HttpObjectAggregator(8192));
                p.addLast(WebSocketClientCompressionHandler.INSTANCE);
                if (idleTimeout > 0) {
                    p.addLast(
                            new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS));
                }
                p.addLast(handler);
            }
        });

        b.connect(uri.getHost(), port).sync();
        ChannelFuture future = handler.handshakeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                Throwable cause = future.cause();
                if (future.isSuccess() && cause == null) {
                    WebSocketSessionImpl session = (WebSocketSessionImpl) handler.getChannelSession();
                    String actualSubProtocol = websocketHandshaker.actualSubprotocol();
                    handler.setActualSubProtocol(actualSubProtocol);
                    session.setNegotiatedSubProtocol(actualSubProtocol);
                    session.setIsOpen(true);
                    handshakeFuture.notifySuccess(session);
                } else {
                    handshakeFuture.notifyError(cause);
                }
            }
        }).sync();
        handshakeFuture.setChannelFuture(future);
    } catch (Throwable t) {
        handshakeFuture.notifyError(t);
    }

    return handshakeFuture;
}

From source file:org.wso2.carbon.transport.http.netty.util.client.http2.HTTP2ResponseHandler.java

License:Open Source License

/**
 * Provide asynchronous response to HTTP2 request
 *
 * @param streamId StreamID/*  ww w  .j a va2s. c  om*/
 * @return Response string
 */
public String getResponse(int streamId) {

    String message = streamIdResponseMap.get(streamId);
    if (message != null) {
        return message;
    } else {
        Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap
                .get(streamId);
        if (channelFutureChannelPromiseEntry != null) {
            ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey();
            if (!writeFuture.awaitUninterruptibly(TestUtil.HTTP2_RESPONSE_TIME_OUT,
                    TestUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting to write for stream id " + streamId);
            }
            if (!writeFuture.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(writeFuture.cause());
            }
            ChannelPromise promise = channelFutureChannelPromiseEntry.getValue();
            if (!promise.awaitUninterruptibly(TestUtil.HTTP2_RESPONSE_TIME_OUT,
                    TestUtil.HTTP2_RESPONSE_TIME_UNIT)) {
                streamIdPromiseMap.remove(streamId);
                throw new IllegalStateException("Timed out waiting for response on stream id " + streamId);
            }
            if (!promise.isSuccess()) {
                streamIdPromiseMap.remove(streamId);
                throw new RuntimeException(promise.cause());
            }
        }
    }
    return streamIdResponseMap.get(streamId);
}

From source file:org.wso2.esb.integration.common.utils.clients.http2client.HttpResponseHandler.java

License:Open Source License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *///from  w ww . j a  v  a 2 s . co m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        log.debug("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:org.wso2.extension.siddhi.io.tcp.sink.TCPSink.java

License:Open Source License

@Override
public void publish(Object payload, DynamicOptions dynamicOptions) throws ConnectionUnavailableException {
    try {/*from   ww w. j av a 2 s .c  om*/
        byte[] message;
        if (payload instanceof String) {
            message = ((String) payload).getBytes(Charset.defaultCharset());
        } else if (payload instanceof ByteBuffer) {
            message = ((ByteBuffer) payload).array();
        } else {
            message = (byte[]) payload;
        }
        boolean isSync;
        if (sync != null) {
            isSync = sync;
        } else {
            isSync = Boolean.parseBoolean(syncOption.getValue(dynamicOptions));
        }
        if (isSync) {
            try {
                ChannelFuture future = tcpNettyClient.send(channelId, message);
                future.sync();
                if (!future.isSuccess()) {
                    throw new ConnectionUnavailableException(
                            "Error sending events to '" + hostAndPort + "' on channel '" + channelId + "', "
                                    + hostAndPort + ", " + future.cause().getMessage(),
                            future.cause());
                }
            } catch (InterruptedException e) {
                throw new ConnectionUnavailableException("Error sending events to '" + hostAndPort
                        + "' on channel '" + channelId + "', " + hostAndPort + ", " + e.getMessage(), e);
            }
        } else {
            ChannelFuture future = tcpNettyClient.send(channelId, message);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        log.error("Error sending events to '" + hostAndPort + "' on channel '" + channelId
                                + "', " + future.cause() + ", dropping events ", future.cause());
                    }
                }
            });
            if (future.isDone() && !future.isSuccess()) {
                throw new ConnectionUnavailableException(
                        "Error sending events to '" + hostAndPort + "' on channel '" + channelId + "', "
                                + hostAndPort + ", " + future.cause().getMessage(),
                        future.cause());
            }
        }
    } catch (Throwable t) {
        throw new ConnectionUnavailableException("Error sending events to '" + hostAndPort + "' on channel '"
                + channelId + "', " + hostAndPort + ", " + t.getMessage(), t);
    }
}

From source file:org.wso2.siddhi.debs2017.transport.utils.TcpNettyClient.java

License:Open Source License

public ChannelFuture send(String streamId, Event[] events) {
    EventComposite EventComposite = new EventComposite(sessionId, streamId, events);
    ChannelFuture cf = channel.writeAndFlush(EventComposite);
    cf.addListener(new ChannelFutureListener() {
        @Override/*from  w  w  w .  j  a v  a2 s  .  com*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                System.out.println("Error sending events to '" + hostAndPort + "' on stream '" + streamId
                        + "', " + future.cause() + ", dropping events " + Arrays.deepToString(events) + "\n"
                        + future.cause());
            }
        }
    });
    return cf;
}

From source file:p2p_server.DeviceHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // System.out.println("Dev recv msg " + msg);
    Gson json = new Gson();

    int msglen = msg.toString().length();
    String s = msg.toString() + "\r\n";
    Type type = new TypeToken<Map<String, String>>() {
    }.getType();/*from w  ww . j a v a2s .c o  m*/
    Map<String, String> dict;
    dict = json.fromJson(s.substring(2, msglen), type);

    String cmd = "";
    try {
        cmd = dict.get(CMD).toString();
        //System.out.println("is login " + cmd);
    } catch (NullPointerException e) {
        write_error(ctx, unkown_cmd);
        return;
    }
    if (cmd.compareTo(LOGIN) == 0) {
        // System.out.println("login ok");
        String uuid = "";
        String pwd = "";
        try {
            uuid = dict.get(UUID).toString();
            pwd = dict.get(PWD).toString();
        } catch (NullPointerException ue) {
            write_error(ctx, unkown_format);
            return;
            // ue.printStackTrace();
        }
        /*??? */
        Object[] oldobj = null;
        try {
            oldobj = dc.getDevChannel(uuid);
        } catch (NullPointerException npe) {
        }

        if (oldobj != null) {
            /* ?  */
            Channel oldch = (Channel) oldobj[1];
            Map<String, String> notifyDict = new HashMap<>();
            notifyDict.put(MSG, "new login from " + ctx.channel().remoteAddress());
            String jsondata = json.toJson(notifyDict);
            ByteBuf sendbuf = oldch.alloc().heapBuffer(jsondata.toString().length() + 4);
            int len = jsondata.length() + 2;
            byte[] lenarry = { 0x0, 0x0 };
            lenarry[0] = (byte) (0xff00 & len);
            lenarry[1] = (byte) (0xff & len);
            sendbuf.writeBytes(lenarry);
            sendbuf.writeBytes(jsondata.toString().getBytes());
            sendbuf.writeBytes("\r\n\r\n".getBytes());
            ChannelFuture write = oldch.writeAndFlush(sendbuf);
            if (!write.isSuccess()) {
                System.out.println("notify new login failed: " + write.cause());
            }
            dc.removeDevChannel(uuid);
            write.addListener(ChannelFutureListener.CLOSE);
        }

        dc.bandUserAndChannel(uuid, pwd, ctx.channel());
        ByteBuf sendbuf = ctx.alloc().heapBuffer(msg_ok.length);
        sendbuf.writeBytes(msg_ok);
        // sendbuf.writeBytes(msg_ok);

        ChannelFuture write = ctx.channel().writeAndFlush(sendbuf);
        if (!write.isSuccess()) {

            System.out.println("send login failed: " + write.cause());
        }

    } else if (0 == cmd.compareTo(KEEP)) {
        //  System.out.println("keep ok");
        ByteBuf sendbuf = ctx.alloc().heapBuffer(msg.toString().length() + 4);
        sendbuf.writeBytes(msg.toString().getBytes());
        sendbuf.writeBytes("\r\n\r\n".getBytes());
        ChannelFuture write = ctx.writeAndFlush(sendbuf);

        if (!write.isSuccess()) {
            System.out.println("send keep failed: " + write.cause());
        }

    } else if (0 == cmd.compareTo(CONN)) {

        String aid = "";
        try {
            aid = dict.get(AID);
        } catch (NullPointerException ue) {
            //ue.printStackTrace();
            write_error(ctx, unkown_format);
            return;

        }
        // Promise<Channel> promise = ctx.executor().newPromise();

        // System.out.println("recv dev conn for aid "+aid);
        Channel appChannel = dc.getAppChannel(aid);
        //System.out.println("app dict size : " + dc.getMapSize("app"));

        if (appChannel instanceof Channel) {
            // System.out.println("ready send addr to app!!!!");
            ByteBuf sendbuf = appChannel.alloc().heapBuffer(msg.toString().length() + 4);
            sendbuf.writeBytes(msg.toString().getBytes());
            sendbuf.writeBytes("\r\n\r\n".getBytes());
            ChannelFuture write = appChannel.writeAndFlush(sendbuf);

            /* 
                if (!write.isSuccess()) {
                    System.out.println("send to app failed: " + write.cause());
                }
             */
            dc.removeAppChannel(aid);
            write.addListener(ChannelFutureListener.CLOSE);

        }

    } else {
        //?
        write_error(ctx, unkown_cmd);
    }

}

From source file:p2p_server.DeviceHandler.java

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
        IdleStateEvent event = (IdleStateEvent) evt;

        // sendbuf.writeBytes(msg_ok);
        if (null != event.state()) {
            switch (event.state()) {
            case READER_IDLE:
                System.out.println("dev read idle");
                break;
            case WRITER_IDLE:
                System.out.println("dev write idle");
                break;
            case ALL_IDLE:
                System.out.println("dev all idle");
                break;
            default:
                break;
            }/*from  w  w  w .  j  a  v a  2 s.c  om*/
        }
        ByteBuf sendbuf = ctx.alloc().heapBuffer(msg_keep.length);
        sendbuf.writeBytes(msg_keep);
        ChannelFuture write = ctx.channel().writeAndFlush(sendbuf);
        if (!write.isSuccess()) {

            System.out.println("send login failed: " + write.cause());
        }
    }
}