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

The following examples show how to use javax.jms.Session#createConsumer() . 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: JmsInvokerClientInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Actually execute the given request, sending the invoker request message
 * to the specified target queue and waiting for a corresponding response.
 * <p>The default implementation is based on standard JMS send/receive,
 * using a {@link javax.jms.TemporaryQueue} for receiving the response.
 * @param session the JMS Session to use
 * @param queue the resolved target Queue to send to
 * @param requestMessage the JMS Message to send
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 */
protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException {
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	try {
		responseQueue = session.createTemporaryQueue();
		producer = session.createProducer(queue);
		consumer = session.createConsumer(responseQueue);
		requestMessage.setJMSReplyTo(responseQueue);
		producer.send(requestMessage);
		long timeout = getReceiveTimeout();
		return (timeout > 0 ? consumer.receive(timeout) : consumer.receive());
	}
	finally {
		JmsUtils.closeMessageConsumer(consumer);
		JmsUtils.closeMessageProducer(producer);
		if (responseQueue != null) {
			responseQueue.delete();
		}
	}
}
 
Example 2
Source File: TestJmsTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private List<String> getQueue() throws Exception {
  List<String> rows = new ArrayList<>();

  Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
  Destination destination = session.createQueue(DESTINATION_NAME);
  MessageConsumer consumer = session.createConsumer(destination);

  Message temp;
  while((temp = consumer.receive(100)) != null) {
    if(temp instanceof BytesMessage) {
      BytesMessage message = (BytesMessage) temp;
      byte[] payload = new byte[(int) message.getBodyLength()];
      message.readBytes(payload);
      rows.add(new String(payload) + RECORD_SEPERATOR);
    } else if(temp instanceof TextMessage) {
      rows.add(((TextMessage) temp).getText());
    } else {
      throw new Exception("Unexpected message type");
    }
  }

  return rows;
}
 
Example 3
Source File: JmsAutoAckListenerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAckedMessageAreConsumed() throws Exception {
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(queueName);
   MessageProducer producer = session.createProducer(queue);
   producer.send(session.createTextMessage("Hello"));

   // Consume the message...
   MessageConsumer consumer = session.createConsumer(queue);
   consumer.setMessageListener(this);

   latch.await(10, TimeUnit.SECONDS);
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   // Attempt to Consume the message...check if message was acknowledge
   consumer = session.createConsumer(queue);
   Message msg = consumer.receive(1000);
   assertNull(msg);

   session.close();
}
 
Example 4
Source File: AutoAckMessageListenerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoAckMsgListenerQueue() throws Exception {
   Connection conn = null;

   try {
      CountDownLatch latch = new CountDownLatch(1);

      conn = createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(queue1);
      MessageConsumer consumer = session.createConsumer(queue1);
      AutoAckMsgListener listener = new AutoAckMsgListener(latch, session);
      consumer.setMessageListener(listener);

      // create and send messages
      log.debug("Send and receive two message");
      Message messageSent = session.createMessage();
      messageSent.setBooleanProperty("last", false);
      producer.send(messageSent);
      messageSent.setBooleanProperty("last", true);
      producer.send(messageSent);

      conn.start();

      // wait until message is received
      log.debug("waiting until message has been received by message listener...");
      latch.await(10, TimeUnit.SECONDS);

      // check message listener status
      if (listener.getPassed() == false) {
         throw new Exception("failed");
      }
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 5
Source File: MessageIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void receivedMessageWithCorrelationIdTestImpl(Object underlyingCorrelationId, String expected) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

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

        PropertiesDescribedType props = new PropertiesDescribedType();
        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        props.setMessageId("myMessageIdString");
        props.setCorrelationId(underlyingCorrelationId);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, props, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(3000);

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

        testPeer.waitForAllHandlersToComplete(3000);

        assertNotNull(receivedMessage);

        assertEquals(expected, receivedMessage.getJMSCorrelationID());
    }
}
 
