Java Code Examples for org.apache.qpid.jms.JmsConnection#close()

The following examples show how to use org.apache.qpid.jms.JmsConnection#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JMSWebSocketConnectionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testSendLargeMessageToClientFromOpenWire() throws Exception {
   JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerQpidJMSConnectionURI());
   JmsConnection connection = (JmsConnection) factory.createConnection();

   sendLargeMessageViaOpenWire();

   try {
      Session session = connection.createSession();
      Queue queue = session.createQueue(getQueueName());
      connection.start();

      MessageConsumer consumer = session.createConsumer(queue);
      Message message = consumer.receive(1000);

      assertNotNull(message);
      assertTrue(message instanceof BytesMessage);
   } finally {
      connection.close();
   }
}
 
Example 2
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testTransactionRollbackSucceeds() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    try {
        session.rollback();
    } catch (TransactionRolledBackException ex) {
        fail("Should allow a rollback while offline.");
    }

    connection.close();
}
 
Example 3
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testTransactionCommitFails() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    try {
        session.commit();
        fail("Should not allow a commit while offline.");
    } catch (TransactionRolledBackException ex) {}

    connection.close();
}
 
Example 4
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseWhenDestroyCallFailsDoesNotBlock() throws Exception {
    mockPeer.setResourceDestroyFilter(new ResourceLifecycleFilter() {

        @Override
        public void onLifecycleEvent(JmsResource resource) throws Exception {
            if (resource instanceof JmsSessionInfo) {
                mockPeer.shutdownQuietly();
                throw new ProviderIOException("Failure closing session");
            }
        }
    });

    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    session.close();

    connection.close();
}
 
Example 5
Source File: SessionIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testCreateTemporaryTopicTimesOut() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.setRequestTimeout(500);
        connection.start();

        testPeer.expectBegin();
        testPeer.expectTempTopicCreationAttach(null, false);
        testPeer.expectDetach(true, false, true);

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        try {
            session.createTemporaryTopic();
            fail("Should have timed out on create.");
        } catch (JmsOperationTimedOutException jmsEx) {
            LOG.info("Caught expected exception: {}", jmsEx.getMessage());
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 6
Source File: SessionIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSessionSnapshotsPolicyObjects() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        JmsSession session = (JmsSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        assertNotSame(session.getMessageIDPolicy(), connection.getMessageIDPolicy());
        assertNotSame(session.getPrefetchPolicy(), connection.getPrefetchPolicy());
        assertNotSame(session.getPresettlePolicy(), connection.getPresettlePolicy());
        assertNotSame(session.getRedeliveryPolicy(), connection.getRedeliveryPolicy());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example 7
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testConsumerCloseDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageConsumer consumer = session.createConsumer(queue);

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    consumer.close();
    connection.close();
}
 
Example 8
Source File: ConnectionFactoryIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSetCustomPrefetchPolicy() throws Exception {
    CustomJmsPrefetchPolicy custom = new CustomJmsPrefetchPolicy();

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Ignore errors from peer close due to not sending any Open / Close frames
        testPeer.setSuppressReadExceptionOnClose(true);

        String uri = "amqp://127.0.0.1:" + testPeer.getServerPort();

        testPeer.expectSaslAnonymous();

        JmsConnectionFactory factory = new JmsConnectionFactory(uri);
        factory.setPrefetchPolicy(custom);
        assertEquals(custom, factory.getPrefetchPolicy());

        JmsConnection connection = (JmsConnection) factory.createConnection();
        assertTrue(connection.getPrefetchPolicy() instanceof CustomJmsPrefetchPolicy);
        assertNotSame(custom, connection.getPrefetchPolicy());

        testPeer.waitForAllHandlersToCompleteNoAssert(1000);

        testPeer.expectOpen();
        testPeer.expectClose();

        connection.close();

        testPeer.waitForAllHandlersToCompleteNoAssert(1000);
    }
}
 
