Java Code Examples for javax.jms.Session#createQueue()

The following examples show how to use javax.jms.Session#createQueue() . 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: ProducerAutoCreateQueueTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAutoCreateSendToQueue() throws Exception {
   Connection connection = null;
   try {
      connection = factory.createConnection("admin", "password");
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue trash = session.createQueue("trash");
      final MessageProducer producer = session.createProducer(trash);
      producer.send(session.createTextMessage("foo"));
   } finally {
      if (connection != null) {
         connection.close();
      }
   }

   Wait.assertTrue(() -> server.getAddressInfo(new SimpleString("trash")) != null);
   Wait.assertTrue(() -> server.locateQueue(new SimpleString("trash")) != null);
   Wait.assertEquals(1, server::getTotalMessageCount);
}
 
Example 2
Source File: JmsQueueBrowserTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=30000)
public void testBroseOneInQueue() throws Exception {
    connection = createAmqpConnection();
    connection.start();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(getDestinationName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("hello"));
    producer.close();

    QueueBrowser browser = session.createBrowser(queue);
    Enumeration enumeration = browser.getEnumeration();
    while (enumeration.hasMoreElements()) {
        Message m = (Message) enumeration.nextElement();
        assertTrue(m instanceof TextMessage);
        LOG.debug("Browsed message {} from Queue {}", m, queue);
    }

    browser.close();

    MessageConsumer consumer = session.createConsumer(queue);
    Message msg = consumer.receive(5000);
    assertNotNull(msg);
    assertTrue(msg instanceof TextMessage);
}
 
Example 3
Source File: QpidAmqpTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
    public void testQueue() throws Exception {
        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
        // Qpid的JMS 2.0 API(似乎有些问题.无法使用队列)
//        try (JMSContext context = factory.createContext()) {
//            Queue queue = context.createQueue("queue.amqp");
//
//            JMSProducer producer = context.createProducer();
//            producer.send(queue, content);
//
//            JMSConsumer consumer = context.createConsumer(queue);
//            Message message = consumer.receive(5000);
//
//            Assert.assertEquals(queue, message.getJMSDestination());
//            Assert.assertEquals(content, message.getBody(String.class));
//        }
        // Qpid的JMS 1.0 API
        Connection connection = factory.createConnection();
        connection.start();
        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("queue.amqp");

            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(content));

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

            Assert.assertEquals(queue, message.getJMSDestination());
            Assert.assertEquals(content, message.getBody(String.class));
        } finally {
            connection.close();
        }
    }
 
Example 4
Source File: FailoverComplexClusterTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void createClients(int numOfClients) throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl);
   for (int i = 0; i < numOfClients; i++) {
      ActiveMQConnection c = (ActiveMQConnection) factory.createConnection();
      c.start();
      Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = s.createQueue(getClass().getName());
      MessageConsumer consumer = s.createConsumer(queue);
      connections.add(c);
   }
}
 
Example 5
Source File: ConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testNoReceivedMessagesWhenConnectionNotStarted() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        final CountDownLatch incoming = new CountDownLatch(1);
        Connection connection = testFixture.establishConnecton(testPeer);

        // Allow wait for incoming message before we call receive.
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {

            @Override
            public void onInboundMessage(JmsInboundMessageDispatch envelope) {
                incoming.countDown();
            }
        });

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(getTestName());

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content"), 3);

        MessageConsumer consumer = session.createConsumer(destination);

        // Wait for a message to arrive then try and receive it, which should not happen
        // since the connection is not started.
        assertTrue(incoming.await(10, TimeUnit.SECONDS));
        assertNull(consumer.receive(100));

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

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 6
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testDefaultDeliveryModeProducesDurableMessages() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = 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
        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        Message message = session.createTextMessage();

        producer.send(message);
        assertEquals(DeliveryMode.PERSISTENT, message.getJMSDeliveryMode());

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 7
Source File: LoggingActiveMQServerPluginTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void sendAndReceive(boolean send,
                              boolean receive,
                              String txtMessage,
                              long expiry) throws JMSException, InterruptedException {
   Connection connection = createActiveMQConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   connection.start();
   Queue queue = session.createQueue("TEST.QUEUE");
   MessageConsumer messageConsumer = null;

   if (receive) {
      messageConsumer = session.createConsumer(queue);
      Thread.sleep(1000);
   }
   if (send) {
      MessageProducer messageProducer = session.createProducer(queue);
      if (expiry > 0) {
         messageProducer.setTimeToLive(expiry);
      }
      messageProducer.send(session.createTextMessage(txtMessage));
   }
   if (receive) {
      messageConsumer.receive(100);
      messageConsumer.close();
   }

   session.close();
   connection.close();
}
 
