Example usage for com.rabbitmq.client AlreadyClosedException AlreadyClosedException

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

Introduction

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

Prototype

public AlreadyClosedException(ShutdownSignalException sse) 

Source Link

Usage

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

License:Mozilla Public License

public void ensureIsOpen() throws AlreadyClosedException {
    if (!isOpen()) {
        throw new AlreadyClosedException(getCloseReason());
    }//from www .  j ava 2 s.  c  o m
}

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

License:Mozilla Public License

/**
 * Protected API - respond, in the driver thread, to a
 * {@link ShutdownSignalException}.//from  w w w .  j  a  v a2s.co  m
 * 
 * @param signal
 *            the signal to handle
 * @param ignoreClosed
 *            the flag indicating whether to ignore the
 *            AlreadyClosedException thrown when the channel is already
 *            closed
 * @param notifyRpc
 *            the flag indicating whether any remaining rpc continuation
 *            should be notified with the given signal
 */
public void processShutdownSignal(ShutdownSignalException signal, boolean ignoreClosed, boolean notifyRpc) {
    try {
        synchronized (_channelMutex) {
            if (!setShutdownCauseIfOpen(signal)) {
                if (!ignoreClosed)
                    throw new AlreadyClosedException(getCloseReason());
            }

            _channelMutex.notifyAll();
        }
    } finally {
        if (notifyRpc)
            notifyOutstandingRpc(signal);
    }
}

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

License:Mozilla Public License

private final void ensureIsOpen() throws AlreadyClosedException {
    if (!isOpen()) {
        throw new AlreadyClosedException(getCloseReason());
    }/*from w  ww  .  j  a  va2  s.c  o m*/
}

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

License:Apache License

@Test
public void shouldResendWhenAlreadyClosedExceptionOccurs() throws IOException {
    // Next ensure that a AlreadyClosedException occurs 
    // and validate that a) a retry is attempted and b) 
    // the data are sent nevertheless. 
    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse));
    crh.send(p2, EXAMPLE_TOPIC);/*from w  w  w .j a va 2s .c  o  m*/
    // verify the logged message, thus spying on the request handler 
    assertEquals(
            "INFO:AlreadyClosedException/retry=1/Msg=channel is already closed due to clean channel shutdown",
            spyLogger.getLastLog());
    // and verify that the message indeed got through 
    assertEquals("Bimse", storage.getCollectionNamed(PRODUCER_CODE).get(0).getString("name"));

    // assert that only two open calls were made 
    assertEquals(2, asStubConnector.getCountOfCallsToOpen());
}

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);//w  w w .  j  a  va 2s .com
    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:dk.au.cs.karibu.integration.TestProducerFailover.java

License:Apache License

@Test
public void shouldResendWhenBothConnectAndAlreadyClosedExcpetionsOccurs() throws IOException {
    // Validate handling of ConnectException as well 
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx03"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx02"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx01"));
    crh.send(p2, EXAMPLE_TOPIC);//from w w  w  .  j a  va2s .c  om
    assertEquals("INFO:ConnectException/retry=3/Msg=CEx03", spyLogger.getLastLog());
    // and verify that the message indeed got through 
    assertEquals("Bimse", storage.getCollectionNamed(PRODUCER_CODE).get(0).getString("name"));

    // Finally validate interleaved failures 
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx04"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse));
    crh.send(p1, EXAMPLE_TOPIC);
    assertEquals("INFO:ConnectException/retry=2/Msg=CEx04", spyLogger.getLastLog());
    // and verify that the message indeed got through (has index 1 in collection as Bimse is already stored) 
    assertEquals("Henrik", storage.getCollectionNamed(PRODUCER_CODE).get(1).getString("name"));
}

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

License:Apache License

@Test
public void shouldFailAfter6ReconnectAttempts() throws IOException {

    // Ensure that reconnect attempts are only made five times. 
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx06"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx05"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new AlreadyClosedException(sse));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx02"));
    asStubConnector.pushExceptionToBeThrownAtNextSend(new ConnectException("CEx01"));

    try {//w w w  . j  a va 2s.c o m
        crh.send(p1, EXAMPLE_TOPIC);
        fail("Reconnection attempt was not given up after the 5th try/" + spyLogger.getLastLog());
    } catch (ConnectException ex) {
        assertEquals("INFO:ConnectException/No more retry attempts permitted/Msg=CEx06",
                spyLogger.getLastLog());
    }
    // assert that only two open calls were made 
    assertEquals(6, asStubConnector.getCountOfCallsToOpen());

}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeAutoAckRetryOnAck() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockConnectionFactory.newConnection()).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });/*from   www. j  av  a2 s  .co  m*/

    AtomicLong ackCount = new AtomicLong(0);
    AtomicLong errorAck = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            errorAck.incrementAndGet();
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    receiver.consumeAutoAck("whatever",
            new ConsumeOptions().exceptionHandler(new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
                    ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE)))
            .subscribe(msg -> {
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
    assertEquals(nbMessages + errorAck.get(), ackCount.get(),
            "There should have been nbMessages+ackInError calls to basicAck as acknowledgments are retried");
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeManualAckRetryOnAck() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockConnectionFactory.newConnection()).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });//from ww w  .j a v a 2s.c  o m

    AtomicLong ackCount = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
            ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE);
    receiver.consumeManualAck("whatever", new ConsumeOptions().exceptionHandler(exceptionHandler))
            .subscribe(msg -> {
                // do business stuff
                // ...
                // trying to ack
                msg.ack();
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
}

From source file:reactor.rabbitmq.ExceptionHandlersTests.java

License:Open Source License

@Test
public void retryableExceptions() {
    predicate = new ExceptionHandlers.ExceptionPredicate(singletonMap(Exception.class, true));
    assertTrue(predicate.test(new AlreadyClosedException(new ShutdownSignalException(true, true, null, null))));
    assertFalse(predicate.test(new Throwable()));

    predicate = new ExceptionHandlers.ExceptionPredicate(new HashMap<Class<? extends Throwable>, Boolean>() {
        {//from w w  w . j  a  va2  s.  c o  m
            put(ShutdownSignalException.class, true);
            put(IOException.class, false);
            put(AuthenticationFailureException.class, true);
        }
    });

    assertTrue(predicate.test(new ShutdownSignalException(true, true, null, null)), "directly retryable");
    assertTrue(predicate.test(new AlreadyClosedException(new ShutdownSignalException(true, true, null, null))),
            "retryable from its super-class");
    assertFalse(predicate.test(new IOException()), "not retryable");
    assertTrue(predicate.test(new AuthenticationFailureException("")), "directly retryable");
}