javax.jms.MessageConsumer Java Examples

The following examples show how to use javax.jms.MessageConsumer. 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: AbstractPollingMessageListenerContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Execute the listener for a message received from the given consumer,
 * wrapping the entire operation in an external transaction if demanded.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doReceiveAndExecute
 */
protected boolean receiveAndExecute(
		Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer)
		throws JMSException {

	if (this.transactionManager != null) {
		// Execute receive within transaction.
		TransactionStatus status = this.transactionManager.getTransaction(this.transactionDefinition);
		boolean messageReceived;
		try {
			messageReceived = doReceiveAndExecute(invoker, session, consumer, status);
		}
		catch (JMSException | RuntimeException | Error ex) {
			rollbackOnException(this.transactionManager, status, ex);
			throw ex;
		}
		this.transactionManager.commit(status);
		return messageReceived;
	}

	else {
		// Execute receive outside of transaction.
		return doReceiveAndExecute(invoker, session, consumer, null);
	}
}
 
Example #2
Source File: ReceiveShipping.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   ConnectionFactory factory = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
   Destination destination = ActiveMQDestination.fromPrefixedName("queue://shipping");

   try (Connection conn = factory.createConnection()) {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);
      consumer.setMessageListener(new MessageListener() {
         @Override
         public void onMessage(Message message) {
            System.out.println("Received Message: ");
            Order order = Jms.getEntity(message, Order.class);
            System.out.println(order);
         }
      });
      conn.start();
      Thread.sleep(1000000);
   }
}
 
Example #3
Source File: StompTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageWithCustomHeadersAndSelector() throws Exception {

   MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'");

   conn.connect(defUser, defPass);

   ClientStompFrame frame = conn.createFrame(Stomp.Commands.SEND)
                                .addHeader(Stomp.Headers.Send.DESTINATION, getQueuePrefix() + getQueueName())
                                .addHeader("foo", "abc")
                                .addHeader("bar", "123")
                                .setBody("Hello World");
   conn.sendFrame(frame);

   TextMessage message = (TextMessage) consumer.receive(1000);
   Assert.assertNotNull(message);
   Assert.assertEquals("Hello World", message.getText());
   Assert.assertEquals("foo", "abc", message.getStringProperty("foo"));
   Assert.assertEquals("bar", "123", message.getStringProperty("bar"));
}
 
Example #4
Source File: JmsTempDestinationTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a temp queue does not drop message if there are no active
 * consumers.
 *
 * @throws JMSException
 */
@Test
public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException {

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createTemporaryQueue();
   MessageProducer producer = session.createProducer(queue);
   producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
   TextMessage message = session.createTextMessage("Hello");
   producer.send(message);

   connection.start();
   MessageConsumer consumer = session.createConsumer(queue);
   Message message2 = consumer.receive(3000);
   Assert.assertNotNull(message2);
   Assert.assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage);
   Assert.assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage) message2).getText().equals(message.getText()));

}
 
Example #5
Source File: JMXRemoveQueueThenSendIgnoredTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveQueueAndProduceBeforeNewConsumerAdded() throws Exception {
   MessageConsumer firstConsumer = registerConsumer();
   produceMessage();
   Message message = firstConsumer.receive(5000);
   LOG.info("Received message " + message);

   assertEquals(1, numberOfMessages());
   firstConsumer.close();
   session.commit();
   Thread.sleep(1000);

   removeQueue();
   Thread.sleep(1000);

   produceMessage();
   MessageConsumer secondConsumer = registerConsumer();
   message = secondConsumer.receive(5000);
   LOG.debug("Received message " + message);

   assertEquals(1, numberOfMessages());
   secondConsumer.close();
}
 
Example #6
Source File: MessageGroupTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testAddingConsumer() throws Exception {
   ActiveMQDestination destination = new ActiveMQQueue("TEST");

   // Setup a first connection
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

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

   TextMessage message = session.createTextMessage("message");
   message.setStringProperty("JMSXGroupID", "TEST-GROUP");

   LOG.info("sending message: " + message);
   producer.send(message);

   MessageConsumer consumer = session.createConsumer(destination);

   TextMessage msg = (TextMessage) consumer.receive();
   assertNotNull(msg);
   boolean first = msg.getBooleanProperty("JMSXGroupFirstForConsumer");
   assertTrue(first);
}
 