Example 8
Source File: MemoryConsumptionTestClient.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void purgeQueue(ConnectionFactory connectionFactory, String queueString, long receiveTimeout) throws JMSException
{
    LOGGER.debug("Consuming left over messages, using receive timeout:" + receiveTimeout);

    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(queueString);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();

    int count = 0;
    while (true)
    {
        BytesMessage msg = (BytesMessage) consumer.receive(receiveTimeout);

        if(msg == null)
        {
            LOGGER.debug("Received {} message(s)", count);
            break;
        }
        else
        {
            count++;
        }
    }

    consumer.close();
    session.close();
    connection.close();
}
 
Example 9
Source File: JmsRedeliveredTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests session recovery and that the redelivered message is marked as
 * such. Session uses client acknowledgement, the destination is a queue.
 *
 * @throws JMSException
 */
public void testQueueRecoverMarksMessageRedelivered() throws JMSException {
   connection.start();

   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Queue queue = session.createQueue("queue-" + getName());
   MessageProducer producer = createProducer(session, queue);
   producer.send(createTextMessage(session));

   // Consume the message...
   MessageConsumer consumer = session.createConsumer(queue);
   Message msg = consumer.receive(1000);
   assertNotNull(msg);
   assertFalse("Message should not be redelivered.", msg.getJMSRedelivered());
   // Don't ack the message.

   // Reset the session. This should cause the Unacked message to be
   // redelivered.
   session.recover();

   // Attempt to Consume the message...
   msg = consumer.receive(2000);
   assertNotNull(msg);
   assertTrue("Message should be redelivered.", msg.getJMSRedelivered());
   msg.acknowledge();

   session.close();
}
 
Example 10
Source File: DtxStartPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if publishing messages works correctly with session suspending and resuming.Steps are,
 * 1. Using a distributed transaction a message is published to a queue and session is suspended
 * 2. Subscribe to the published queue and see if any message is received.
 * 3. Resume the suspended session and publish another message and commit
 * 4. Subscribe to the queue and see if two messages are received
 */
@Test(groups = { "wso2.mb", "dtx" })
public void suspendResumeQueuePublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxStartPositiveTestCaseSuspendResumeQueuePublishTestCase";

    InitialContext initialContext = JMSClientHelper.createInitialContextBuilder("admin", "admin", "localhost",
            getAMQPPort()).withQueue(queueName).build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMSUSPEND);

    // subscribe and see if the message is received
    ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection queueConnection = queueConnectionFactory.createConnection();
    queueConnection.start();
    Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer messageConsumer = queueSession.createConsumer(xaTestQueue);

    // wait 5 seconds
    Message receive = messageConsumer.receive(5000);
    Assert.assertNull(receive, "Message received. Message was not rolled back");


    xaResource.start(xid, XAResource.TMRESUME);
    producer.send(session.createTextMessage("Test 2"));
    xaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.prepare(xid);
    xaResource.commit(xid, false);

    session.close();
    xaConnection.close();

    receive = messageConsumer.receive(5000);
    Assert.assertNotNull(receive, "Message not received");

    receive = messageConsumer.receive(5000);
    Assert.assertNotNull(receive, "Message not received");

    queueConnection.close();
}
 
Example 11
Source File: WorkDoneOutsideTransactionTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Publish and then consume outside a distributed transaction
 *
 * @throws XPathExpressionException
 * @throws NamingException
 * @throws JMSException
 * @throws XAException
 */
