Example usage for com.rabbitmq.client ShutdownSignalException getReference

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

Introduction

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

Prototype

public Object getReference() 

Source Link

Usage

From source file:com.googlesource.gerrit.plugins.rabbitmq.AMQPSession.java

License:Apache License

@Override
public void shutdownCompleted(ShutdownSignalException exception) {
    Object obj = exception.getReference();

    if (obj instanceof Channel) {
        Channel ch = (Channel) obj;
        if (ch.equals(publishChannel)) {
            LOGGER.info("Publish channel closed.");
            publishChannel = null;//from   ww w . jav  a 2s. co  m
        } else if (ch.equals(consumeChannel)) {
            LOGGER.info("Consume channel closed.");
            consumeChannel = null;
        }
    } else if (obj instanceof Connection) {
        LOGGER.info("Connection disconnected.");
        connection = null;
    }
}

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

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//  w  w w  . j a  va 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.  java 2  s  . c om*/
 */
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: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.  j  a v a  2s  .  co  m*/
        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);/* www.  j a v a 2  s .  c  o m*/
    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.teksme.server.common.messaging.AMQPBrokerManager.java

License:Apache License

public void shutdownCompleted(ShutdownSignalException sse) {

    Connection conn = (Connection) sse.getReference();
    Command closeCommand = (Command) sse.getReason();
    if (sse.isHardError()) {
        if (!sse.isInitiatedByApplication()) {
            AMQP.Connection.Close closeMethod = (AMQP.Connection.Close) closeCommand.getMethod();
            logger.log(Level.SEVERE, "Connection host [" + conn.getHost() + "] closed. Shutdown reason: "
                    + closeMethod.getReplyCode());
        }// w w  w  . j  a  v a  2s.  c  om
    } else {
        Channel ch = (Channel) sse.getReference();
        logger.info("Connection host [" + conn.getHost() + "] closed. Shutdown reason: " + ch.getCloseReason());
    }

    logger.info("RabbitMQ AMQP broker shutdown completed!");

}

From source file:uk.trainwatch.rabbitmq.RabbitRPCClient.java

License:Apache License

private byte[] primitiveCall(AMQP.BasicProperties props, byte[] message)
        throws IOException, ShutdownSignalException, TimeoutException {
    checkConsumer();//  w  w w .  j av  a2  s .  c o  m
    BlockingCell<Object> k = new BlockingCell<>();

    String replyId = RabbitMQ.newCorrelationId();
    props = ((props == null) ? new AMQP.BasicProperties.Builder() : props.builder()).correlationId(replyId)
            .replyTo(replyQueue).build();
    continuationMap.put(replyId, k);

    publish(props, message);

    Object reply = k.uninterruptibleGet(timeout);
    if (reply instanceof ShutdownSignalException) {
        ShutdownSignalException sig = (ShutdownSignalException) reply;
        ShutdownSignalException wrapper = new ShutdownSignalException(sig.isHardError(),
                sig.isInitiatedByApplication(), sig.getReason(), sig.getReference());
        wrapper.initCause(sig);
        throw wrapper;
    } else {
        return (byte[]) reply;
    }
}