Example #7
Source File: CloseRollbackRedeliveryQueueTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testVerifyConsumerAndSessionCloseRedeliveryWithFailoverTransport() throws Throwable {
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   MessageConsumer consumer = session.createConsumer(destination);

   Message message = consumer.receive(1000);
   String id = message.getJMSMessageID();
   assertNotNull(message);
   LOG.info("got message " + message);
   consumer.close();
   session.close();
   session = connection.createSession(true, Session.SESSION_TRANSACTED);
   consumer = session.createConsumer(destination);

   message = consumer.receive(1000);
   session.commit();
   assertNotNull(message);
   assertEquals("redelivered message", id, message.getJMSMessageID());
   assertEquals(2, message.getLongProperty("JMSXDeliveryCount"));
}
 
Example #8
Source File: JMSConsumer2Test.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testDupsOkConsumer() throws Exception {

   // Receive a message with the JMS API
   connection.start();
   Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE);
   ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
   MessageConsumer consumer = session.createConsumer(destination);

   // Send the messages
   sendMessages(session, destination, 4);

   // Make sure only 4 message are delivered.
   for (int i = 0; i < 4; i++) {
      Message m = consumer.receive(1000);
      assertNotNull(m);
   }
   assertNull(consumer.receive(1000));

   // Close out the consumer.. no other messages should be left on the queue.
   consumer.close();

   consumer = session.createConsumer(destination);
   assertNull(consumer.receive(1000));
}
 
Example #9
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSelector() throws Exception {
   Connection consumerConnection = null;

   try {
      consumerConnection = createConnection();

      Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      String selector = "JMSType = 'something'";

      MessageConsumer topicConsumer = consumerSession.createConsumer(ActiveMQServerTestCase.topic1, selector);

      ProxyAssertSupport.assertEquals(selector, topicConsumer.getMessageSelector());
   } finally {
      if (consumerConnection != null) {
         consumerConnection.close();
      }
   }
}
 
Example #10
Source File: StompV11Test.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessage() throws Exception {
   MessageConsumer consumer = session.createConsumer(queue);

   conn.connect(defUser, defPass);

   send(conn, getQueuePrefix() + getQueueName(), null, "Hello World");

   TextMessage message = (TextMessage) consumer.receive(1000);
   Assert.assertNotNull(message);
   Assert.assertEquals("Hello World", message.getText());
   // Assert default priority 4 is used when priority header is not set
   Assert.assertEquals("getJMSPriority", 4, message.getJMSPriority());

   // Make sure that the timestamp is valid - should
   // be very close to the current time.
   long tnow = System.currentTimeMillis();
   long tmsg = message.getJMSTimestamp();
   Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);
}
 
Example #11
Source File: TopicDurableTests.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected List<CompletableFuture<List<Message>>> receiveMessagesAsync(int count, MessageConsumer... consumer) throws JMSException {
   AtomicInteger totalCount = new AtomicInteger(count);
   List<CompletableFuture<List<Message>>> resultsList = new ArrayList<>();
   List<List<Message>> receivedResList = new ArrayList<>();

   for (int i = 0; i < consumer.length; i++) {
      final int index = i;
      resultsList.add(new CompletableFuture<>());
      receivedResList.add(new ArrayList<>());
      MessageListener myListener = message -> {
         instanceLog.debug("Mesages received" + message + " count: " + totalCount.get());
         receivedResList.get(index).add(message);
         if (totalCount.decrementAndGet() == 0) {
            for (int j = 0; j < consumer.length; j++) {
               resultsList.get(j).complete(receivedResList.get(j));
            }
         }
      };
      consumer[i].setMessageListener(myListener);
   }
   return resultsList;
}
 