Example 9
Source File: TransactionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionCreateFailsOnDeclareTimeout() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.setRequestTimeout(500);
        connection.start();

        testPeer.expectBegin();
        testPeer.expectCoordinatorAttach();
        testPeer.expectDeclareButDoNotRespond();
        // Expect the AMQP session to be closed due to the JMS session creation failure.
        testPeer.expectEnd();

        try {
            connection.createSession(true, Session.SESSION_TRANSACTED);
            fail("Should have timed out waiting for declare.");
        } catch (JmsOperationTimedOutException jmsEx) {
        } catch (Throwable error) {
            fail("Should have caught an timed out exception:");
            LOG.error("Caught -> ", error);
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 10
Source File: TransactionsIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testTransactionRolledBackOnSessionCloseTimesOut() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.setRequestTimeout(500);
        connection.start();

        testPeer.expectBegin();
        testPeer.expectCoordinatorAttach();

        Binary txnId = new Binary(new byte[]{ (byte) 5, (byte) 6, (byte) 7, (byte) 8});
        testPeer.expectDeclare(txnId);

        // Closed session should roll-back the TX with a failed discharge
        testPeer.expectDischargeButDoNotRespond(txnId, true);

        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

        try {
            session.close();
            fail("Should have timed out waiting for declare.");
        } catch (JmsOperationTimedOutException jmsEx) {
        } catch (Throwable error) {
            fail("Should have caught an timed out exception:");
            LOG.error("Caught -> ", error);
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 11
Source File: IdleTimeoutIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testConnectionSetFailedWhenPeerNeglectsToSendEmptyFrames() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        int configuredTimeout = 200;

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();

        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?amqp.idleTimeout=" + configuredTimeout);
        final JmsConnection connection = (JmsConnection) factory.createConnection();
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        // The peer is still connected, so it will get the close frame with error
        testPeer.expectClose(Matchers.notNullValue(), false);
        assertNull(testPeer.getThrowable());
        testPeer.setSuppressReadExceptionOnClose(true);

        boolean failed = Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisfied() throws Exception {
                return connection.isFailed();
            }
        }, 10000, 10);

        assertTrue("connection didnt fail in expected timeframe", failed);
        testPeer.waitForAllHandlersToComplete(1000);

        connection.close();
    }
}
 
Example 12
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testAsyncCompletionGetsNotifiedWhenConnectionClosed() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);

        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");

        MessageProducer producer = session.createProducer(queue);

        // Create and transfer a new message
        String text = "myMessage";
        testPeer.expectTransferButDoNotRespond(new TransferPayloadCompositeMatcher());
        testPeer.expectClose();

        TextMessage message = session.createTextMessage(text);
        TestJmsCompletionListener listener = new TestJmsCompletionListener();

        producer.send(message, listener);

        connection.close();

        assertTrue("Did not get async callback", listener.awaitCompletion(5, TimeUnit.SECONDS));
        assertNotNull(listener.exception);
        assertNotNull(listener.message);
        assertTrue(listener.message instanceof TextMessage);

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 13
Source File: IdleTimeoutIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testConnectionNotMarkedFailedWhenPeerSendsEmptyFrames() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        int configuredTimeout = 2000;
        int period = 500;
        int cycles = 6;

        final CountDownLatch latch = new CountDownLatch(cycles);

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();

        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        // Start to emit idle frames when the connection is set up, this should stop it timing out
        testPeer.runAfterLastHandler(new EmptyFrameSender(latch, period, cycles, testPeer));

        JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?amqp.idleTimeout=" + configuredTimeout);
        final JmsConnection connection = (JmsConnection) factory.createConnection();
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        boolean framesSent = latch.await(cycles * period * 2, TimeUnit.MILLISECONDS);
        assertTrue("idle frames were not sent as expected", framesSent);

        assertFalse("connection shouldnt fail", connection.isFailed());
        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());
    }
}
 