@Test(groups = { "wso2.mb", "dtx" })
public void publishConsumeOutsideTransactionTestCase() throws XPathExpressionException, NamingException,
                                                              JMSException, XAException {

    String queueName = "publishConsumeOutsideTransactionTestCase";
    String outsideTransactionMessage = "outside transaction";

    InitialContext initialContext =
            JMSClientHelper.createInitialContextBuilder("admin", "admin", "localhost",
                                                        getAMQPPort()).withQueue(queueName).build();


    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);

    MessageConsumer consumer = session.createConsumer(xaTestQueue);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = new TestXidImpl(100, new byte[] { 0x01 }, new byte[] { 0x05 });

    producer.send(session.createTextMessage(outsideTransactionMessage));

    xaResource.start(xid, XAResource.TMNOFLAGS);
    consumer.receive(30000);
    xaResource.end(xid, XAResource.TMSUCCESS);

    int status  = xaResource.prepare(xid);
    Assert.assertEquals(status, XAResource.XA_OK, "Prepare state failed for distributed transaction");

    xaResource.rollback(xid);
    JMSTextMessage message = (JMSTextMessage) consumer.receive(30000);

    Assert.assertNotNull(message, "Message did not receive from server");
    Assert.assertEquals(message.getText(), outsideTransactionMessage, "Invalid Message received");

    session.close();
    xaConnection.close();

}
 
Example 12
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that when sending a message with the JMSXGroupID, JMSXGroupSeq, and JMS_AMQP_REPLY_TO_GROUP_ID
 * properties of the JMS message set, that the expected values are included in the fields of
 * the AMQP message emitted.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test(timeout = 20000)
public void testSendMessageWithGroupRelatedPropertiesSet() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

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

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);

        String expectedGroupId = "myGroupId123";
        int expectedGroupSeq = 1;
        String expectedReplyToGroupId = "myReplyToGroupId456";

        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true);
        propsMatcher.withGroupId(equalTo(expectedGroupId));
        propsMatcher.withReplyToGroupId(equalTo(expectedReplyToGroupId));
        propsMatcher.withGroupSequence(equalTo(UnsignedInteger.valueOf(expectedGroupSeq)));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(null));
        testPeer.expectTransfer(messageMatcher);

        Message message = session.createTextMessage();
        message.setStringProperty(JmsClientProperties.JMSXGROUPID, expectedGroupId);
        message.setIntProperty(JmsClientProperties.JMSXGROUPSEQ, expectedGroupSeq);
        message.setStringProperty(AmqpMessageSupport.JMS_AMQP_REPLY_TO_GROUP_ID, expectedReplyToGroupId);

        producer.send(message);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 13
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testLastValueQueueUsingAddressQueueParameters() throws Exception {
   ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();

   //Set the consumer window size to 0 to not buffer any messages client side.
   fact.setConsumerWindowSize(0);
   Connection connection = fact.createConnection();

   try {

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

      Queue queue = session.createQueue("random?last-value=true");
      assertEquals("random", queue.getQueueName());

      ActiveMQDestination a = (ActiveMQDestination) queue;
      assertTrue(a.getQueueAttributes().getLastValue());
      assertTrue(a.getQueueConfiguration().isLastValue());

      MessageProducer producer = session.createProducer(queue);
      MessageConsumer consumer1 = session.createConsumer(queue);

      connection.start();
      for (int j = 0; j < 100; j++) {
         TextMessage message = session.createTextMessage();

         message.setText("Message" + j);
         message.setStringProperty(Message.HDR_LAST_VALUE_NAME.toString(), "key");
         producer.send(message);
      }

      //Last message only should go to the consumer
      TextMessage tm = (TextMessage) consumer1.receive(10000);

      assertNotNull(tm);

      assertEquals("Message99", tm.getText());

   } finally {
      connection.close();
   }
}
 
Example 14
Source File: QueueDistributedTransactionTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Test
public void testPublisherWithCommit() throws NamingException, JMSException, XAException {

    String queueName = "testPublisherWithCommit";
    String testMessage = "testPublisherWithCommit-Message";
    InitialContext initialContext = initialContextBuilder.withXaConnectionFactory()
                                                         .withQueue(queueName)
                                                         .build();

    XAConnectionFactory xaConnectionFactory =
            (XAConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);

    XAConnection xaConnection = xaConnectionFactory.createXAConnection();
    XASession xaSession = xaConnection.createXASession();
    XAResource xaResource = xaSession.getXAResource();

    Session session = xaSession.getSession();
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);
    xaConnection.start();

    XidImpl xid = new XidImpl(0, "branchId_1".getBytes(), "globalId_1".getBytes());
    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage(testMessage));
    xaResource.end(xid, XAResource.TMSUCCESS);

    int prepareOK = xaResource.prepare(xid);
    Assert.assertEquals(prepareOK, XAResource.XA_OK, "Prepare phase should return XA_OK");

    xaResource.commit(xid, false);

    // Test by consuming the committed message.
    ConnectionFactory connectionFactory =
            (ConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    Session receivingSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = receivingSession.createConsumer(receivingSession.createQueue(queueName));
    connection.start();
    TextMessage message = (TextMessage) consumer.receive(3000);

    Assert.assertNotNull(message, "Didn't receive a message");
    Assert.assertEquals(message.getText(), testMessage, "Received message should match sent message");

    session.close();
    xaConnection.close();
    connection.close();
}
 
