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.opendaylight.sxp.core.SxpNode.java

License:Open Source License

/**
 * Start SxpNode/* ww  w .ja v a 2 s.c o  m*/
 */
public synchronized SxpNode start() {
    channelInitializationWait("Error while starting");
    if (isEnabled()) {
        return this;
    }
    this.sourceIp = InetAddresses.forString(Search.getAddress(getNodeIdentity().getSourceIp()));
    final SxpNode node = this;
    try {
        ConnectFacade.createServer(node, handlerFactoryServer).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    serverChannel = channelFuture.channel();
                    LOG.info(node + " Server created [" + getSourceIp().getHostAddress() + ":" + getServerPort()
                            + "]");
                    node.setTimer(TimerType.RetryOpenTimer, node.getRetryOpenTime());
                } else {
                    LOG.error(node + " Server [" + node.getSourceIp().getHostAddress() + ":" + getServerPort()
                            + "] Could not be created " + channelFuture.cause());
                }
                serverChannelInit.set(false);
            }
        }).syncUninterruptibly();
    } catch (Exception e) {
        LOG.debug("Failed to bind SxpNode {} to ip", this, e);
    }
    return this;
}

From source file:org.openremote.agent.protocol.AbstractNettyMessageProcessor.java

License:Open Source License

@Override
public synchronized void connect() {
    if (connectionStatus != ConnectionStatus.DISCONNECTED && connectionStatus != ConnectionStatus.WAITING) {
        LOG.finest("Must be disconnected before calling connect");
        return;/*from ww w  .ja v a  2  s. co m*/
    }

    LOG.fine("Connecting");
    onConnectionStatusChanged(ConnectionStatus.CONNECTING);

    if (workerGroup == null) {
        // TODO: In Netty 5 you can pass in an executor service; can only pass in thread factory for now
        workerGroup = getWorkerGroup();
    }

    bootstrap = new Bootstrap();
    bootstrap.channel(getChannelClass());
    configureChannel();
    bootstrap.group(workerGroup);

    bootstrap.handler(new ChannelInitializer() {
        @Override
        public void initChannel(Channel channel) {
            AbstractNettyMessageProcessor.this.initChannel(channel);
        }
    });

    // Start the client and store the channel
    socketAddress = getSocketAddress();
    channelFuture = bootstrap.connect(socketAddress);
    channel = channelFuture.channel();

    // Add channel callback - this gets called when the channel connects or when channel encounters an error
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            synchronized (AbstractNettyMessageProcessor.this) {
                channelFuture.removeListener(this);

                if (connectionStatus == ConnectionStatus.DISCONNECTING) {
                    return;
                }

                if (future.isSuccess()) {
                    LOG.log(Level.INFO, "Connection initialising");
                    reconnectTask = null;
                    reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
                } else if (future.cause() != null) {
                    LOG.log(Level.INFO, "Connection error", future.cause());
                    // Failed to connect so schedule reconnection attempt
                    scheduleReconnect();
                }
            }
        }
    });

    // Add closed callback
    channel.closeFuture().addListener(future -> {
        if (connectionStatus != ConnectionStatus.DISCONNECTING) {
            scheduleReconnect();
        }
    });
}

From source file:org.ow2.petals.bc.gateway.commons.AbstractDomain.java

License:Open Source License