Example 14
Source File: AnonymousFallbackProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Repeat(repetitions = 1)
@Test(timeout = 20000)
public void testAsyncSendFailureHandled() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        final CountDownLatch sendFailureReportedToListener = new CountDownLatch(1);
        final AtomicReference<Throwable> sendFailureError = new AtomicReference<>();

        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer,
            "?jms.forceAsyncSend=true&amqp.anonymousFallbackCacheSize=0&amqp.anonymousFallbackCacheTimeout=60000");

        connection.setExceptionListener((error) -> {
            sendFailureError.compareAndSet(null, error);
            sendFailureReportedToListener.countDown();
        });

        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);

        // Expect no AMQP traffic when we create the anonymous producer, as it will wait
        // for an actual send to occur on the producer before anything occurs on the wire

        //Create an anonymous producer
        MessageProducer producer = session.createProducer(null);
        assertNotNull("Producer object was null", producer);

        // Expect a new message sent by the above producer to cause creation of a new
        // sender link to the given destination, then closing the link after the message is sent.
        TargetMatcher targetMatcher = new TargetMatcher();
        targetMatcher.withAddress(equalTo(topicName));
        targetMatcher.withDynamic(equalTo(false));
        targetMatcher.withDurable(equalTo(TerminusDurability.NONE));

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);

        final String BREAD_CRUMB = "SEND FAILURE EXPECTED";

        org.apache.qpid.jms.test.testpeer.describedtypes.Error rejectError = new org.apache.qpid.jms.test.testpeer.describedtypes.Error();
        rejectError.setCondition(AmqpError.RESOURCE_LIMIT_EXCEEDED);
        rejectError.setDescription(BREAD_CRUMB);

        testPeer.expectSenderAttach(targetMatcher, false, false);
        testPeer.expectTransfer(messageMatcher, nullValue(), new Rejected().setError(rejectError), true);
        testPeer.expectDetach(true, true, true);

        // Producer should act as synchronous regardless of asynchronous send setting.
        Message message = session.createMessage();
        try {
            producer.send(dest, message);
        } catch (JMSException jmsEx) {
            LOG.debug("Caught expected error from failed send.");
            fail("Send should not fail as it should have fired asynchronously");
        }

        // Repeat the send and observe another attach->transfer->detach.
        testPeer.expectSenderAttach(targetMatcher, false, false);
        testPeer.expectTransfer(messageMatcher);
        testPeer.expectDetach(true, true, true);

        assertTrue("Send failure not reported to exception handler", sendFailureReportedToListener.await(5, TimeUnit.SECONDS));
        assertNotNull(sendFailureError.get());
        assertTrue(sendFailureError.get() instanceof ResourceAllocationException);
        assertTrue(sendFailureError.get().getMessage().contains(BREAD_CRUMB));

        producer.send(dest, message);

        // Send here is asynchronous so we need to wait for disposition to arrive and detach to happen
        testPeer.waitForAllHandlersToComplete(1000);

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 15
Source File: ConnectionConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testRemotelyCloseConnectionConsumer() throws Exception {
    final String BREAD_CRUMB = "ErrorMessage";

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        final CountDownLatch connectionError = new CountDownLatch(1);
        JmsServerSessionPool sessionPool = new JmsServerSessionPool();
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.setExceptionListener(new ExceptionListener() {

            @Override
            public void onException(JMSException exception) {
                connectionError.countDown();
            }
        });

        // Create a consumer, then remotely end it afterwards.
        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlow();
        testPeer.remotelyDetachLastOpenedLinkOnLastOpenedSession(true, true, AmqpError.RESOURCE_DELETED, BREAD_CRUMB);

        Queue queue = new JmsQueue("myQueue");
        ConnectionConsumer consumer = connection.createConnectionConsumer(queue, null, sessionPool, 100);

        // Verify the consumer gets marked closed
        testPeer.waitForAllHandlersToComplete(1000);
        assertTrue("consumer never closed.", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisfied() throws Exception {
                try {
                    consumer.getServerSessionPool();
                } catch (IllegalStateException jmsise) {
                    LOG.debug("Error reported from consumer.getServerSessionPool()", jmsise);
                    if (jmsise.getCause() != null) {
                        String message = jmsise.getCause().getMessage();
                        return message.contains(AmqpError.RESOURCE_DELETED.toString()) &&
                               message.contains(BREAD_CRUMB);
                    } else {
                        return false;
                    }
                }
                return false;
            }
        }, 10000, 10));

        assertTrue("Consumer closed callback didn't trigger", connectionError.await(5, TimeUnit.SECONDS));

        // Try closing it explicitly, should effectively no-op in client.
        // The test peer will throw during close if it sends anything.
        consumer.close();

        testPeer.expectClose();
        connection.close();
    }
}
 