Example #12
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetQueue() throws Exception {
   Connection consumerConnection = null;

   try {
      consumerConnection = createConnection();

      Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageConsumer queueConsumer = consumerSession.createConsumer(queue1);

      Queue q = ((QueueReceiver) queueConsumer).getQueue();

      ProxyAssertSupport.assertEquals(queue1, q);
   } finally {
      if (consumerConnection != null) {
         consumerConnection.close();
      }
   }
}
 
Example #13
Source File: LoadClient.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected String consume() throws Exception {
   Connection con = null;
   MessageConsumer c = consumer;
   if (connectionPerMessage) {
      con = factory.createConnection();
      con.start();
      Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      c = s.createConsumer(getConsumeDestination());
   }
   TextMessage result = (TextMessage) c.receive(timeout);
   if (result != null) {
      if (audit.isDuplicate(result.getJMSMessageID())) {
         throw new JMSException("Received duplicate " + result.getText());
      }
      if (!audit.isInOrder(result.getJMSMessageID())) {
         throw new JMSException("Out of order " + result.getText());
      }

      if (connectionPerMessage) {
         Thread.sleep(SLEEP_TIME);//give the broker a chance
         con.close();
      }
   }
   return result != null ? result.getText() : null;
}
 
Example #14
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 #15
Source File: StompTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testJMSXGroupIdCanBeSet() throws Exception {
   final String jmsxGroupID = "JMSXGroupID";
   MessageConsumer consumer = session.createConsumer(queue);

   conn.connect(defUser, defPass);

   ClientStompFrame frame = conn.createFrame(Stomp.Commands.SEND)
                                .addHeader(Stomp.Headers.Send.DESTINATION, getQueuePrefix() + getQueueName())
                                .addHeader("JMSXGroupID", jmsxGroupID)
                                .setBody("Hello World");
   conn.sendFrame(frame);

   TextMessage message = (TextMessage) consumer.receive(1000);
   Assert.assertNotNull(message);
   Assert.assertEquals("Hello World", message.getText());
   // differ from StompConnect
   Assert.assertEquals(jmsxGroupID, message.getStringProperty("JMSXGroupID"));
}
 
Example #16
Source File: FailureXATest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void doTestCrashServerAfterXACommit(boolean onePhase) throws Exception {
   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
   XAConnection connection = connectionFactory.createXAConnection();

   try {
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      Queue queue = session.createQueue("Queue1");
      final XASession xaSession = connection.createXASession();
      MessageConsumer consumer = xaSession.createConsumer(queue);

      MessageProducer producer = session.createProducer(queue);
      producer.send(session.createTextMessage("hello " + 1));
      session.commit();

      XAResource xaResource = xaSession.getXAResource();
      final Xid xid = newXID();
      xaResource.start(xid, XAResource.TMNOFLAGS);

      connection.start();
      Assert.assertNotNull(consumer.receive(5000));

      xaResource.end(xid, XAResource.TMSUCCESS);

      try {
         xaResource.commit(xid, onePhase);
         Assert.fail("didn't get expected exception!");
      } catch (XAException xae) {
         if (onePhase) {
            //expected error code is XAER_RMFAIL
            Assert.assertEquals(XAException.XAER_RMFAIL, xae.errorCode);
         } else {
            //expected error code is XA_RETRY
            Assert.assertEquals(XAException.XA_RETRY, xae.errorCode);
         }
      }
   } finally {
      connection.close();
   }
}
 
Example #17
Source File: ThreeBrokerTopicNetworkTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * BrokerA -> BrokerB <- BrokerC
 */
