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.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation.//from   www. j av a  2  s  .  c  o  m
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Utils.checkArgument(msg != null);
    Utils.checkState(channel.isOpen(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = egroup.next().newPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Utils.propagate(e);
    }
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

protected Channel createConnectedChannel(String host, int port, long connectTimeoutMillis)
        throws SmppTimeoutException, SmppChannelException, InterruptedException {
    // a socket address used to "bind" to the remote system
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);

    // attempt to connect to the remote system
    ChannelFuture connectFuture = this.clientBootstrap.connect(socketAddr);

    // wait until the connection is made successfully
    boolean timeout = !connectFuture.await(connectTimeoutMillis);

    if (timeout) {
        throw new SmppChannelConnectTimeoutException("Unable to connect to host [" + host + "] and port ["
                + port + "] within " + connectTimeoutMillis + " ms");
    }/*  ww  w  .j  a  v a  2 s  .  c  o m*/

    if (!connectFuture.isSuccess()) {
        throw new SmppChannelConnectException("Unable to connect to host [" + host + "] and port [" + port
                + "]: " + connectFuture.cause().getMessage(), connectFuture.cause());
    }

    // if we get here, then we were able to connect and get a channel
    return connectFuture.channel();
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from  w ww.  java 2 s. co  m
public WindowFuture<Integer, PduRequest, PduResponse> sendRequestPdu(PduRequest pdu, long timeoutMillis,
        boolean synchronous) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException,
        SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    WindowFuture<Integer, PduRequest, PduResponse> future = null;
    try {
        future = sendWindow.offer(pdu.getSequenceNumber(), pdu, timeoutMillis,
                configuration.getRequestExpiryTimeout(), synchronous);
    } catch (DuplicateKeyException e) {
        throw new UnrecoverablePduException(e.getMessage(), e);
    } catch (OfferTimeoutException e) {
        throw new SmppTimeoutException(e.getMessage(), e);
    }

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        if (synchronous) {
            logger.info("sync send PDU: {}", pdu);
        } else {
            logger.info("async send PDU: {}", pdu);
        }
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }

    this.countSendRequestPdu(pdu);

    return future;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

/**
 * Asynchronously sends a PDU and does not wait for a response PDU.
 * This method will wait for the PDU to be written to the underlying channel.
 * @param pdu The PDU to send (can be either a response or request)
 * @throws RecoverablePduException/* w w  w. j  a  v  a  2  s.c o  m*/
 * @throws UnrecoverablePduException
 * @throws SmppChannelException
 * @throws InterruptedException
 */
@Override
public void sendResponsePdu(PduResponse pdu)
        throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        logger.info("send PDU: {}", pdu);
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }
}

From source file:com.cloudhopper.smpp.impl.UnboundSmppSession.java

License:Apache License

public void sendResponsePdu(PduResponse pdu) {
    try {/*from ww w  .  j  ava2s  .c  o  m*/
        // encode the pdu into a buffer
        ByteBuf buffer = server.getTranscoder().encode(pdu);

        // always log the PDU
        logger.info("send PDU: {}", pdu);

        // write the pdu out & wait till its written
        ChannelFuture channelFuture = this.channel.writeAndFlush(buffer).await();

        // check if the write was a success
        if (!channelFuture.isSuccess()) {
            // the write failed, make sure to throw an exception
            throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
        }
    } catch (Exception e) {
        logger.error("Fatal exception thrown while attempting to send response PDU: {}", e);
    }
}

From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.OutboundWebSocketConnection.java

License:Apache License

/**
 * Open the connection to the target web socket endpoint.
 *///from ww  w. j ava  2  s .  c  o m
public void openConnection() {
    LOG.info("Connecting to web socket server at {}", targetEndpoint);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
            .handler(new WebSocketClientInitializer(monitor, connectionConfig, this));

    bootstrap.connect(targetEndpoint.getHost(), targetEndpoint.getPort())
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        connectionEstablished(future.channel());
                    } else {
                        LOG.warn("Connection to {} failed: {}", targetEndpoint, future.cause().getMessage());
                        eventGroup.schedule(new Runnable() {
                            @Override
                            public void run() {
                                openConnection();
                            }
                        }, CONNECT_RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS);
                    }
                }
            });
}

From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java

License:Apache License

private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) {
    final Channel channel = ctx.channel();

    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, false, configuration.getMaxFramePayloadLength());
    WebSocketServerHandshaker handshaker = factory.newHandshaker(req);
    if (handshaker != null) {
        ChannelFuture f = handshaker.handshake(channel, req);
        f.addListener(new ChannelFutureListener() {
            @Override/*from w w w.  jav  a  2s .com*/
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("Can't handshake " + sessionId, future.cause());
                    return;
                }

                channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT,
                        SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR,
                        new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength()));
                connectClient(channel, sessionId);
            }
        });
    } else {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    }
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

/**
 * Helper method to perform the actual connect and reconnect.
 *
 * @param observable the {@link Subject} which is eventually notified if the connect process
 *                   succeeded or failed.
 * @param bootstrapping true if connection attempt is for bootstrapping phase and therefore be less forgiving of
 *                      some errors (like socket connect timeout).
 *//*w w w . j  a va  2  s.  c  o  m*/