Example 16
Source File: AnonymousFallbackProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Repeat(repetitions = 1)
@Test(timeout = 60000)
public void testRepeatedSendToSameAddressWhenCacheSizeOfOneKeepsFallbackProducerInCache() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        final int MESSAGE_COUNT = 25;

        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer,
            "?amqp.anonymousFallbackCacheSize=1&amqp.anonymousFallbackCacheTimeout=200");

        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";

        // Expect no AMQP traffic when we create the anonymous producer, as it will wait
        // for an actual send to occur on the producer before anything occurs on the wire

        // Create an anonymous producer
        MessageProducer producer = session.createProducer(null);
        assertNotNull("Producer object was null", producer);

        // Expect a new message sent by the above producer to cause creation of a new
        // sender link to the given destination.
        TargetMatcher targetMatcher = new TargetMatcher();
        targetMatcher.withAddress(equalTo(topicName));
        targetMatcher.withDynamic(equalTo(false));
        targetMatcher.withDurable(equalTo(TerminusDurability.NONE));

        testPeer.expectSenderAttach(targetMatcher, false, true);

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);

        Topic dest = session.createTopic(topicName);
        Message message = session.createMessage();

        // Setup our expectations
        for (int i = 1; i <= MESSAGE_COUNT; ++i) {
            testPeer.expectTransfer(messageMatcher);
        }

        testPeer.expectDetach(true, true, true);

        // First round of sends should open and cache sender links
        for (int i = 1; i <= MESSAGE_COUNT; ++i) {
            producer.send(dest, message);
        }

        LOG.debug("Finished with send cycle, producer should now timeout");

        // The eviction timer should reduce the cache to zero after we go idle
        testPeer.waitForAllHandlersToComplete(3000);

        producer.close();

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 17
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testConnectHandlesSaslTempFailure() throws Exception {
    try (TestAmqpPeer originalPeer = new TestAmqpPeer();
         TestAmqpPeer finalPeer = new TestAmqpPeer();) {

        final CountDownLatch finalConnected = new CountDownLatch(1);
        final String finalURI = createPeerURI(finalPeer);

        originalPeer.expectSaslFailingExchange(new Symbol[] { ANONYMOUS }, ANONYMOUS, SASL_SYS_TEMP);

        finalPeer.expectSaslAnonymous();
        finalPeer.expectOpen();
        finalPeer.expectBegin();

        final JmsConnection connection = establishAnonymousConnecton(originalPeer, finalPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (finalURI.equals(remoteURI.toString())) {
                    finalConnected.countDown();
                }
            }
        });

        try {
            connection.start();
        } catch (Exception ex) {
            fail("Should not have thrown an Exception: " + ex);
        }

        assertTrue("Should connect to final peer", finalConnected.await(5, TimeUnit.SECONDS));

        String content = "myContent";
        final DescribedType amqpValueNullContent = new AmqpValueDescribedType(content);

        finalPeer.expectBegin();
        finalPeer.expectReceiverAttach();
        finalPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent);
        finalPeer.expectDispositionThatIsAcceptedAndSettled();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(2000);

        finalPeer.expectClose();
        connection.close();
        finalPeer.waitForAllHandlersToComplete(1000);

        assertNotNull(message);
        assertTrue(message instanceof TextMessage);
        assertEquals(content, ((TextMessage) message).getText());
    }
}
 