public void testABandCBbrokerNetwork() throws Exception {
   // Setup broker networks
   bridgeBrokers("BrokerA", "BrokerB");
   bridgeBrokers("BrokerC", "BrokerB");

   startAllBrokers();

   // Setup destination
   Destination dest = createDestination("TEST.FOO", true);

   // Setup consumers
   MessageConsumer clientA = createConsumer("BrokerA", dest);
   MessageConsumer clientB = createConsumer("BrokerB", dest);
   MessageConsumer clientC = createConsumer("BrokerC", dest);

   //let consumers propagate around the network
   Thread.sleep(2000);

   // Send messages
   sendMessages("BrokerA", dest, MESSAGE_COUNT);
   sendMessages("BrokerB", dest, MESSAGE_COUNT);
   sendMessages("BrokerC", dest, MESSAGE_COUNT);

   // Get message count
   MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
   MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
   MessageIdList msgsC = getConsumerMessages("BrokerC", clientC);

   msgsA.waitForMessagesToArrive(MESSAGE_COUNT);
   msgsB.waitForMessagesToArrive(MESSAGE_COUNT * 3);
   msgsC.waitForMessagesToArrive(MESSAGE_COUNT);

   assertEquals(MESSAGE_COUNT, msgsA.getMessageCount());
   assertEquals(MESSAGE_COUNT * 3, msgsB.getMessageCount());
   assertEquals(MESSAGE_COUNT, msgsC.getMessageCount());
}
 
Example #18
Source File: JmsMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncReceiveWithoutExpirationChecks() throws Exception {
   ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
   factory.setConsumerExpiryCheckEnabled(false);

   final CountDownLatch received = new CountDownLatch(1);

   Connection connection = factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Destination destination = session.createQueue(name.getMethodName());
   MessageConsumer consumer = session.createConsumer(destination);
   consumer.setMessageListener(new MessageListener() {

      @Override
      public void onMessage(Message message) {
         received.countDown();
      }
   });
   MessageProducer producer = session.createProducer(destination);
   producer.setTimeToLive(TimeUnit.SECONDS.toMillis(2));

   producer.send(session.createTextMessage("test"));

   // Allow message to expire in the prefetch buffer
   TimeUnit.SECONDS.sleep(4);
   connection.start();

   assertTrue(received.await(5, TimeUnit.SECONDS));
   connection.close();
}
 
Example #19
Source File: SecurityExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void checkUserReceiveNoSend(final Topic topic,
                                           final Connection connection,
                                           final String user,
                                           final Connection sendingConn) throws JMSException {
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(topic);
   MessageConsumer consumer = session.createConsumer(topic);
   TextMessage msg = session.createTextMessage("hello-world-1");

   try {
      producer.send(msg);
      throw new IllegalStateException("Security setting is broken! User " + user +
                                         " can send message [" +
                                         msg.getText() +
                                         "] to topic " +
                                         topic);
   } catch (JMSException e) {
      System.out.println("User " + user + " cannot send message [" + msg.getText() + "] to topic: " + topic);
   }

   // Now send a good message
   Session session1 = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   producer = session1.createProducer(topic);
   producer.send(msg);

   TextMessage receivedMsg = (TextMessage) consumer.receive(2000);

   if (receivedMsg != null) {
      System.out.println("User " + user + " can receive message [" + receivedMsg.getText() + "] from topic " + topic);
   } else {
      throw new IllegalStateException("Security setting is broken! User " + user + " cannot receive message from topic " + topic);
   }

   session1.close();
   session.close();
}
 
Example #20
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testJMSSelectorFiltersJMSMessageIDOnTopic() throws Exception {
   Connection connection = createConnection();

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      javax.jms.Queue queue = session.createQueue(getQueueName());
      MessageProducer producer = session.createProducer(queue);

      // Send one to receive
      TextMessage message = session.createTextMessage();
      producer.send(message);

      // Send another to filter
      producer.send(session.createTextMessage());

      connection.start();

      // First one should make it through
      MessageConsumer messageConsumer = session.createConsumer(queue, "JMSMessageID = '" + message.getJMSMessageID() + "'");
      TextMessage m = (TextMessage) messageConsumer.receive(5000);
      assertNotNull(m);
      assertEquals(message.getJMSMessageID(), m.getJMSMessageID());

      // The second one should not be received.
      assertNull(messageConsumer.receive(1000));
   } finally {
      connection.close();
   }
}
 