Example 15
Source File: SessionIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doCreateProducerTargetContainsCapabilityTestImpl(Class<? extends Destination> destType) throws JMSException, Exception, IOException {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();

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

        String destName = "myDest";
        Symbol nodeTypeCapability = null;

        Destination dest = null;
        if (destType == Queue.class) {
            dest = session.createQueue(destName);
            nodeTypeCapability = AmqpDestinationHelper.QUEUE_CAPABILITY;
        } else if (destType == Topic.class) {
            dest = session.createTopic(destName);
            nodeTypeCapability = AmqpDestinationHelper.TOPIC_CAPABILITY;
        } else if (destType == TemporaryQueue.class) {
            testPeer.expectTempQueueCreationAttach(destName);
            dest = session.createTemporaryQueue();
            nodeTypeCapability = AmqpDestinationHelper.TEMP_QUEUE_CAPABILITY;
        } else if (destType == TemporaryTopic.class) {
            testPeer.expectTempTopicCreationAttach(destName);
            dest = session.createTemporaryTopic();
            nodeTypeCapability = AmqpDestinationHelper.TEMP_TOPIC_CAPABILITY;
        } else {
            fail("unexpected type");
        }

        TargetMatcher targetMatcher = new TargetMatcher();
        targetMatcher.withCapabilities(arrayContaining(nodeTypeCapability));

        testPeer.expectSenderAttach(targetMatcher, false, false);
        testPeer.expectClose();

        session.createProducer(dest);

        connection.close();

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

        // Expect a PLAIN connection
        String user = "user";
        String pass = "qwerty123456";

        testPeer.expectSaslPlain(user, pass);
        testPeer.expectOpen();
        testPeer.expectBegin();
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        JmsConnectionFactory factory = new JmsConnectionFactory(
            "amqp://localhost:" + testPeer.getServerPort());
        factory.setPopulateJMSXUserID(false);

        Connection connection = factory.createConnection(user, pass);
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("TestQueue");
        MessageProducer producer = session.createProducer(queue);

        MessagePropertiesSectionMatcher propertiesMatcher = new MessagePropertiesSectionMatcher(true);
        propertiesMatcher.withUserId(nullValue());
        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setPropertiesMatcher(propertiesMatcher);
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);

        testPeer.expectTransfer(messageMatcher);

        Message message = new CustomForeignMessage();
        producer.send(message);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 17
Source File: FailoverPrefetchZeroTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
@BMRules(
   rules = {@BMRule(
      name = "set no return response and stop the broker",
      targetClass = "org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection$CommandProcessor",
      targetMethod = "processMessagePull",
      targetLocation = "ENTRY",
      action = "org.apache.activemq.transport.failover.FailoverPrefetchZeroTest.holdResponseAndStopBroker($0)")})
public void testPrefetchZeroConsumerThroughRestart() throws Exception {
   broker = createBroker();
   broker.start();
   doByteman.set(true);

   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
   cf.setWatchTopicAdvisories(false);

   final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
   connection.start();

   final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);

   final MessageConsumer consumer = consumerSession.createConsumer(destination);
   produceMessage(consumerSession, destination, 1);

   final CountDownLatch receiveDone = new CountDownLatch(1);
   final Vector<Message> received = new Vector<>();
   new Thread() {
      @Override
      public void run() {
         try {
            LOG.info("receive one...");
            Message msg = consumer.receive(30000);
            if (msg != null) {
               received.add(msg);
            }
            receiveDone.countDown();
            LOG.info("done receive");
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
   }.start();

   // will be stopped by the plugin
   assertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS));
   brokerStopLatch.await();
   doByteman.set(false);
   broker = createBroker();
   broker.start();

   assertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS));

   assertTrue("we got our message:", !received.isEmpty());

   connection.close();
}
 
