Example usage for com.rabbitmq.client ShutdownSignalException isInitiatedByApplication

List of usage examples for com.rabbitmq.client ShutdownSignalException isInitiatedByApplication

Introduction

In this page you can find the example usage for com.rabbitmq.client ShutdownSignalException isInitiatedByApplication.

Prototype

public boolean isInitiatedByApplication() 

Source Link

Usage

From source file:mx.bigdata.utils.amqp.ReconnectingPublisher.java

License:Apache License

private boolean initPublisher() {
    try {/* w  w w  .ja v a2  s  .  c o m*/
        declaredExchanges.clear();
        String exchName = amqp.getExchangeName(key);
        if (exchName == null || amqp.getExchangeType(key) == null) {
            out = amqp.declareChannel(factory, key, false);
        } else {
            out = amqp.declareChannel(factory, key);
            declaredExchanges.add(exchName);
        }
        out.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException sig) {
                out.getConnection().abort(10000);
                if (!sig.isInitiatedByApplication()) {
                    logger.warn(tag + " ShutdownSignal for tag: " + tag + "\n\t reason: " + sig.getReason()
                            + "\n\t reference: " + sig.getReason() + "\n\t ", sig);
                    reconnect();
                } else {
                    logger.debug(tag + " ShutdownSignal for tag: " + tag + "\n\t reason: " + sig.getReason());
                    out = null;
                }
            }
        });
        logger.info("Publisher " + tag + " initialized");
        return true;
    } catch (Throwable e) {
        logger.error("Exception initializing publisher " + tag + ": ", e);
        if (out != null) {
            out.getConnection().abort(5000);
        }
    }
    return false;
}

From source file:net.joshdevins.rabbitmq.client.ha.HaUtils.java

License:Apache License

/**
 * Determines if the {@link ShutdownSignalException} can be recovered from.
 * // w w  w . j  av a  2 s.c o m
 * Straight code copy from RabbitMQ messagepatterns library v0.1.3 {@code
 * ConnectorImpl}.
 * 
 * <p>
 * Changes:
 * <ul>
 * <li>added AlreadyClosedException as recoverable when isInitiatedByApplication == true</li>
 * </ul>
 * </p>
 */
public static boolean isShutdownRecoverable(final ShutdownSignalException s) {

    if (s != null) {
        int replyCode = 0;

        if (s.getReason() instanceof AMQImpl.Connection.Close) {
            replyCode = ((AMQImpl.Connection.Close) s.getReason()).getReplyCode();
        }

        if (s.isInitiatedByApplication()) {

            return replyCode == AMQP.CONNECTION_FORCED || replyCode == AMQP.INTERNAL_ERROR
                    || s.getCause() instanceof EOFException || s instanceof AlreadyClosedException;
        }
    }

    return false;
}

From source file:net.lshift.accent.ExceptionUtils.java

License:Apache License

/**
 * Determines whether a given shutdown reason is recoverable.
 * @param s the shutdown signal to inspect.
 * @return true - the shutdown is recoverable; false - it isn't.
 *///from  w w  w  .j a  va2 s . com
public static boolean isShutdownRecoverable(ShutdownSignalException s) {
    if (s != null) {
        int replyCode = getReplyCode(s);

        return s.isInitiatedByApplication()
                && ((replyCode == AMQP.CONNECTION_FORCED) || (replyCode == AMQP.INTERNAL_ERROR)
                        || s instanceof AlreadyClosedException || (s.getCause() instanceof EOFException));
    }
    return false;
}

From source file:net.roboconf.messaging.rabbitmq.internal.impl.RoboconfConsumer.java

License:Apache License

@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {

    if (sig.isInitiatedByApplication()) {
        this.logger.fine(
                this.sourceName + ": the connection to the messaging server was shut down." + id(consumerTag));

    } else if (sig.getReference() instanceof Channel) {
        int nb = ((Channel) sig.getReference()).getChannelNumber();
        this.logger.fine("A RabbitMQ consumer was shut down. Channel #" + nb + ", " + id(consumerTag));

    } else {//from   ww w .  ja  v  a  2 s. c  om
        this.logger.fine("A RabbitMQ consumer was shut down." + id(consumerTag));
    }
}

From source file:net.roboconf.messaging.rabbitmq.internal.impl.RoboconfConsumerTest.java

