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:amqp.AmqpConsumer.java

License:Apache License

/**
 * Will log the specified exception and will set the {@link #exception} field if the
 * {@link com.rabbitmq.client.ShutdownSignalException#isInitiatedByApplication()} is false meaning
 * that the shutdown wasn't client initiated.
 *
 * @param e exception// w  ww  . j av  a  2s.c o  m
 */
private void logShutdownSignalException(ShutdownSignalException e) {
    if (e.isInitiatedByApplication()) {
        LOG.info("Consumer Thread caught ShutdownSignalException, shutting down...");
    } else {
        LOG.error("Unexpected ShutdownSignalException caught in Consumer Thread , shutting down...", e);
        this.exception = e;
    }
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to publish the message to RabbitMQ
 * @param routingKey/*from w w  w .j  a va 2  s .c  o m*/
 * @param msg is Eiffel Event
 * @throws IOException
 */
public void send(String routingKey, String msg) throws IOException {

    Channel channel = giveMeRandomChannel();
    channel.addShutdownListener(new ShutdownListener() {
        public void shutdownCompleted(ShutdownSignalException cause) {
            // Beware that proper synchronization is needed here
            if (cause.isInitiatedByApplication()) {
                log.debug("Shutdown is initiated by application. Ignoring it.");
            } else {
                log.error("Shutdown is NOT initiated by application.");
                log.error(cause.getMessage());
                boolean cliMode = Boolean.getBoolean(PropertiesConfig.CLI_MODE);
                if (cliMode) {
                    System.exit(-3);
                }
            }
        }
    });

    BasicProperties msgProps = MessageProperties.BASIC;
    if (usePersitance)
        msgProps = MessageProperties.PERSISTENT_BASIC;

    channel.basicPublish(exchangeName, routingKey, msgProps, msg.getBytes());
    log.info("Published message with size {} bytes on exchange '{}' with routing key '{}'",
            msg.getBytes().length, exchangeName, routingKey);
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception// w w  w .  jav a  2  s  .  c o m
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from   w w w  .j  av a2 s.  co  m
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.sitewhere.sources.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

private void connect() {

    try {/*from   w w w .  ja  va 2  s .c o m*/

        this.connection = factory.newConnection(executors);

        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
                LOGGER.info("shutdown signal received", cause);

                // Do nothing if SiteWhere initiated the connection close
                if (!cause.isInitiatedByApplication()) {
                    connection = null;
                    scheduleReconnect();
                }
            }
        });

        this.channel = connection.createChannel();

        LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri());

        channel.queueDeclare(getQueueName(), isDurable(), false, false, null);

        LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName());

        // Add consumer callback for channel.
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                onEventPayloadReceived(body, null);
            }
        };

        channel.basicConsume(getQueueName(), true, consumer);

    } catch (Exception e) {
        LOGGER.error("Connection Error", e);
        connection = null;
        scheduleReconnect();
    }

}

From source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQConnection.java

License:Open Source License

@Override
public void shutdownCompleted(ShutdownSignalException cause) {
    if (cause.isHardError()) {
        if (!cause.isInitiatedByApplication()) {
            LOGGER.warn("MQ connection was suddenly disconnected.");
            try {
                if (connection != null && connection.isOpen()) {
                    connection.close();//from  ww  w.j av  a 2s  .  c  o m
                }
                if (channel != null && channel.isOpen()) {
                    channel.close();
                }
            } catch (IOException e) {
                LOGGER.error("IOException: ", e);
            } catch (AlreadyClosedException e) {
                LOGGER.error("AlreadyClosedException: ", e);
            } finally {
                channel = null;
                connection = null;
            }
        }
    } else {
        LOGGER.warn("MQ channel was suddenly disconnected.");
    }
}

From source file:io.qdb.server.input.RabbitMQInputHandler.java

License:Apache License

@Override
public synchronized void shutdownCompleted(ShutdownSignalException cause) {
    channel = null;//from  w w  w  . ja va 2 s  .c  om
    if (!cause.isInitiatedByApplication()) {
        try {
            if (con.isOpen())
                con.close();
        } catch (Exception ignore) {
        }
        con = null;
        sink.error("Channel closed unexpectedly: " + cause.getMessage(), null);
    }
}

From source file:io.qdb.server.output.RabbitMQOutputHandler.java

License:Apache License

@Override
public synchronized void shutdownCompleted(ShutdownSignalException cause) {
    channel = null;//w ww .j av  a2  s  .  c o  m
    if (!cause.isInitiatedByApplication()) {
        log.error(outputPath + ": Channel closed unexpectedly: " + cause.getMessage());
        try {
            if (con.isOpen())
                con.close();
        } catch (Exception ignore) {
        }
        con = null;
    }
}

From source file:mobisocial.musubi.service.AMQPService.java

License:Apache License

