Example usage for com.rabbitmq.client ShutdownSignalException ShutdownSignalException

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

Introduction

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

Prototype

public ShutdownSignalException(boolean hardError, boolean initiatedByApplication, Method reason, Object ref) 

Source Link

Document

Construct a ShutdownSignalException from the arguments.

Usage

From source file:de.htwk_leipzig.bis.connection.handshake.clientRewrite.Copyright.java

License:Mozilla Public License

private ShutdownSignalException startShutdown(Method reason, boolean initiatedByApplication, Throwable cause,
        boolean notifyRpc) {
    ShutdownSignalException sse = new ShutdownSignalException(true, initiatedByApplication, reason, this);
    sse.initCause(cause);//  w ww  . j  a v a  2s . c o  m
    if (!setShutdownCauseIfOpen(sse)) {
        if (initiatedByApplication)
            throw new AlreadyClosedException(getCloseReason(), cause);
    }

    // stop any heartbeating
    _heartbeatSender.shutdown();

    _channel0.processShutdownSignal(sse, !initiatedByApplication, notifyRpc);

    return sse;
}

From source file:de.htwk_leipzig.bis.connection.handshake.clientRewrite.Copyright.java

License:Mozilla Public License

/**
 * Protected API - Close this connection with the given code, message,
 * source and timeout value for all the close operations to complete.
 * Specifies if any encountered exceptions should be ignored.
 *//*from   w  ww. j  ava 2  s  .  c om*/
public void close(int closeCode, String closeMessage, boolean initiatedByApplication, Throwable cause,
        int timeout, boolean abort) throws IOException {
    boolean sync = !(Thread.currentThread() == mainLoopThread);

    try {
        AMQP.Connection.Close reason = new AMQP.Connection.Close.Builder().replyCode(closeCode)
                .replyText(closeMessage).build();

        final ShutdownSignalException sse = startShutdown(reason, initiatedByApplication, cause, true);
        if (sync) {

            /*
             * Do custom action
             */
            mHandshakeAction.doAction();

            BlockingRpcContinuation<AMQCommand> k = new BlockingRpcContinuation<AMQCommand>() {

                @Override
                public AMQCommand transformReply(AMQCommand command) {
                    AMQConnection.this.finishShutdown(sse);
                    return command;
                }
            };

            _channel0.quiescingRpc(reason, k);

            /*
             * Do custom action
             */
            mHandshakeAction.doAction();

            k.getReply(timeout);

        } else {
            _channel0.quiescingTransmit(reason);
        }
    } catch (TimeoutException tte) {
        if (!abort) {
            ShutdownSignalException sse = new ShutdownSignalException(true, true, null, this);
            sse.initCause(cause);
            throw sse;
        }
    } catch (ShutdownSignalException sse) {
        if (!abort)
            throw sse;
    } catch (IOException ioe) {
        if (!abort)
            throw ioe;
    } finally {
        if (sync)
            _frameHandler.close();
    }
}

From source file:dk.au.cs.karibu.integration.TestMessageReceiverEndpoint.java

License:Apache License

/** Test the receiver end point in case connection problems occur. */
@Test//from w ww  .  java  2s .  co m
public void shouldTestFailoverWhenMQFails() throws InterruptedException, IOException {
    receiverThread.start();

    // this should succeed 
    crh.send(p1, EXAMPLE_TOPIC);

    // wait for the threads to settle (so the consumer thread has pulled 
    // the message from the queue). 
    Thread.sleep(100);

    // Validate that the consumer has indeed looked up the deserializer 
    assertEquals("INFO:Caching the deserializer (GameFavoriteDeserializer)", spyLogger.getLastLog());

    // Validate that the storage has stored the item 
    BasicDBObject dbo = storage.getCollectionNamed(PRODUCER_CODE).get(0);
    assertNotNull(dbo);

    // tell the polling consumer to throw an exception on the next call to a fecth from the queue.
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));

    // this should succeed but the log must show a reconnect was initiated 
    crh.send(p2, EXAMPLE_TOPIC);

    Thread.sleep(100);

    // dumpFullLog();

    // assert that a reconnect was made 
    assertEquals("INFO:MQ shutdown signal, will backoff for 2ms and retry (Retry #1)", spyLogger.getLastLog(2));
    assertEquals("INFO:OpenChannel called/Count = 1", spyLogger.getLastLog());

    dbo = storage.getCollectionNamed(PRODUCER_CODE).get(1);
    assertNotNull(dbo);
    assertEquals("Mathilde", dbo.getString("name"));

    // dumpFullLog();

    pollingConsumer.closeChannel();
    assertEquals(0, pollingConsumer.getOpenCloseCount());
}