License:Apache License

@Test
public void testShutdownSignal() throws Exception {

    RoboconfMessageQueue messageQueue = new RoboconfMessageQueue();
    Channel channel = Mockito.mock(Channel.class);
    RoboconfConsumer rc = new RoboconfConsumer("DM", channel, messageQueue);

    final StringHandler logHandler = new StringHandler();
    Logger logger = TestUtils.getInternalField(rc, "logger", Logger.class);
    logger.setUseParentHandlers(false);//from w  ww  .  ja v a2s . c om
    logger.setLevel(Level.FINE);
    logger.addHandler(logHandler);

    // Depending on the shutdown signal, we do not log the same message.
    ShutdownSignalException sig = Mockito.mock(ShutdownSignalException.class);
    Mockito.when(sig.isInitiatedByApplication()).thenReturn(true);
    rc.handleShutdownSignal("tag", sig);
    String log1 = logHandler.getLogs();

    // Not initiated by the application, but the source is a channel.
    Mockito.reset(sig);
    Mockito.when(sig.isInitiatedByApplication()).thenReturn(false);
    Mockito.when(sig.getReference()).thenReturn(channel);
    logHandler.getStringBuilder().setLength(0);

    rc.handleShutdownSignal("tag", sig);
    String log2 = logHandler.getLogs();

    // Not initiated by the application and the source is not a channel.
    Mockito.reset(sig);
    Mockito.when(sig.isInitiatedByApplication()).thenReturn(false);
    logHandler.getStringBuilder().setLength(0);

    rc.handleShutdownSignal("tag", sig);
    String log3 = logHandler.getLogs();

    // The 3 messages should be different
    Assert.assertFalse(Utils.isEmptyOrWhitespaces(log1));
    Assert.assertFalse(Utils.isEmptyOrWhitespaces(log2));
    Assert.assertFalse(Utils.isEmptyOrWhitespaces(log3));

    Assert.assertFalse(log1.equals(log2));
    Assert.assertFalse(log1.equals(log3));
    Assert.assertFalse(log3.equals(log2));
}

From source file:org.graylog2.inputs.transports.AmqpConsumer.java

License:Open Source License

public void connect() throws IOException {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);/*from  w ww . j  a  va  2  s  . c o m*/
    factory.setPort(port);
    factory.setVirtualHost(virtualHost);

    if (tls) {
        try {
            LOG.info("Enabling TLS for AMQP input [{}/{}].", sourceInput.getName(), sourceInput.getId());
            factory.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new IOException("Couldn't enable TLS for AMQP input.", e);
        }
    }

    // Authenticate?
    if (!isNullOrEmpty(username) && !isNullOrEmpty(password)) {
        factory.setUsername(username);
        factory.setPassword(password);
    }

    connection = factory.newConnection();
    channel = connection.createChannel();

    if (null == channel) {
        LOG.error("No channel descriptor available!");
    }

    if (null != channel && prefetchCount > 0) {
        channel.basicQos(prefetchCount);

        LOG.info("AMQP prefetch count overriden to <{}>.", prefetchCount);
    }

    connection.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            if (cause.isInitiatedByApplication()) {
                LOG.info("Not reconnecting connection, we disconnected explicitly.");
                return;
            }
            while (true) {
                try {
                    LOG.error("AMQP connection lost! Trying reconnect in 1 second.");

                    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);

                    connect();

                    LOG.info("Connected! Re-starting consumer.");

                    run();

                    LOG.info("Consumer running.");
                    break;
                } catch (IOException e) {
                    LOG.error("Could not re-connect to AMQP broker.", e);
                }
            }
        }
    });
}

From source file:org.mule.transport.amqp.AbstractAmqpITCase.java

License:Open Source License

private Channel newChannel() throws IOException {
    final Channel channel = connection.createChannel();
    channel.addShutdownListener(new ShutdownListener() {
        public void shutdownCompleted(final ShutdownSignalException sse) {
            if (!sse.isInitiatedByApplication()) {
                channelRef.set(null);//from  w ww.j a v  a  2 s .  com
            }
        }
    });
    return channel;
}

From source file:org.mule.transport.amqp.AmqpMessageReceiver.java

License:Open Source License