protected void doConnect(final Subject<LifecycleState, LifecycleState> observable,
        final boolean bootstrapping) {
    bootstrap.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (state() == LifecycleState.DISCONNECTING || state() == LifecycleState.DISCONNECTED) {
                LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Endpoint connect completed, "
                        + "but got instructed to disconnect in the meantime.");
                transitionState(LifecycleState.DISCONNECTED);
                channel = null;
            } else {
                if (future.isSuccess()) {
                    channel = future.channel();
                    LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Connected Endpoint.");
                    transitionState(LifecycleState.CONNECTED);
                } else {
                    if (future.cause() instanceof AuthenticationException) {
                        LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Authentication Failure.");
                        transitionState(LifecycleState.DISCONNECTED);
                        observable.onError(future.cause());
                    } else if (future.cause() instanceof SSLHandshakeException) {
                        LOGGER.warn(logIdent(channel, AbstractEndpoint.this)
                                + "SSL Handshake Failure during connect.");
                        transitionState(LifecycleState.DISCONNECTED);
                        observable.onError(future.cause());
                    } else if (future.cause() instanceof ClosedChannelException) {
                        LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Generic Failure.");
                        transitionState(LifecycleState.DISCONNECTED);
                        LOGGER.warn(future.cause().getMessage());
                        observable.onError(future.cause());
                    } else if (future.cause() instanceof ConnectTimeoutException) {
                        LOGGER.warn(logIdent(channel, AbstractEndpoint.this)
                                + "Socket connect took longer than specified timeout.");
                        transitionState(LifecycleState.DISCONNECTED);
                        observable.onError(future.cause());
                    } else if (isTransient) {
                        transitionState(LifecycleState.DISCONNECTED);
                        LOGGER.warn(future.cause().getMessage());
                        observable.onError(future.cause());
                    }

                    if (!disconnected && !bootstrapping && !isTransient) {
                        long delay = env.reconnectDelay().calculate(reconnectAttempt++);
                        TimeUnit delayUnit = env.reconnectDelay().unit();
                        LOGGER.warn(logIdent(channel, AbstractEndpoint.this)
                                + "Could not connect to endpoint, retrying with delay " + delay + " "
                                + delayUnit + ": ", future.cause());
                        if (responseBuffer != null) {
                            responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR,
                                    SignalConfigReload.INSTANCE, null);
                        }
                        transitionState(LifecycleState.CONNECTING);
                        future.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                // Make sure to avoid a race condition where the reconnect could override
                                // the disconnect phase. If this happens, explicitly break the retry loop
                                // and re-run the disconnect phase to make sure all is properly freed.
                                if (!disconnected) {
                                    doConnect(observable, bootstrapping);
                                } else {
                                    LOGGER.debug(
                                            "{}Explicitly breaking retry loop because already disconnected.",
                                            logIdent(channel, AbstractEndpoint.this));
                                    disconnect();
                                }
                            }
                        }, delay, delayUnit);
                    } else {
                        LOGGER.debug("{}Not retrying because already disconnected.",
                                logIdent(channel, AbstractEndpoint.this));
                    }
                }
            }
            observable.onNext(state());
            observable.onCompleted();
        }
    });
}

From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java

License:Apache License

@Override
public Observable<LifecycleState> disconnect() {
    disconnected = true;//from  w  ww  .  j  a  v a  2  s.  c o m

    if (state() == LifecycleState.DISCONNECTED || state() == LifecycleState.DISCONNECTING) {
        return Observable.just(state());
    }

    if (state() == LifecycleState.CONNECTING) {
        transitionState(LifecycleState.DISCONNECTED);
        return Observable.just(state());
    }

    transitionState(LifecycleState.DISCONNECTING);
    final AsyncSubject<LifecycleState> observable = AsyncSubject.create();
    channel.disconnect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Disconnected Endpoint.");
            } else {
                LOGGER.warn(
                        logIdent(channel, AbstractEndpoint.this) + "Received an error " + "during disconnect.",
                        future.cause());
            }
            transitionState(LifecycleState.DISCONNECTED);
            observable.onNext(state());
            observable.onCompleted();
            channel = null;
        }
    });
    return observable;
}

From source file:com.couchbase.client.core.io.endpoint.AbstractEndpoint.java

License:Open Source License

@Override
public Promise<EndpointState> connect() {
    if (state == EndpointState.CONNECTED || state == EndpointState.CONNECTING) {
        return Promises.success(state).get();
    }//from w ww.  jav a2  s .  co m

    if (state != EndpointState.RECONNECTING) {
        transitionState(EndpointState.CONNECTING);
    }

    final Deferred<EndpointState, Promise<EndpointState>> deferred = Promises.defer(env, defaultPromiseEnv);
    connectionBootstrap.connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                transitionState(EndpointState.CONNECTED);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Successfully connected Endpoint to: " + channel.remoteAddress());
                }
            } else {
                channel = null;
                transitionState(EndpointState.RECONNECTING);
                long nextReconnectDelay = nextReconnectDelay();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Could not connect to Endpoint, retrying with delay: " + nextReconnectDelay,
                            future.cause());
                }

                future.channel().eventLoop().schedule(new Runnable() {
                    @Override
                    public void run() {
                        if (shouldRetry) {
                            connect();
                        }
                    }
                }, nextReconnectDelay, TimeUnit.MILLISECONDS);
            }
            deferred.accept(state);
        }
    });
    addRetryListener();
    return deferred.compose();
}