Example 18
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testPassthroughOfSendTimesOutWhenNoDispostionArrives() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        final String testPeerURI = createPeerURI(testPeer);
        LOG.info("Original peer is at: {}", testPeerURI);

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();
        testPeer.expectBegin();
        testPeer.expectBegin();

        JmsConnection connection = establishAnonymousConnecton(testPeer);
        connection.setSendTimeout(500);
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        String queueName = "myQueue";
        Queue queue = session.createQueue(queueName);

        Message message = session.createTextMessage("text");
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();

        // Expect the producer to attach and grant it some credit, it should send
        // a transfer which we will not send any response for which should cause the
        // send operation to time out.
        testPeer.expectSenderAttach();
        testPeer.expectTransferButDoNotRespond(messageMatcher);
        testPeer.expectClose();

        MessageProducer producer = session.createProducer(queue);

        try {
            producer.send(message);
            fail("Send should time out.");
        } catch (JmsSendTimedOutException jmsEx) {
            LOG.info("Caught expected error: {}", jmsEx.getMessage());
        } catch (Throwable error) {
            fail("Send should time out, but got: " + error.getMessage());
        }

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 19
Source File: AnonymousFallbackProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Repeat(repetitions = 1)
@Test(timeout = 30000)
public void testCachedFallbackProducersAreTimedOut() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        final int CACHE_SIZE = 5;

        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer,
            "?amqp.anonymousFallbackCacheSize=" + CACHE_SIZE + "&amqp.anonymousFallbackCacheTimeout=300");

        connection.start();

        testPeer.expectBegin();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";

        // Expect no AMQP traffic when we create the anonymous producer, as it will wait
        // for an actual send to occur on the producer before anything occurs on the wire

        // Create an anonymous producer
        MessageProducer producer = session.createProducer(null);
        assertNotNull("Producer object was null", producer);

        // First round of sends should open and cache sender links
        for (int i = 1; i <= CACHE_SIZE; ++i) {
            Topic dest = session.createTopic(topicName + i);

            // Expect a new message sent by the above producer to cause creation of a new
            // sender link to the given destination.
            TargetMatcher targetMatcher = new TargetMatcher();
            targetMatcher.withAddress(equalTo(dest.getTopicName()));
            targetMatcher.withDynamic(equalTo(false));
            targetMatcher.withDurable(equalTo(TerminusDurability.NONE));

            MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
            MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
            TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
            messageMatcher.setHeadersMatcher(headersMatcher);
            messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);

            Message message = session.createMessage();

            testPeer.expectSenderAttach(targetMatcher, false, false);
            testPeer.expectTransfer(messageMatcher);

            producer.send(dest, message);
        }

        // Cached senders should all close when the cache timeout is reached and they are expired
        for (int i = 1; i <= CACHE_SIZE; ++i) {
            testPeer.expectDetach(true, true, true);
        }

        // On a slow CI machine we could fail here due to the timeouts not having run.
        testPeer.waitForAllHandlersToComplete(6000);

        producer.close();

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 20
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testPassthroughOfSendFailsWhenDelayedDeliveryIsNotSupported() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer()) {

        final String testPeerURI = createPeerURI(testPeer);
        LOG.info("Original peer is at: {}", testPeerURI);

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();
        testPeer.expectBegin();
        testPeer.expectBegin();

        // DO NOT add capability to indicate server support for DELAYED-DELIVERY so that
        // send fails and we can see if the error passes through the failover provider
        JmsConnection connection = establishAnonymousConnecton(testPeer);
        connection.start();

        Matcher<Symbol[]> desiredCapabilitiesMatcher = arrayContaining(new Symbol[] { DELAYED_DELIVERY });
        Symbol[] offeredCapabilities = null;
        testPeer.expectSenderAttach(notNullValue(), notNullValue(), false, false, false, false, 0, 1, null, null, desiredCapabilitiesMatcher, offeredCapabilities);

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "myTopic";
        Topic dest = session.createTopic(topicName);

        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryDelay(5000);

        // Producer should fail to send when message has delivery delay since remote
        // did not report that it supports that option.
        Message message = session.createMessage();
        try {
            producer.send(message);
            fail("Send should fail");
        } catch (JMSException jmsEx) {
            LOG.debug("Caught expected error from failed send.");
        }

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}