private void sendToChannel(final ChannelHandlerContext ctx, final TransportedForExchange m) {

    if (m instanceof TransportedMessage) {
        final TransportedMessage tm = (TransportedMessage) m;
        logBeforeSendingToChannel(tm);//from w  ww.  ja v a 2 s.  c  o m
        m.senderExtStep = PetalsExecutionContext.getFlowAttributes();
    }

    ctx.writeAndFlush(m).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final @Nullable ChannelFuture future) throws Exception {
            assert future != null;
            // TODO add tests for these use cases!
            if (!future.isSuccess()) {
                // TODO introduce some basic retrying before cancelling the send
                // Careful because if we reconnect, I guess the channel is not the same one?!?!
                final Throwable cause = future.cause();
                // TODO is the channel notified of the error too?
                // see https://groups.google.com/d/msg/netty/yWMRRS6zaQ0/2MYNvRZQAQAJ
                if (m instanceof TransportedMessage && !((TransportedMessage) m).last) {
                    final TransportedMessage tm = (TransportedMessage) m;
                    tm.exchange.setError(new MessagingException(cause));
                    // TODO what about the other side waiting for this exchange?! it should be removed there... but
                    // if there is a connection problem, then maybe it is simply that it was stopped?
                    // we could take note of which exchangeId failed and send them on reconnect for cleaning?
                    logger.log(Level.WARNING,
                            "Can't send message over the channel, sending back the error over the NMR: " + m,
                            cause);
                    // TODO we have to wrap the modification in a transported message even though it hasn't been
                    // so there may be extra useless operations... improve that!
                    receiveFromChannel(ctx, TransportedMessage.lastMessage(tm, tm.exchange));
                } else {
                    logger.log(Level.WARNING,
                            "Can't send message over the channel but nothing I can do now: " + m, cause);
                }
            }
        }
    });
}

From source file:org.ow2.petals.bc.gateway.inbound.TransportListener.java

License:Open Source License

/**
 * Start listening/*from   www .j a v a 2  s .c  o m*/
 */
public void bind() {
    bootstrap.localAddress(jtl.getPort()).bind().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final @Nullable ChannelFuture future) throws Exception {
            assert future != null;
            if (!future.isSuccess()) {
                logger.log(Level.SEVERE, "Cannot bind transport listener " + jtl.getId()
                        + ": fix the problem and, either stop/start the component or use the JMX API to (re-)set the port",
                        future.cause());
                lastBindingError = future.cause().getMessage();
            } else {
                channel = future.channel();
                lastBindingError = "";
            }
        }
    });
}

From source file:org.ow2.petals.bc.gateway.outbound.TransportClient.java

License:Open Source License

private void doConnect() {
    final String ip = pd.getJPD().getRemoteIp();
    // it should have been checked already at deploy
    final int port = Integer.parseInt(pd.getJPD().getRemotePort());

    logger.info("Connecting to " + pd.getJPD().getId() + " (" + ip + ":" + port + ")"
            + (retries > 0 ? ", retry " + retries + " of " + pd.getJPD().getRetryMax() : ""));

    // it will be set by the channel initializer during connect!
    authenticationFuture = null;/*  w  ww. j  ava  2  s  .  c om*/
    connectOrNext = bootstrap.remoteAddress(ip, port).connect().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final @Nullable ChannelFuture future) throws Exception {
            assert future != null;
            final Channel ch = future.channel();
            assert ch != null;
            if (!future.isSuccess()) {
                // here the connect itself failed, the cause will most certainly be non-null
                setupReconnectIfNeeded(ch, future.cause(), false);
            } else {
                // here the connect succeeded, but maybe the authentication will fail
                assert authenticationFuture != null;
                authenticationFuture.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final @Nullable Future<Channel> future) throws Exception {
                        assert future != null;
                        if (future.isSuccess()) {
                            // we set it only once we are sure everything went well
                            channel = ch;
                            // now we can setup reconnect for close
                            ch.closeFuture().addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(final @Nullable ChannelFuture future)
                                        throws Exception {
                                    assert future != null;
                                    // here the channel was closed, the cause will most certainly be null
                                    setupReconnectIfNeeded(ch, future.cause(), true);
                                }
                            });
                        } else {
                            // in that case, authentication failed, the cause will most certainly be non-null
                            setupReconnectIfNeeded(ch, future.cause(), false);
                        }
                    }
                });
            }
        }
    });
}

From source file:org.quartzpowered.network.client.NetworkClient.java

License:Open Source License

public ChannelFuture connect(InetSocketAddress address) {
    ChannelFuture future = bootstrap.connect(address);
    return future.addListener(ignored -> {
        channel = future.channel();/*  w  ww .  ja v a 2s .co m*/
        session = sessionManager.get(channel);

        if (future.isSuccess()) {
            onConnectSuccess(address);
        } else {
            onConnectFailure(address, future.cause());
        }
    });
}

From source file:org.redisson.client.RedisClient.java

License:Apache License