From source file:dk.au.cs.karibu.integration.TestMessageReceiverEndpoint.java

License:Apache License

/** Test exponential backup in case of MQ failure. */
@Test//from   www.j a  va  2  s . co  m
public void shouldTestExpBackoffWhenMQFails() throws InterruptedException, IOException {
    receiverThread.start();
    // 'warm up' the receiver so the deserializer has been cached.
    crh.send(p2, EXAMPLE_TOPIC);
    Thread.sleep(100);

    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));

    // this should succeed, but the log must contain the full log exponential backup 
    crh.send(p1, EXAMPLE_TOPIC);
    Thread.sleep(100);

    //dumpFullLog();

    // Assert that the object was stored (as item #1, #0 is Mathilde)
    BasicDBObject dbo = storage.getCollectionNamed(PRODUCER_CODE).get(1);
    assertNotNull(dbo);
    assertEquals("Henrik", dbo.getString("name"));

    // Assert from the log that exponential backup was made during the reconnect tries
    assertEquals("INFO:MQ shutdown signal, will backoff for 2ms and retry (Retry #1)", spyLogger.getLastLog(4));
    assertEquals("INFO:MQ shutdown signal, will backoff for 4ms and retry (Retry #2)", spyLogger.getLastLog(2));
    assertEquals("INFO:OpenChannel called/Count = 1", spyLogger.getLastLog());

    // Next, ensure that the exp backoff counter is reset after a successful send, AND the
    // dublication of timing

    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));

    // this should succeed, but the log must contain the full log exponential backup 
    crh.send(p1, EXAMPLE_TOPIC);
    Thread.sleep(100);

    // Assert from the log that exponential backup was made during the five reconnect tries
    assertEquals("INFO:MQ shutdown signal, will backoff for 8ms and retry (Retry #3)", spyLogger.getLastLog(2));
    assertEquals("INFO:OpenChannel called/Count = 1", spyLogger.getLastLog());

    //dumpFullLog();
}

From source file:dk.au.cs.karibu.integration.TestMessageReceiverEndpoint.java

License:Apache License

@Test
public void shouldTestExpBackoffCapingAfter10RetriesWhenMQFails() throws InterruptedException, IOException {
    receiverThread.start();/*w w  w.  j  a v  a2s.c  o m*/
    // 'warm up' the receiver so the deserializer has been cached.
    crh.send(p2, EXAMPLE_TOPIC);
    Thread.sleep(100);

    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));
    pollingConsumer.pushExceptionToBeThrownNext(new ShutdownSignalException(false, true, null, null));

    crh.send(p1, EXAMPLE_TOPIC);
    Thread.sleep(4500);

    // dumpFullLog();

    // Assert from the log that the exp backoff stops after 10 retries.
    assertEquals("INFO:MQ shutdown signal, will backoff for 1024ms and retry (Retry #10)",
            spyLogger.getLastLog(4));
    assertEquals("INFO:MQ shutdown signal, will backoff for 1024ms and retry (Retry #11)",
            spyLogger.getLastLog(2));
}

From source file:dk.au.cs.karibu.integration.TestProducerFailover.java

License:Apache License