Example 6
Source File: JMSLVQTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void receiveLVQ(ConnectionSupplier consumerConnectionSupplier, String queueName, String lastValueKey) throws JMSException {
   try (Connection consumerConnection = consumerConnectionSupplier.createConnection()) {

      Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue consumerQueue = consumerSession.createQueue(queueName);
      MessageConsumer consumer = consumerSession.createConsumer(consumerQueue);
      TextMessage msg = (TextMessage) consumer.receive(1000);
      assertNotNull(msg);
      assertEquals("KEY", msg.getStringProperty(lastValueKey));
      assertEquals("how are you", msg.getText());
      consumer.close();
   }
}
 
Example 7
Source File: JmsTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a JMS MessageConsumer for the given Session and Destination.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to create a MessageConsumer for
 * @param destination the JMS Destination to create a MessageConsumer for
 * @param messageSelector the message selector for this consumer (can be {@code null})
 * @return the new JMS MessageConsumer
 * @throws JMSException if thrown by JMS API methods
 */
protected MessageConsumer createConsumer(Session session, Destination destination, @Nullable String messageSelector)
		throws JMSException {

	// Only pass in the NoLocal flag in case of a Topic:
	// Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException
	// in case of the NoLocal flag being specified for a Queue.
	if (isPubSubDomain()) {
		return session.createConsumer(destination, messageSelector, isPubSubNoLocal());
	}
	else {
		return session.createConsumer(destination, messageSelector);
	}
}
 
Example 8
Source File: TemporaryQueueTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosingConsumerDoesNotDeleteQueue() throws Exception
{
    final Connection connection = getConnection();
    try
    {
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final TemporaryQueue queue = session.createTemporaryQueue();
        assertNotNull("Temporary queue cannot be null", queue);

        MessageProducer producer = session.createProducer(queue);
        String messageText = "Hello World!";
        producer.send(session.createTextMessage(messageText));

        connection.start();
        session.createConsumer(queue).close();

        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(getReceiveTimeout());
        assertTrue("Received message not a text message", message instanceof TextMessage);
        assertEquals("Incorrect message text", messageText, ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example 9
Source File: ConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a message is received when calling receive with a timeout
 * of 0, which means wait indefinitely.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test(timeout = 20000)
public void testReceiveMessageWithReceiveZeroTimeout() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

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

        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(0);

        assertNotNull("A message should have been recieved", receivedMessage);

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

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 10
Source File: PersistentMessagingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void transactedAcknowledgementPersistence() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection initialConnection = getConnection();
    List<Message> remainingMessages = new ArrayList<>();
    try
    {
        initialConnection.start();
        Session session = initialConnection.createSession(true, SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(queue);

        final List<Message> initialMessage = sendMessages(session, producer, PERSISTENT, 0, 1);
        remainingMessages.addAll(sendMessages(session, producer, PERSISTENT, 1, 1));

        // Receive first message and commit
        MessageConsumer consumer = session.createConsumer(queue);
        receiveAndVerifyMessages(session, consumer, initialMessage);
        // Receive second message but do not commit
        final Message peek = consumer.receive(getReceiveTimeout());
        assertNotNull(peek);
    }
    finally
    {
        initialConnection.close();
    }

    getBrokerAdmin().restart();

    verifyQueueContents(queue, remainingMessages);
}
 
Example 11
Source File: ActiveMQEc2LiveTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private int clearQueue(Connection connection, String queueName) throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    org.apache.activemq.command.ActiveMQQueue destination = (org.apache.activemq.command.ActiveMQQueue) session.createQueue(queueName);
    MessageConsumer messageConsumer = session.createConsumer(destination);

    int received = 0;
    while (messageConsumer.receive(500) != null) received++;

    session.close();

    return received;
}
 
Example 12
Source File: DtxCommitPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if committing a published message works correctly.Steps are,
 *    1. Using a distributed transaction a message is published to a queue and committed
 *    2. Subscribe to the published queue and see if the message is received.
 */
@Test(groups = { "wso2.mb", "dtx" })
public void performClientQueuePublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "CommitTestCasePerformClientQueuePublishTestCase";

    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.TMSUCCESS);

    int ret = xaResource.prepare(xid);
    Assert.assertEquals(ret, XAResource.XA_OK, "Dtx.prepare was not successful.");

    xaResource.commit(xid, false);

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

    // 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.assertNotNull(receive, "Message was not received.");

    queueConnection.close();
}
 