Example #21
Source File: JMSConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testMessageListenerWithConsumer() throws Exception {

      final AtomicInteger counter = new AtomicInteger(0);
      final CountDownLatch done = new CountDownLatch(1);

      // Receive a message with the JMS API
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destination = createDestination(session, destinationType);
      MessageConsumer consumer = session.createConsumer(destination);
      consumer.setMessageListener(new MessageListener() {
         @Override
         public void onMessage(Message m) {
            counter.incrementAndGet();
            if (counter.get() == 4) {
               done.countDown();
            }
         }
      });

      // Send the messages
      sendMessages(session, destination, 4);

      assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
      Thread.sleep(200);

      // Make sure only 4 messages were delivered.
      assertEquals(4, counter.get());
   }
 
Example #22
Source File: JmsMultipleBrokersTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public MessageConsumer createDurableSubscriber(Topic dest, Session sess, String name) throws Exception {
   MessageConsumer client = sess.createDurableSubscriber(dest, name);
   MessageIdList messageIdList = new MessageIdList();
   messageIdList.setParent(allMessages);
   client.setMessageListener(messageIdList);
   consumers.put(client, messageIdList);

   return client;
}
 
Example #23
Source File: SslTransportTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({ "broker-ssl-port"})
@Test
public void testConsumerProducerWithSsl(String port) throws Exception {
    String queueName = "testConsumerProducerWithAutoAck";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .enableSsl()
            .withQueue(queueName)
            .build();

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

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

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

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

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(1000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
Example #24
Source File: TempQueueWithDotTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testSimple(String protocol) throws Exception {
   ConnectionFactory factory = CFUtil.createConnectionFactory(protocol, getConnectionUrl());
   Connection connection = factory.createConnection();
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue dest = session.createTemporaryQueue();
      String queueName = dest.getQueueName();
      Wait.waitFor(() -> server.locateQueue(queueName) != null);
      org.apache.activemq.artemis.core.server.Queue queue = server.locateQueue(queueName);
      MessageConsumer consumer = null;
      try {
         consumer = session.createConsumer(dest);
      } catch (Exception e) {
         e.printStackTrace();
         // I'm calling fail because openwire sends the stacktrace for the server, not the client in case of a failure
         fail(e.getMessage());
      }

      MessageProducer producer = session.createProducer(dest);
      producer.send(session.createTextMessage("hello"));

      Wait.assertEquals(1, queue::getMessageCount);

      connection.start();

      Assert.assertNotNull(consumer.receive(500));
   } finally {
      connection.close();
   }
}
 
Example #25
Source File: JMSConnectionHandlingActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Nullable
private ConsumerData createJmsConsumer(final Session session, final Map<String, Exception> failedSources,
        final Source source, final String sourceAddress, final String addressWithIndex) {
    log.debug("Creating AMQP Consumer for <{}>", addressWithIndex);
    final Destination destination = new JmsQueue(sourceAddress);
    final MessageConsumer messageConsumer;
    try {
        messageConsumer = session.createConsumer(destination);
        return ConsumerData.of(source, sourceAddress, addressWithIndex, messageConsumer);
    } catch (final JMSException jmsException) {
        failedSources.put(addressWithIndex, jmsException);
        return null;
    }
}
 
Example #26
Source File: JMSDurableConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testDurableConsumerSync() throws Exception {
   String durableClientId = getTopicName() + "-ClientId";

   Connection connection = createConnection(durableClientId);
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic(getTopicName());
      final MessageConsumer consumer = session.createDurableSubscriber(topic, "DurbaleTopic");
      MessageProducer producer = session.createProducer(topic);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      connection.start();

      TextMessage message = session.createTextMessage();
      message.setText("hello");
      producer.send(message);

      final AtomicReference<Message> msg = new AtomicReference<>();
      assertTrue(Wait.waitFor(new Wait.Condition() {

         @Override
         public boolean isSatisfied() throws Exception {
            msg.set(consumer.receiveNoWait());
            return msg.get() != null;
         }
      }, TimeUnit.SECONDS.toMillis(25), TimeUnit.MILLISECONDS.toMillis(200)));

      assertNotNull("Should have received a message by now.", msg.get());
      assertTrue("Should be an instance of TextMessage", msg.get() instanceof TextMessage);
   } finally {
      connection.close();
   }
}
 