@Before
public void setup() throws IOException {
    // create a spy into the logging so we can validate what goes on 
    // in the client request handler 
    spyLogger = new SpyLogger();

    // create the depended-on objects in fake object implementations 
    // for the server side to allow inspection. 
    storage = new FakeObjectStorage();
    DeserializerFactory factory = new DeserializerFactory() {
        @Override/*from   w  w  w  . jav a2  s.co  m*/
        public Deserializer createDeserializer(String producerCode) {
            return new GameFavoriteDeserializer();
        }
    };
    srh = new StandardServerRequestHandler(storage, factory);
    asStubConnector = new InVMInterProcessConnector(srh);
    connector = asStubConnector;

    crh = new StandardClientRequestHandler<GameFavorite>(PRODUCER_CODE, connector, new GameFavoriteSerializer(),
            0, 5, spyLogger);

    p1 = new GameFavorite("Henrik", "SCII");
    p2 = new GameFavorite("Bimse", "Bimses julerejse");

    sse = new ShutdownSignalException(false, true, null, null);
}

From source file:dk.au.cs.karibu.integration.TestProducerFailover.java

License:Apache License

@Test
public void shouldResendWhenMultipleAlreadyClosedExcpetionsOccurs() throws IOException {
    // Assert multiple exceptions are handled, by pushing the last exception first (stack behaviour) 
    ShutdownSignalException sse1 = new ShutdownSignalException(false, true, null, null);
    ShutdownSignalException sse2 = new ShutdownSignalException(false, true, null, null);

    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse1));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse2));
    crh.send(p1, EXAMPLE_TOPIC);/*ww  w .  j  a  v a 2  s .  co m*/
    assertEquals(
            "INFO:AlreadyClosedException/retry=2/Msg=channel is already closed due to clean channel shutdown",
            spyLogger.getLastLog());
    // and verify that the message indeed got through 
    assertEquals("Henrik", storage.getCollectionNamed(PRODUCER_CODE).get(0).getString("name"));

}

From source file:org.smartdeveloperhub.curator.connector.BrokerControllerTest.java

License:Apache License

@Test
public void testPublishMessage$unexpectedFailure() throws Exception {
    final BrokerController sut = newInstance();
    final DeliveryChannel dc = ProtocolFactory.newDeliveryChannel().withExchangeName("exchangeName")
            .withRoutingKey("routingKey").build();
    final String message = "message";
    new MockUp<ConnectionFactory>() {
        @Mock/* w  w w .  j  av a  2 s .  co m*/
        public void setHost(final String host) {
        }

        @Mock
        public void setPort(final int port) {
        }

        @Mock
        public void setVirtualHost(final String virtualHost) {
        }

        @Mock
        public void setThreadFactory(final ThreadFactory threadFactory) {
        }

        @Mock
        public Connection newConnection() throws IOException, TimeoutException {
            return BrokerControllerTest.this.connection;
        }
    };
    new Expectations() {
        {
            BrokerControllerTest.this.connection.createChannel();
            this.result = BrokerControllerTest.this.channel;
            BrokerControllerTest.this.channel.basicPublish(dc.exchangeName(), dc.routingKey(), true,
                    (BasicProperties) this.any, message.getBytes());
            this.result = new ShutdownSignalException(true, true, null, BrokerControllerTest.this.channel);
        }
    };
    sut.connect();
    try {
        sut.publishMessage(dc, message);
    } catch (final IOException e) {
        assertThat(e.getMessage(), equalTo(
                "Unexpected failure while publishing message [message] to exchange 'exchangeName' and routing key 'routingKey' using broker localhost:5672/: clean connection shutdown"));
        assertThat(e.getCause(), instanceOf(ShutdownSignalException.class));
    }
    new Verifications() {
        {
            BasicProperties s;
            BrokerControllerTest.this.channel.basicPublish(dc.exchangeName(), dc.routingKey(), true,
                    s = withCapture(), message.getBytes());
            assertThat(s.getDeliveryMode(), equalTo(2));
            assertThat(s.getHeaders().get(BrokerController.BROKER_CONTROLLER_MESSAGE), instanceOf(Long.class));
        }
    };
}

From source file:org.springframework.amqp.rabbit.transaction.RabbitExceptionTranslatorTests.java

License:Apache License