Example 13
Source File: TemporaryJMSQueueClusterTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testDuplicateCacheCleanupForTempQueues() throws Exception {
   setupServer(0, isFileStorage(), isNetty());
   setupServer(1, isFileStorage(), isNetty());

   setupClusterConnection("cluster0", "", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), 0, 1);
   servers[0].getConfiguration().getClusterConfigurations().get(0).setDuplicateDetection(true);
   servers[0].getAddressSettingsRepository().addMatch("#", new AddressSettings().setRedistributionDelay(0));

   setupClusterConnection("cluster1", "", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), 1, 0);
   servers[1].getConfiguration().getClusterConfigurations().get(0).setDuplicateDetection(true);
   servers[1].getAddressSettingsRepository().addMatch("#", new AddressSettings().setRedistributionDelay(0));

   startServers(0, 1);

   final Map<String, TextMessage> requestMap = new HashMap<>();
   ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");

   for (int j = 0; j < 10; j++) {
      try (Connection connection = cf.createConnection()) {
         SimpleMessageListener server = new SimpleMessageListener().start();
         Queue requestQueue = ActiveMQJMSClient.createQueue("exampleQueue");
         connection.start();
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         MessageProducer producer = session.createProducer(requestQueue);
         TemporaryQueue replyQueue = session.createTemporaryQueue();
         MessageConsumer replyConsumer = session.createConsumer(replyQueue);

         int numMessages = 10;
         for (int i = 0; i < numMessages; i++) {

            TextMessage requestMsg = session.createTextMessage("A request message");
            requestMsg.setJMSReplyTo(replyQueue);
            producer.send(requestMsg);
            requestMap.put(requestMsg.getJMSMessageID(), requestMsg);
         }

         for (int i = 0; i < numMessages; i++) {
            TextMessage replyMessageReceived = (TextMessage) replyConsumer.receive();
            assertNotNull(requestMap.get(replyMessageReceived.getJMSCorrelationID()));
         }

         replyConsumer.close();
         replyQueue.delete();
         server.shutdown();
      }

   }

   assertTrue(((PostOfficeImpl) servers[0].getPostOffice()).getDuplicateIDCaches().size() <= 1);
   assertTrue(((PostOfficeImpl) servers[1].getPostOffice()).getDuplicateIDCaches().size() <= 1);

}
 