void initiateConnection() {
    if (mConnection != null) {
        //just for information sake, this is a legitimate event
        Log.i(TAG, "Already connected when triggered to initiate connection");
        return;//from ww w  . ja v a 2s.  c om
    }
    Log.i(TAG, "Network is up connection is being attempted");
    try {
        mConnection = mConnectionFactory.newConnection();
        mConnection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                if (!cause.isInitiatedByApplication()) {
                    //start the connection
                    mAMQPHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            closeConnection(FailedOperationType.FailedConnect);
                        }
                    });
                }
            }
        });

        mDeclaredGroups = new HashSet<String>();
        mMessageWaitingForAck = new TLongHashSet();
        mMessageWaitingForAckByTag = new TLongLongHashMap();

        mIncomingChannel = mConnection.createChannel();
        mIncomingChannel.basicQos(10);
        attachToQueues();

        mOutgoingChannel = mConnection.createChannel();
        //TODO: these callbacks run in another thread, so this is not correct
        //we need some synchronized or a customized ExecutorService that
        //posts to the handler (though, that may not be possible if they demand
        //n threads to run on
        mOutgoingChannel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                //don't immediately try to resend, just flag it, it will be rescanned later
                //this probably only happens if the server is temporarily out of space
                long encoded_id = mMessageWaitingForAckByTag.get(deliveryTag);
                mMessageWaitingForAckByTag.remove(deliveryTag);
                mMessageWaitingForAck.remove(encoded_id);
            }

            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                //delivered!
                long encoded_id = mMessageWaitingForAckByTag.get(deliveryTag);

                //mark the db entry as processed
                MEncodedMessage encoded = mEncodedMessageManager.lookupMetadataById(encoded_id);
                assert (encoded.outbound_);
                encoded.processed_ = true;
                encoded.processedTime_ = new Date().getTime();
                mEncodedMessageManager.updateEncodedMetadata(encoded);

                mMessageWaitingForAckByTag.remove(deliveryTag);
                mMessageWaitingForAck.remove(encoded_id);

                long feedId = mEncodedMessageManager.getFeedIdForEncoded(encoded_id);
                if (feedId != -1) {
                    Uri feedUri = MusubiContentProvider.uriForItem(Provided.FEEDS_ID, feedId);
                    getContentResolver().notifyChange(feedUri, null);
                }
            }
        });
        mOutgoingChannel.confirmSelect();
        mConnectionReady = true;

        //once we have successfully done our work, we can
        //reset the failure delay, FYI, internal exceptions in the
        //message sender will cause backoff to MAX_DELAY
        if (mFailedOperation == FailedOperationType.FailedConnect) {
            mFailureDelay = MIN_DELAY;
            mFailedOperation = FailedOperationType.FailedNone;
        }
    } catch (Throwable e) {
        closeConnection(FailedOperationType.FailedConnect);
        Log.e(TAG, "Failed to connect to AMQP", e);
    }
    //slight downside here is that if publish a message causes the fault,
    //then we will always reconnect and disconnect
    sendMessages();
}

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

License:Apache License

private boolean initConsumer() {
    Channel channel = null;/*from   www.j av a  2 s  .  c o m*/
    try {
        channel = amqp.declareChannel(factory, key);
        String queue = createQueue(amqp, channel, key);
        this.consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                ReconnectingConsumer.this.handleDelivery(consumerTag, envelope, properties, body);
            }

            @Override
            public void handleConsumeOk(String consumerTag) {
                ReconnectingConsumer.this.consumerTag = consumerTag;
            }

            @Override
            public void handleCancel(String consumerTag) throws IOException {
                logger.warn(tag + " handleCancel for consumer tag: " + consumerTag);
                try {
                    this.getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                }
                this.getChannel().getConnection().abort(5000);
                reconnect();
            }

            @Override
            public void handleShutdownSignal(java.lang.String consumerTag, ShutdownSignalException sig) {
                try {
                    getChannel().basicCancel(ReconnectingConsumer.this.consumerTag);
                } catch (Exception ignore) {
                    ;
                }
                getChannel().getConnection().abort(5000);
                if (!sig.isInitiatedByApplication()) {
                    logger.warn(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    reconnect();
                } else {
                    logger.debug(tag + " ShutdownSignal for tag: " + tag + "\n\t consumer tag: " + consumerTag
                            + "\n\t reason: " + sig.getReason() + "\n\t reference: " + sig.getReason()
                            + "\n\t ", sig);
                    consumer = null;
                }
            }
        };

        channel.basicConsume(queue, false, consumer);
        logger.info("Consumer " + tag + " initilized");
        return true;
    } catch (Throwable e) {
        logger.error("Exception initializing consumer " + tag + ": ", e);
        if (channel != null) {
            channel.getConnection().abort(5000);
        }
    }
    return false;
}