@Test
public void testConvertRabbitAccessException() {

    assertThat(//w w  w .j  av a2 s.  c  o m
            RabbitExceptionTranslator.convertRabbitAccessException(
                    new PossibleAuthenticationFailureException(new RuntimeException())),
            instanceOf(AmqpAuthenticationException.class));

    assertThat(RabbitExceptionTranslator.convertRabbitAccessException(new AmqpException("")),
            instanceOf(AmqpException.class));

    assertThat(
            RabbitExceptionTranslator
                    .convertRabbitAccessException(new ShutdownSignalException(false, false, null, null)),
            instanceOf(AmqpConnectException.class));

    assertThat(RabbitExceptionTranslator.convertRabbitAccessException(new ConnectException()),
            instanceOf(AmqpConnectException.class));

    assertThat(RabbitExceptionTranslator.convertRabbitAccessException(new IOException()),
            instanceOf(AmqpIOException.class));

    assertThat(RabbitExceptionTranslator.convertRabbitAccessException(new UnsupportedEncodingException()),
            instanceOf(AmqpUnsupportedEncodingException.class));

    assertThat(RabbitExceptionTranslator.convertRabbitAccessException(new Exception() {
        private static final long serialVersionUID = 1L;
    }), instanceOf(UncategorizedAmqpException.class));

}

From source file:pl.nask.hsn2.DataStoreActiveCleanerTest.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unused" })
private void mockObjects() throws Exception {
    connCloseRequested = false;/*w  w w  .  j ava 2  s.c  o m*/
    new NonStrictExpectations() {
        @Mocked
        ConnectionFactory cf;
        {
            // Create new connection.
            cf.newConnection();
            result = c;

            // Create channel.
            c.createChannel();
            result = ch;

            // Close connection.
            c.close();
            forEachInvocation = new Object() {
                void validate() {
                    connCloseRequested = true;
                }
            };

            // Declare exchange.
            ch.exchangeDeclare(anyString, anyString);

            // Declare queue.
            ch.queueDeclare();
            result = dok;

            // Get queue name.
            dok.getQueue();

            consumer.nextDelivery();
            result = new Delegate() {
                public Delivery nextDelivery() throws Exception {
                    Thread.sleep(100);
                    Delivery d = null;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    switch (nextAction) {
                    case TASK_ACCEPTED:
                        d = taskAcceptedMsg();
                        nextAction = CleaningActions.REMOVE_JOB_1;
                        break;
                    case REMOVE_JOB_1:
                        d = removeJobFinished(1, JobStatus.COMPLETED);
                        nextAction = CleaningActions.REMOVE_JOB_2;
                        break;
                    case REMOVE_JOB_2:
                        d = removeJobFinishedReminder(2);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_3:
                        d = removeJobFinished(3, JobStatus.COMPLETED);
                        nextAction = CleaningActions.REMOVE_JOB_3_AGAIN;
                        break;
                    case REMOVE_JOB_3_AGAIN:
                        d = removeJobFinished(3, JobStatus.COMPLETED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_4:
                        d = removeJobFinished(4, JobStatus.COMPLETED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_5:
                        d = removeJobFinished(5, JobStatus.FAILED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case NEVER_RETURN:
                        while (true) {
                            LOGGER.debug("Never return...");
                            Thread.sleep(10000);
                        }
                    case CANCEL:
                        throw new ConsumerCancelledException();
                    case INTERRUPT:
                        throw new InterruptedException("Test interruption");
                    case SHUTDOWN:
                        throw new ShutdownSignalException(false, false, null, null);
                    case IO_EXCEPTION:
                        throw new IOException("Test I/O exception");
                    }
                    return d;
                }

                private Delivery taskAcceptedMsg() {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("TaskAccepted").build();
                    body = new byte[] { 1 };
                    d = new Delivery(envelope, properties, body);
                    return d;
                }

                private Delivery removeJobFinished(long jobId, JobStatus status) {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("JobFinished").build();
                    jf = JobFinished.newBuilder().setJob(jobId).setStatus(status).build();
                    body = jf.toByteArray();
                    d = new Delivery(envelope, properties, body);
                    return d;
                }

                private Delivery removeJobFinishedReminder(long jobId) {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("JobFinishedReminder").build();
                    JobFinishedReminder jfr = JobFinishedReminder.newBuilder().setJob(jobId)
                            .setStatus(JobStatus.COMPLETED).build();
                    body = jfr.toByteArray();
                    d = new Delivery(envelope, properties, body);
                    return d;
                }
            };
        }
    };
}