Example #27
Source File: AutoCreateQueueClusterTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoCreate() throws Exception {
   server1.getAddressSettingsRepository().getMatch("#").setAutoCreateQueues(true).setAutoCreateAddresses(true).setRedistributionDelay(0);
   server2.getAddressSettingsRepository().getMatch("#").setAutoCreateQueues(true).setAutoCreateAddresses(true).setRedistributionDelay(0);
   Connection conn1 = cf1.createConnection();
   Connection conn2 = cf2.createConnection();
   conn1.start();
   conn2.start();

   try {
      Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer prod1 = session1.createProducer(ActiveMQJMSClient.createQueue("myQueue"));

      prod1.setDeliveryMode(DeliveryMode.PERSISTENT);

      prod1.send(session1.createTextMessage("m1"));

      MessageConsumer cons2 = session2.createConsumer(ActiveMQJMSClient.createQueue("myQueue"));

      TextMessage received = (TextMessage) cons2.receive(5000);

      assertNotNull(received);

      assertEquals("m1", received.getText());

      cons2.close();
   } finally {
      conn1.close();
      conn2.close();
   }
}
 
Example #28
Source File: ObjectMessageTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetObjectPropertyForShort() throws Exception
{
    Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ObjectMessage msg = session.createObjectMessage("test");
        msg.setObjectProperty("TestShortProperty", Short.MAX_VALUE);
        assertEquals(Short.MAX_VALUE, msg.getObjectProperty("TestShortProperty"));
        MessageProducer producer = session.createProducer(queue);
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(queue);
        connection.start();
        Message receivedMessage = consumer.receive(getReceiveTimeout());

        assertTrue("ObjectMessage should be received", receivedMessage instanceof ObjectMessage);
        assertEquals("Unexpected received property",
                     Short.MAX_VALUE,
                     receivedMessage.getObjectProperty("TestShortProperty"));
    }
    finally
    {
        connection.close();
    }
}
 
Example #29
Source File: JmsDestinationAccessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Actually receive a message from the given consumer.
 * @param consumer the JMS MessageConsumer to receive with
 * @param timeout the receive timeout (a negative value indicates
 * a no-wait receive; 0 indicates an indefinite wait attempt)
 * @return the JMS Message received, or {@code null} if none
 * @throws JMSException if thrown by JMS API methods
 * @since 4.3
 * @see #RECEIVE_TIMEOUT_NO_WAIT
 * @see #RECEIVE_TIMEOUT_INDEFINITE_WAIT
 */
@Nullable
protected Message receiveFromConsumer(MessageConsumer consumer, long timeout) throws JMSException {
	if (timeout > 0) {
		return consumer.receive(timeout);
	}
	else if (timeout < 0) {
		return consumer.receiveNoWait();
	}
	else {
		return consumer.receive();
	}
}
 
Example #30
Source File: SimpleMessageListenerContainerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetToFalse() throws Exception {
	MessageConsumer messageConsumer = mock(MessageConsumer.class);
	Session session = mock(Session.class);
	// Queue gets created in order to create MessageConsumer for that Destination...
	given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION);
	// and then the MessageConsumer gets created...
	given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);  // no MessageSelector...

	Connection connection = mock(Connection.class);
	// session gets created in order to register MessageListener...
	given(connection.createSession(this.container.isSessionTransacted(),
			this.container.getSessionAcknowledgeMode())).willReturn(session);

	ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	given(connectionFactory.createConnection()).willReturn(connection);

	this.container.setConnectionFactory(connectionFactory);
	this.container.setDestinationName(DESTINATION_NAME);

	this.container.setMessageListener(new TestMessageListener());
	this.container.setAutoStartup(false);
	this.container.afterPropertiesSet();
	GenericApplicationContext context = new GenericApplicationContext();
	context.getBeanFactory().registerSingleton("messageListenerContainer", this.container);
	context.refresh();

	verify(connection).setExceptionListener(this.container);
}