Example 18
Source File: ConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout=20000)
public void testMessageListenerCallsConnectionStopThrowsIllegalStateException() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Exception> asyncError = new AtomicReference<Exception>(null);

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        final Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(getTestName());
        connection.start();

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content"), 1);

        MessageConsumer consumer = session.createConsumer(destination);

        testPeer.expectDisposition(true, new AcceptedMatcher());

        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message m) {
                try {
                    LOG.debug("Async consumer got Message: {}", m);
                    connection.stop();
                } catch (Exception ex) {
                    asyncError.set(ex);
                }

                latch.countDown();
            }
        });

        boolean await = latch.await(3, TimeUnit.MINUTES);
        assertTrue("Messages not received within given timeout. Count remaining: " + latch.getCount(), await);

        assertNotNull("Expected IllegalStateException", asyncError.get());
        assertTrue(asyncError.get() instanceof IllegalStateException);

        testPeer.waitForAllHandlersToComplete(2000);

        testPeer.expectDetach(true, true, true);
        consumer.close();

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

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 19
Source File: ConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout=20000)
public void testCloseConsumersWithDeferredAckHandledLaterWhenlastConsumedMessageIsAcked() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        final int DEFAULT_PREFETCH = 10;

        // Set to fixed known value to reduce breakage if defaults are changed.
        Connection connection = testFixture.establishConnecton(testPeer, "jms.prefetchPolicy.all=" + DEFAULT_PREFETCH);
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue(getTestName());

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content-for-consumer-1"),
                1, false, false, Matchers.equalTo(UnsignedInteger.valueOf(DEFAULT_PREFETCH)), 1, true);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, new AmqpValueDescribedType("content-for-consumer-2"),
                1, false, false, Matchers.equalTo(UnsignedInteger.valueOf(DEFAULT_PREFETCH)), 2, true);

        final CountDownLatch expected = new CountDownLatch(2);
        ((JmsConnection) connection).addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onInboundMessage(JmsInboundMessageDispatch envelope) {
                expected.countDown();
            }
        });

        // These are our two consumers, the first gets a message and abandons it, the second will have
        // acknowledge called on its message which will lead to the message for the first to be acknowledged
        // and then it's link will be closed.
        MessageConsumer consumer1 = session.createConsumer(queue);
        MessageConsumer consumer2 = session.createConsumer(queue);
        Message receivedMessage1 = null;
        Message receivedMessage2 = null;

        // Ensure all the messages arrived so that the matching below is deterministic
        assertTrue("Expected transfers didnt occur: " + expected.getCount(), expected.await(5, TimeUnit.SECONDS));

        // Take our two messages from the queue leaving them in a delivered state.
        receivedMessage1 = consumer1.receive(3000);
        assertNotNull(receivedMessage1);
        assertTrue(receivedMessage1 instanceof TextMessage);
        receivedMessage2 = consumer2.receive(3000);
        assertNotNull(receivedMessage2);
        assertTrue(receivedMessage2 instanceof TextMessage);

        // Expect the client to then drain off all credit from the link when "closed"
        testPeer.expectLinkFlow(true, true, equalTo(UnsignedInteger.valueOf(DEFAULT_PREFETCH - 1)));
        // Expect the client to then drain off all credit from the link when "closed"
        testPeer.expectLinkFlow(true, true, equalTo(UnsignedInteger.valueOf(DEFAULT_PREFETCH - 1)));

        // Close should be deferred as the messages were delivered but not acknowledged.
        consumer1.close();
        consumer2.close();

        testPeer.waitForAllHandlersToComplete(3000);

        testPeer.expectDisposition(true, new AcceptedMatcher());
        testPeer.expectDisposition(true, new AcceptedMatcher());

        // Now the links should close as we tear down the deferred consumers
        testPeer.expectDetach(true, true, true);
        testPeer.expectDetach(true, true, true);

        // Acknowledge the last read message, which should accept all previous messages as well
        // and our consumers should then close their links in turn.
        receivedMessage2.acknowledge();

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

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 20
Source File: DynamicDestinationResolver.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Resolve the given destination name to a {@link Queue}.
 * @param session the current JMS Session
 * @param queueName the name of the desired {@link Queue}
 * @return the JMS {@link Queue}
 * @throws javax.jms.JMSException if resolution failed
 * @see Session#createQueue(String)
 */
protected Queue resolveQueue(Session session, String queueName) throws JMSException {
	return session.createQueue(queueName);
}