public RFuture<RedisConnection> connectAsync() {
    final RPromise<RedisConnection> f = new RedissonPromise<RedisConnection>();
    ChannelFuture channelFuture = bootstrap.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override//ww w  . j a  v a 2 s .  co m
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                final RedisConnection c = new RedisConnection(RedisClient.this, future.channel());
                bootstrap.group().execute(new Runnable() {
                    public void run() {
                        if (!f.trySuccess(c)) {
                            c.closeAsync();
                        }
                    }
                });
            } else {
                bootstrap.group().execute(new Runnable() {
                    public void run() {
                        f.tryFailure(future.cause());
                    }
                });
            }
        }
    });
    return f;
}

From source file:org.redisson.client.RedisClient.java

License:Apache License

public RFuture<RedisPubSubConnection> connectPubSubAsync() {
    final RPromise<RedisPubSubConnection> f = new RedissonPromise<RedisPubSubConnection>();
    ChannelFuture channelFuture = bootstrap.connect();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override//from   w w  w  . ja  v a2 s.  co m
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                final RedisPubSubConnection c = new RedisPubSubConnection(RedisClient.this, future.channel());
                bootstrap.group().execute(new Runnable() {
                    public void run() {
                        if (!f.trySuccess(c)) {
                            c.closeAsync();
                        }
                    }
                });
            } else {
                bootstrap.group().execute(new Runnable() {
                    public void run() {
                        f.tryFailure(future.cause());
                    }
                });
            }
        }
    });
    return f;
}

From source file:org.redisson.command.CommandAsyncService.java

License:Apache License

private <V, R> void checkWriteFuture(final AsyncDetails<V, R> details, final RedisConnection connection) {
    ChannelFuture future = details.getWriteFuture();
    if (details.getAttemptPromise().isDone() || future.isCancelled()) {
        return;/*from w ww  .j  a v  a 2  s .  co  m*/
    }

    if (!future.isSuccess()) {
        details.setException(new WriteRedisConnectionException(
                "Can't write command: " + details.getCommand() + ", params: "
                        + LogHelper.toString(details.getParams()) + " to channel: " + future.channel(),
                future.cause()));
        return;
    }

    details.getTimeout().cancel();

    long timeoutTime = connectionManager.getConfig().getTimeout();
    if (RedisCommands.BLOCKING_COMMANDS.contains(details.getCommand().getName())) {
        Long popTimeout = Long.valueOf(details.getParams()[details.getParams().length - 1].toString());
        handleBlockingOperations(details, connection, popTimeout);
        if (popTimeout == 0) {
            return;
        }
        timeoutTime += popTimeout * 1000;
        // add 1 second due to issue https://github.com/antirez/redis/issues/874
        timeoutTime += 1000;
    }

    final long timeoutAmount = timeoutTime;
    TimerTask timeoutTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            details.getAttemptPromise().tryFailure(new RedisTimeoutException("Redis server response timeout ("
                    + timeoutAmount + " ms) occured for command: " + details.getCommand() + " with params: "
                    + LogHelper.toString(details.getParams()) + " channel: " + connection.getChannel()));
        }
    };

    Timeout timeout = connectionManager.newTimeout(timeoutTask, timeoutTime, TimeUnit.MILLISECONDS);
    details.setTimeout(timeout);
}

From source file:org.redisson.command.CommandBatchService.java

License:Apache License

private void checkWriteFuture(final RPromise<Void> attemptPromise, AsyncDetails details,
        final RedisConnection connection, ChannelFuture future, boolean noResult) {
    if (attemptPromise.isDone() || future.isCancelled()) {
        return;//ww  w  .  j  a v a2s . c  o  m
    }

    if (!future.isSuccess()) {
        details.setException(new WriteRedisConnectionException(
                "Can't write command batch to channel: " + future.channel(), future.cause()));
    } else {
        details.getTimeout().cancel();
        TimerTask timeoutTask = new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                attemptPromise.tryFailure(new RedisTimeoutException(
                        "Redis server response timeout during command batch execution. Channel: "
                                + connection.getChannel()));
            }
        };
        Timeout timeout = connectionManager.newTimeout(timeoutTask, connectionManager.getConfig().getTimeout(),
                TimeUnit.MILLISECONDS);
        details.setTimeout(timeout);
    }
}