Example 14
Source File: VirtualTopicToFQQNOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testTwoTopicSubsSameNameAutoVirtualTopicFQQN() throws Exception {
   Connection connection = null;

   SimpleString topic1 = new SimpleString("VirtualTopic.Orders1");
   SimpleString topic2 = new SimpleString("VirtualTopic.Orders2");

   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateQueues(true);
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateAddresses(true);

   try {
      ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(urlString);
      activeMQConnectionFactory.setWatchTopicAdvisories(false);
      connection = activeMQConnectionFactory.createConnection();
      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination1 = session.createTopic(topic1.toString());
      Destination destination2 = session.createTopic(topic2.toString());

      MessageConsumer messageConsumer1 = session.createConsumer(session.createQueue("Consumer.A." + topic1.toString()));
      MessageConsumer messageConsumer2 = session.createConsumer(session.createQueue("Consumer.A." + topic2.toString()));

      MessageProducer producer = session.createProducer(null);
      TextMessage message = session.createTextMessage("This is a text message to 1");
      producer.send(destination1, message);
      message = session.createTextMessage("This is a text message to 2");
      producer.send(destination2, message);


      TextMessage messageReceived1 = (TextMessage) messageConsumer1.receive(2000);
      TextMessage messageReceived2 = (TextMessage) messageConsumer2.receive(2000);

      assertNotNull(messageReceived1);
      assertNotNull(messageReceived2);

      String text = messageReceived1.getText();
      assertEquals("This is a text message to 1", text);

      text = messageReceived2.getText();
      assertEquals("This is a text message to 2", text);

      messageConsumer1.close();
      messageConsumer2.close();

   } finally {
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 15
Source File: PriorityQueueTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testOddOrdering() throws Exception
{
    final Queue queue = createPriorityQueue(getTestName(), 3);
    final Connection producerConnection = getConnection();
    try
    {
        final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
        final MessageProducer producer = producerSession.createProducer(queue);

        // In order ABC
        producer.setPriority(9);
        producer.send(nextMessage(producerSession, 1));
        producer.setPriority(4);
        producer.send(nextMessage(producerSession, 2));
        producer.setPriority(1);
        producer.send(nextMessage(producerSession, 3));

        // Out of order BAC
        producer.setPriority(4);
        producer.send(nextMessage(producerSession, 4));
        producer.setPriority(9);
        producer.send(nextMessage(producerSession, 5));
        producer.setPriority(1);
        producer.send(nextMessage(producerSession, 6));

        // Out of order BCA
        producer.setPriority(4);
        producer.send(nextMessage(producerSession, 7));
        producer.setPriority(1);
        producer.send(nextMessage(producerSession, 8));
        producer.setPriority(9);
        producer.send(nextMessage(producerSession, 9));

        // Reverse order CBA
        producer.setPriority(1);
        producer.send(nextMessage(producerSession, 10));
        producer.setPriority(4);
        producer.send(nextMessage(producerSession, 11));
        producer.setPriority(9);
        producer.send(nextMessage(producerSession, 12));
        producerSession.commit();
    }
    finally
    {
        producerConnection.close();
    }

    final Connection consumerConnection = getConnection();
    try
    {
        final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MessageConsumer consumer = consumerSession.createConsumer(queue);
        consumerConnection.start();

        Message msg = consumer.receive(getReceiveTimeout());
        assertEquals(1, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(5, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(9, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(12, msg.getIntProperty("msg"));

        msg = consumer.receive(getReceiveTimeout());
        assertEquals(2, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(4, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(7, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(11, msg.getIntProperty("msg"));

        msg = consumer.receive(getReceiveTimeout());
        assertEquals(3, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(6, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(8, msg.getIntProperty("msg"));
        msg = consumer.receive(getReceiveTimeout());
        assertEquals(10, msg.getIntProperty("msg"));
    }
    finally
    {
        consumerConnection.close();
    }
}
 
Example 16
Source File: RedeployTempTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRedeployAddressQueueOpenWire() throws Exception {
   Path brokerXML = getTestDirfile().toPath().resolve("broker.xml");
   URL url1 = RedeployTest.class.getClassLoader().getResource("RedeployTempTest-reload-temp.xml");
   URL url2 = RedeployTest.class.getClassLoader().getResource("RedeployTempTest-reload-temp-updated.xml");
   Files.copy(url1.openStream(), brokerXML);

   EmbeddedActiveMQ embeddedActiveMQ = new EmbeddedActiveMQ();
   embeddedActiveMQ.setConfigResourcePath(brokerXML.toUri().toString());
   embeddedActiveMQ.start();

   final ReusableLatch latch = new ReusableLatch(1);

   Runnable tick = latch::countDown;

   embeddedActiveMQ.getActiveMQServer().getReloadManager().setTick(tick);

   ConnectionFactory connectionFactory = new org.apache.activemq.ActiveMQConnectionFactory();
   Connection connection = connectionFactory.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Destination destination = session.createQueue("queue");
   MessageProducer messageProducer = session.createProducer(destination);

   Destination replyTo = session.createTemporaryQueue();
   Message message = session.createTextMessage("hello");
   message.setJMSReplyTo(replyTo);
   messageProducer.send(message);

   try {
      latch.await(10, TimeUnit.SECONDS);

      Files.copy(url2.openStream(), brokerXML, StandardCopyOption.REPLACE_EXISTING);
      brokerXML.toFile().setLastModified(System.currentTimeMillis() + 1000);
      latch.setCount(1);
      embeddedActiveMQ.getActiveMQServer().getReloadManager().setTick(tick);
      latch.await(10, TimeUnit.SECONDS);

      try (Connection connectionConsumer = connectionFactory.createConnection()) {
         connectionConsumer.start();
         try (Session sessionConsumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
            Destination destinationConsumer = session.createQueue("queue");
            MessageConsumer messageConsumer = sessionConsumer.createConsumer(destinationConsumer);

            Message receivedMessage = messageConsumer.receive(1000);
            assertEquals("hello", ((TextMessage) receivedMessage).getText());

            Destination replyToDest = receivedMessage.getJMSReplyTo();
            Message message1 = sessionConsumer.createTextMessage("hi there");

            session.createProducer(replyToDest).send(message1);
         }
      }

      MessageConsumer messageConsumerProducer = session.createConsumer(replyTo);
      Message message2 = messageConsumerProducer.receive(1000);
      Assert.assertNotNull(message2);
      assertEquals("hi there", ((TextMessage) message2).getText());

   } finally {
      connection.close();
      embeddedActiveMQ.stop();
   }
}
 
Example 17
Source File: ConsumerPriorityTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
@Test
public void testLowPriorityConsumerReceiveMessagesIfHigherPriorityConsumerDoesNotSelect() throws Exception
{
    assumeThat("Only legacy client implements this feature", getProtocol(), is(not(equalTo(Protocol.AMQP_1_0))));

    final String queueName = getTestName();
    final Queue queue = createQueue(queueName);
    Connection consumingConnection = getConnection();
    try
    {
        Connection producingConnection = getConnectionBuilder().setSyncPublish(true).build();
        try
        {
            Session consumingSession = consumingConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            consumingConnection.start();

            Session producingSession = producingConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            final Queue consumerDestination =
                    consumingSession.createQueue(String.format(LEGACY_BINDING_URL, queueName, queueName, 10));
            final MessageConsumer consumer = consumingSession.createConsumer(consumerDestination);
            assertNull("There should be no messages in the queue", consumer.receive(getShortReceiveTimeout()));

            final Connection secondConsumingConnection = getConnection();
            try
            {
                final Session secondConsumingSession =
                        secondConsumingConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                secondConsumingConnection.start();
                final MessageConsumer standardPriorityConsumer =
                        secondConsumingSession.createConsumer(queue,
                                                              "msg <> 2");
                assertNull("There should be no messages in the queue", standardPriorityConsumer.receive(
                        getShortReceiveTimeout()));

                final MessageProducer producer = producingSession.createProducer(queue);

                producer.send(createTextMessage(1, producingSession));
                assertNull("Message should not go to the low priority consumer", consumer.receive(
                        getShortReceiveTimeout()));
                producer.send(createTextMessage(2, producingSession));
                Message message = consumer.receive(getReceiveTimeout());
                assertNotNull(
                        "Message should go to the low priority consumer as standard priority consumer is not interested",
                        message);
                assertTrue("Message is not a text message", message instanceof TextMessage);
                assertEquals(getTestName() + " 2", ((TextMessage) message).getText());
            }
            finally
            {
                secondConsumingConnection.close();
            }
        }
        finally
        {
            producingConnection.close();
        }
    }
    finally
    {
        consumingConnection.close();
    }
}
 
Example 18
Source File: BytesMessageIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doReceiveBasicBytesMessageUsingDataSectionTestImpl(Symbol contentType, boolean typeAnnotation) throws JMSException, InterruptedException, Exception, IOException {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        connection.start();

        testPeer.expectBegin();

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

        PropertiesDescribedType properties = new PropertiesDescribedType();
        properties.setContentType(contentType);

        MessageAnnotationsDescribedType msgAnnotations = null;
        if (typeAnnotation) {
            msgAnnotations = new MessageAnnotationsDescribedType();
            msgAnnotations.setSymbolKeyedAnnotation(AmqpMessageSupport.JMS_MSG_TYPE.toString(), AmqpMessageSupport.JMS_BYTES_MESSAGE);
        }

        final byte[] expectedContent = "expectedContent".getBytes();
        DescribedType dataContent = new DataDescribedType(new Binary(expectedContent));

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, msgAnnotations, properties, null, dataContent);
        testPeer.expectDispositionThatIsAcceptedAndSettled();

        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message receivedMessage = messageConsumer.receive(3000);
        testPeer.waitForAllHandlersToComplete(3000);

        assertNotNull(receivedMessage);
        assertTrue(receivedMessage instanceof BytesMessage);
        BytesMessage bytesMessage = (BytesMessage) receivedMessage;
        assertEquals(expectedContent.length, bytesMessage.getBodyLength());
        byte[] recievedContent = new byte[expectedContent.length];
        int readBytes = bytesMessage.readBytes(recievedContent);
        assertEquals(recievedContent.length, readBytes);
        assertTrue(Arrays.equals(expectedContent, recievedContent));

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

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example 19
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRedel0() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();
      conn.start();

      Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageProducer prod = sess.createProducer(queue1);
      TextMessage tm1 = sess.createTextMessage("a");
      TextMessage tm2 = sess.createTextMessage("b");
      TextMessage tm3 = sess.createTextMessage("c");
      prod.send(tm1);
      prod.send(tm2);
      prod.send(tm3);
      sess.commit();

      MessageConsumer cons1 = sess.createConsumer(queue1);

      TextMessage rm1 = (TextMessage) cons1.receive();
      ProxyAssertSupport.assertNotNull(rm1);
      ProxyAssertSupport.assertEquals("a", rm1.getText());

      cons1.close();

      MessageConsumer cons2 = sess.createConsumer(queue1);

      sess.commit();

      TextMessage rm2 = (TextMessage) cons2.receive(1500);
      ProxyAssertSupport.assertNotNull(rm2);
      ProxyAssertSupport.assertEquals("b", rm2.getText());

      TextMessage rm3 = (TextMessage) cons2.receive(1500);
      ProxyAssertSupport.assertNotNull(rm3);
      ProxyAssertSupport.assertEquals("c", rm3.getText());

      sess.commit();
   } finally {
      if (conn != null) {
         conn.close();
      }

      checkEmpty(queue1);

      removeAllMessages(queue1.getQueueName(), true);
   }
}
 
Example 20
Source File: DeadLetterChannelTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({ "broker-hostname", "broker-port", "admin-username", "admin-password" })
@Test
public void testDlcWithBasicRecover(String brokerHostname,
                                    String port,
                                    String adminUsername,
                                    String adminPassword) throws Exception {
    String queueName = "testDlcWithBasicRecover";
    String dlcQueueName = "amq.dlq";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .withQueue(dlcQueueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish message
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    producer.send(producerSession.createTextMessage("Message for DLC test"));
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int iteration = 0; iteration < 6; iteration++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message was not received");
        subscriberSession.recover();
    }

    Connection dlcConsumerConnection = connectionFactory.createConnection();
    dlcConsumerConnection.start();
    Session dlcConsumerSession = dlcConsumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer dlcConsumer = dlcConsumerSession.createConsumer((Destination) initialContextForQueue.lookup(
            dlcQueueName));

    Message dlcMessage = dlcConsumer.receive(5000);
    Assert.assertNotNull(dlcMessage, "Dead lettered message was not received" + dlcMessage);
    String originQueue = dlcMessage.getStringProperty("x-origin-queue");
    Assert.assertEquals(originQueue, queueName, "Origin queue name did not match" + dlcMessage);
    String originExchange = dlcMessage.getStringProperty("x-origin-exchange");
    Assert.assertEquals(originExchange, "amq.direct", "Origin exchange name did not match" + dlcMessage);
    String originRoutingKey = dlcMessage.getStringProperty("x-origin-routing-key");
    Assert.assertEquals(originRoutingKey, queueName, "Origin routing key did not match" + dlcMessage);

    dlcConsumerConnection.close();
    connection.close();
}