@Override
public void doStart() {
    try {//  www .  j a v a2s.co  m
        consumerTag = getChannel().basicConsume(getQueueName(), amqpConnector.getAckMode().isAutoAck(),
                getClientConsumerTag(), amqpConnector.isNoLocal(), amqpConnector.isExclusiveConsumers(), null,
                new DefaultConsumer(getChannel()) {
                    @Override
                    public void handleDelivery(final String consumerTag, final Envelope envelope,
                            final AMQP.BasicProperties properties, final byte[] body) throws IOException {
                        final AmqpMessage amqpMessage = new AmqpMessage(consumerTag, envelope, properties,
                                body);

                        if (logger.isDebugEnabled()) {
                            logger.debug("Received: " + amqpMessage);
                        }

                        deliverAmqpMessage(amqpMessage);
                    }

                    @Override
                    public void handleShutdownSignal(final String consumerTag,
                            final ShutdownSignalException sse) {
                        if (!sse.isInitiatedByApplication()) {
                            // inform the connector the subscription is dead
                            // so it will reconnect the receiver
                            amqpConnector.handleException(new ConnectException(
                                    MessageFactory.createStaticMessage(
                                            "Unexpected susbscription shutdown for: " + consumerTag),
                                    sse, AmqpMessageReceiver.this));
                        }
                    }
                });

        logger.info("Started subscription: " + consumerTag + " on channel: " + getChannel());
    } catch (final IOException ioe) {
        throw new MuleRuntimeException(
                MessageFactory.createStaticMessage(
                        "Error when subscribing to queue: " + getQueueName() + " on channel: " + getChannel()),
                ioe);
    }
}

From source file:org.mule.transport.amqp.internal.client.ChannelHandler.java

License:Open Source License

public Channel createChannel(ImmutableEndpoint endpoint) throws IOException {
    final AmqpConnector connector = (AmqpConnector) endpoint.getConnector();

    try {//from  w  ww. j av a  2s.  co  m
        final Channel channel = connector.getConnection().createChannel();
        channel.addReturnListener(connector.getDefaultReturnListener());
        channel.basicQos(connector.getPrefetchSize(), connector.getPrefetchCount(), false);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Created and configured new channel: " + channel);
        }

        channel.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(final ShutdownSignalException sse) {
                if (sse.isInitiatedByApplication()) {
                    return;
                }

                // do not inform the connector of the issue as it can't
                // decide what to do reset the channel so it would later
                // be lazily reconnected
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Terminated dead channel: " + channel, sse);
                }
            }
        });

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Shutdown listener configured on channel: " + channel);
        }

        return channel;
    } catch (final Exception e) {
        if ((!connector.isStopping()) && (connector.isStarted())) {
            connector.getMuleContext().getExceptionListener()
                    .handleException(new ConnectException(MessageFactory.createStaticMessage(
                            "Impossible to create new channels on connection: " + connector.getConnection()), e,
                            connector));
        }
        return null;
    }

}

From source file:org.mule.transport.amqp.internal.connector.AmqpConnector.java

License:Open Source License

protected void connectToFirstResponsiveBroker(final List<Address> brokerAddresses) throws Exception {
    Exception lastException = null;

    for (final Address brokerAddress : brokerAddresses) {
        lastException = null;/*ww  w .  j av a  2  s.c o m*/

        try {
            logger.debug("Connecting to AMQP host: " + brokerAddress.getHost() + " and port: "
                    + brokerAddress.getPort());
            connectionFactory.setHost(brokerAddress.getHost());
            connectionFactory.setPort(brokerAddress.getPort());
            connection = connectionFactory.newConnection(receiverExecutor);

            connection.addShutdownListener(new ShutdownListener() {
                public void shutdownCompleted(final ShutdownSignalException sse) {
                    if (sse.isInitiatedByApplication()) {
                        return;
                    }

                    forceReconnect("Connection shutdown detected for: " + getName(), sse);
                }
            });
            logger.info("Connected to AMQP host: " + brokerAddress.getHost() + " and port: "
                    + brokerAddress.getPort());
            break;
        } catch (final Exception e) {
            logger.error("Error occurred when connecting to AMQP host: " + brokerAddress.getHost()
                    + " and port: " + brokerAddress.getPort(), e);
            lastException = e;
        }
    }

    if (lastException != null) {
        throw lastException;
    }
}