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

The following examples show how to use javax.jms.Session#createTextMessage() . 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: RecieverMDB.java    From tutorials with MIT License 6 votes vote down vote up
private void acknowledge(String text) throws JMSException {

        Connection connection = null;
        Session session = null;

        try {
            connection = connectionFactory.createConnection();
            connection.start();

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

            MessageProducer ackSender = session.createProducer(ackQueue);
            ackSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

            TextMessage message = session.createTextMessage(text);

            ackSender.send(message);
        } finally {
            session.close();
            connection.close();
        }
    }
 
Example 2
Source File: ConcurrentProducerQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected TextMessage createTextMessage(Session session, String initText) throws Exception {
   TextMessage msg = session.createTextMessage();

   // Pad message text
   if (initText.length() < messageSize) {
      char[] data = new char[messageSize - initText.length()];
      Arrays.fill(data, '*');
      String str = new String(data);
      msg.setText(initText + str);

      // Do not pad message text
   } else {
      msg.setText(initText);
   }

   return msg;
}
 
Example 3
Source File: SessionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateQueue() throws Exception {
   Connection conn = getConnectionFactory().createConnection();
   Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = sess.createQueue("Queue1");

   MessageProducer producer = sess.createProducer(queue);
   MessageConsumer consumer = sess.createConsumer(queue);
   conn.start();

   Message m = sess.createTextMessage("testing");
   producer.send(m);

   Message m2 = consumer.receive(3000);

   ProxyAssertSupport.assertNotNull(m2);
   conn.close();
}
 
Example 4
Source File: JNDIConnectionFactoryProviderTest.java    From solace-integration-guides with Apache License 2.0 5 votes vote down vote up
/**
 * This test simply validates that {@link ConnectionFactory} can be setup by pointing to the location of the client
 * libraries at runtime. It uses ActiveMQ which is not present at the POM but instead pulled from Maven repo using
 * {@link TestUtils#setupActiveMqLibForTesting(boolean)}, which implies that for this test to run the computer must
 * be connected to the Internet. If computer is not connected to the Internet, this test will quietly fail logging a
 * message.
 */
@Test
public void validateFactoryCreationWithActiveMQLibraries() throws Exception {
    try {
        String libPath = TestUtils.setupActiveMqLibForTesting(true);

        TestRunner runner = TestRunners.newTestRunner(mock(Processor.class));
        JNDIConnectionFactoryProvider cfProvider = new JNDIConnectionFactoryProvider();
        runner.addControllerService("cfProvider", cfProvider);
        runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.BROKER_URI,
                "vm://localhost?broker.persistent=false");
        runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.JNDI_CF_LOOKUP, "ConnectionFactory");
        runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CLIENT_LIB_DIR_PATH, libPath);
        runner.setProperty(cfProvider, JNDIConnectionFactoryProvider.CONNECTION_FACTORY_IMPL,
                "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        runner.enableControllerService(cfProvider);
        runner.assertValid(cfProvider);

        Connection connection = cfProvider.getConnectionFactory().createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination queue = session.createQueue("myqueue");
        MessageProducer producer = session.createProducer(queue);
        MessageConsumer consumer = session.createConsumer(queue);

        TextMessage message = session.createTextMessage("Hello");
        producer.send(message);
        assertEquals("Hello", ((TextMessage) consumer.receive()).getText());
        connection.stop();
        connection.close();
    } catch (Exception e) {
        logger.error("'validateFactoryCreationWithActiveMQLibraries' failed due to ", e);
    }
}
 
Example 5
Source File: JmsSchedulerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testScheduleRestart() throws Exception {
   // send a message
   Connection connection = createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   connection.start();
   MessageProducer producer = session.createProducer(destination);
   TextMessage message = session.createTextMessage("test msg");
   long time = 5000;
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
   producer.send(message);
   producer.close();

   //restart broker
   broker.stop();
   broker.waitUntilStopped();

   broker = createBroker(false);
   broker.start();
   broker.waitUntilStarted();

   // consume the message
   connection = createConnection();
   connection.start();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createConsumer(destination);
   Message msg = consumer.receive(5000);
   assertNotNull("Didn't receive the message", msg);

   //send another message
   producer = session.createProducer(destination);
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
   producer.send(message);
   producer.close();
}
 
Example 6
Source File: AnonymousFallbackProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void doTestSendWhenLinkCreditIsZeroAndTimeout(int cacheSize) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Use a long timeout to ensure no early evictions in this test.
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer,
            "?amqp.anonymousFallbackCacheSize=" + cacheSize + "&amqp.anonymousFallbackCacheTimeout=60000");
        connection.setSendTimeout(500);

        testPeer.expectBegin();

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

        Message message = session.createTextMessage("text");

        // Expect the producer to attach. Don't send any credit so that the client will
        // block on a send and we can test our timeouts.
        testPeer.expectSenderAttachWithoutGrantingCredit();
        if (cacheSize == 0) {
            testPeer.expectDetach(true, true, true);
        }
        testPeer.expectClose();

        MessageProducer producer = session.createProducer(null);

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

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 7
Source File: JMSStringInputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private void produceMsg(int numMessages) throws Exception
{
  // Create a ConnectionFactory
  ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

  // Create a Connection
  Connection connection = connectionFactory.createConnection();
  connection.start();

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

  // Create the destination (Topic or Queue)
  Destination destination = session.createQueue("TEST.FOO");

  // Create a MessageProducer from the Session to the Topic or Queue
  MessageProducer producer = session.createProducer(destination);
  producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

  // Create a messages
  String text = "Hello world! From tester producer";
  TextMessage message = session.createTextMessage(text);
  for (int i = 0; i < numMessages; i++) {
    producer.send(message);
  }

  // Clean up
  session.close();
  connection.close();

}
 
Example 8
Source File: MessageCompressionTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void publishMessage(final Connection senderConnection, final String messageText, final Queue testQueue)
        throws JMSException
{
    Session session = senderConnection.createSession(true, Session.SESSION_TRANSACTED);

    MessageProducer producer = session.createProducer(testQueue);
    TextMessage sentMessage = session.createTextMessage(messageText);
    sentMessage.setStringProperty("bar", "foo");

    producer.send(sentMessage);
    session.commit();
}
 
Example 9
Source File: JobSchedulerJmxManagementTests.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void scheduleMessage(int time, int period, int repeat) throws Exception {
   Connection connection = createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(destination);
   TextMessage message = session.createTextMessage("test msg");
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
   message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
   message.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
   producer.send(message);
   connection.close();
}
 
Example 10
Source File: ExpiredMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpiredAndLivingMessages() throws Exception {
   Connection conn = getConnectionFactory().createConnection();
   Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer prod = session.createProducer(queue1);

   // sent 2 messages: 1 expiring, 1 living
   TextMessage livingMessage = session.createTextMessage("This message will live");
   TextMessage expiringMessage = session.createTextMessage("This message will expire");

   prod.setTimeToLive(1);
   prod.send(expiringMessage);

   prod.setTimeToLive(0);
   prod.send(livingMessage);

   // wait for the expiring message to die
   Thread.sleep(250);

   MessageConsumer cons = session.createConsumer(queue1);
   conn.start();

   // receive living message
   Message receivedMessage = cons.receive(1000);
   ProxyAssertSupport.assertNotNull("did not receive living message", receivedMessage);
   ProxyAssertSupport.assertTrue(receivedMessage instanceof TextMessage);
   ProxyAssertSupport.assertEquals(livingMessage.getText(), ((TextMessage) receivedMessage).getText());

   // we do not receive the expiring message
   ProxyAssertSupport.assertNull(cons.receiveNoWait());

   conn.close();
}
 
Example 11
Source File: JmsStubMessages.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private Message createMessage(Session session, Object payload) throws JMSException {
	if (payload instanceof String) {
		return session.createTextMessage((String) payload);
	}
	else if (payload instanceof byte[]) {
		BytesMessage bytesMessage = session.createBytesMessage();
		bytesMessage.writeBytes((byte[]) payload);
		return bytesMessage;
	}
	else if (payload instanceof Serializable) {
		return session.createObjectMessage((Serializable) payload);
	}
	return session.createMessage();
}
 
Example 12
Source File: MessageListenerRedeliveryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private TextMessage createTextMessage(Session session, String text) throws JMSException {
   return session.createTextMessage(text);
}
 
Example 13
Source File: TemporaryQueueClusterTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testClusteredQueue() throws Exception {

   Connection conn1 = openWireCf1.createConnection();
   Connection conn2 = openWireCf2.createConnection();

   conn1.start();
   conn2.start();

   try {
      Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue targetQueue1 = session1.createQueue(QUEUE_NAME);

      Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue targetQueue2 = session2.createQueue(QUEUE_NAME);

      this.waitForBindings(servers[0], QUEUE_NAME, true, 1, 0, 2000);
      this.waitForBindings(servers[1], QUEUE_NAME, true, 1, 0, 2000);
      this.waitForBindings(servers[1], QUEUE_NAME, false, 1, 0, 2000);
      this.waitForBindings(servers[0], QUEUE_NAME, false, 1, 0, 2000);

      MessageProducer prod1 = session1.createProducer(targetQueue1);
      MessageConsumer cons2 = session2.createConsumer(targetQueue2);

      this.waitForBindings(servers[0], QUEUE_NAME, false, 1, 1, 2000);
      this.waitForBindings(servers[1], QUEUE_NAME, true, 1, 1, 2000);

      TextMessage msg = session1.createTextMessage("hello");

      prod1.send(msg);

      Wait.assertTrue(() -> getServer(1).locateQueue(SimpleString.toSimpleString(QUEUE_NAME)).getMessageCount() == 1, 5000, 100);

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

      assertNotNull(msgReceived);
      assertEquals(msgReceived.getText(), msg.getText());

   } finally {
      conn1.close();
      conn2.close();
   }
}
 
Example 14
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout=20000)
public void testSendingMessageWithPrefixedUUIDStringMessageIdFormat() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // DONT create a test fixture, we will drive everything directly.
        String uri = "amqp://127.0.0.1:" + testPeer.getServerPort() + "?jms.messageIDPolicy.messageIDType=PREFIXED_UUID_STRING";
        JmsConnectionFactory factory = new JmsConnectionFactory(uri);

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

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

        String text = "myMessage";
        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withMessageId(isA(String.class));
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(text));
        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        Message message = session.createTextMessage(text);

        assertNull("JMSMessageID should not yet be set", message.getJMSMessageID());

        producer.send(message);

        String jmsMessageID = message.getJMSMessageID();
        assertNotNull("JMSMessageID should be set", jmsMessageID);
        assertTrue("JMS 'ID:' prefix not found", jmsMessageID.startsWith("ID:"));

        connection.close();
        testPeer.waitForAllHandlersToComplete(1000);

        // Get the value that was actually transmitted/received, verify it is a String,
        // verify it is the "ID:" prefix followed by the UUID toString, check the
        // JMSMessageID value that we have locally matches exactly.
        Object receivedMessageId = propsMatcher.getReceivedMessageId();

        String uuidToString = jmsMessageID.substring("ID:".length());
        UUID.fromString(uuidToString);
        assertTrue("Expected String message id to be sent", receivedMessageId instanceof String);
        assertEquals("Expected UUID toString value to be present in AMQP message", jmsMessageID, receivedMessageId);
    }
}
 
Example 15
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Repeat(repetitions = 1)
@Test(timeout = 20000)
public void testFailoverDoesNotFailPendingAsyncCompletionSend() throws Exception {
    try (TestAmqpPeer originalPeer = new TestAmqpPeer();
         TestAmqpPeer finalPeer = new TestAmqpPeer();) {

        // Create a peer to connect to, then one to reconnect to
        final String originalURI = createPeerURI(originalPeer);
        final String finalURI = createPeerURI(finalPeer);

        LOG.info("Original peer is at: {}", originalURI);
        LOG.info("Final peer is at: {}", finalURI);

        originalPeer.expectSaslAnonymous();
        originalPeer.expectOpen();
        originalPeer.expectBegin();
        originalPeer.expectBegin();
        // Ensure our send blocks in the provider waiting for credit so that on failover
        // the message will actually get sent from the Failover bits once we grant some
        // credit for the recovered sender.
        originalPeer.expectSenderAttachWithoutGrantingCredit();
        originalPeer.dropAfterLastHandler(10);  // Wait for sender to get into wait state

        // --- Post Failover Expectations of sender --- //
        finalPeer.expectSaslAnonymous();
        finalPeer.expectOpen();
        finalPeer.expectBegin();
        finalPeer.expectBegin();
        finalPeer.expectSenderAttach();
        finalPeer.expectTransfer(new TransferPayloadCompositeMatcher());
        finalPeer.expectClose();

        final JmsConnection connection = establishAnonymousConnecton("failover.initialReconnectDelay=25", originalPeer, finalPeer);

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

        MessageProducer producer = session.createProducer(queue);

        // Create and transfer a new message
        String text = "myMessage";

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

        try {
            producer.send(message, listener);
        } catch (JMSException jmsEx) {
            fail("Should not have failed the async completion send.");
        }

        // This should fire after reconnect without an error, if it fires with an error at
        // any time then something is wrong.
        assertTrue("Did not get async callback", listener.awaitCompletion(5, TimeUnit.SECONDS));
        assertNull("Completion should not have been on error", listener.exception);
        assertNotNull(listener.message);
        assertTrue(listener.message instanceof TextMessage);

        connection.close();

        finalPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 16
Source File: FQQNOpenWireTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testVirtualTopicFQQNAutoCreateQAndAddress() throws Exception {
   Connection exConn = null;

   SimpleString topic = new SimpleString("VirtualTopic.Orders");
   SimpleString subscriptionQ = new SimpleString("Consumer.A");

   // defaults are false via test setUp
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateQueues(true);
   this.server.getAddressSettingsRepository().getMatch("VirtualTopic.#").setAutoCreateAddresses(true);

   try {
      ActiveMQConnectionFactory exFact = new ActiveMQConnectionFactory();
      exFact.setWatchTopicAdvisories(false);
      exConn = exFact.createConnection();
      exConn.start();

      Session session = exConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createTopic(topic.toString());
      MessageProducer producer = session.createProducer(destination);

      Destination destinationFQN = session.createQueue(CompositeAddress.toFullyQualified(topic, subscriptionQ).toString());

      MessageConsumer messageConsumerA = session.createConsumer(destinationFQN);
      MessageConsumer messageConsumerB = session.createConsumer(destinationFQN);

      TextMessage message = session.createTextMessage("This is a text message");
      producer.send(message);

      // only one consumer should get the message
      TextMessage messageReceivedA = (TextMessage) messageConsumerA.receive(2000);
      TextMessage messageReceivedB = (TextMessage) messageConsumerB.receive(2000);

      assertTrue((messageReceivedA == null || messageReceivedB == null));
      String text = messageReceivedA != null ? messageReceivedA.getText() : messageReceivedB.getText();
      assertEquals("This is a text message", text);

      messageConsumerA.close();
      messageConsumerB.close();

   } finally {
      if (exConn != null) {
         exConn.close();
      }
   }
}
 
Example 17
Source File: ClusteredQueueExample.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
   Connection connection0 = null;

   Connection connection1 = null;

   try {
      // Step 2. Instantiate the Queue
      Queue queue = ActiveMQJMSClient.createQueue("exampleQueue");

      // Instantiate connection towards server 0
      ConnectionFactory cf0 = new ActiveMQConnectionFactory("tcp://localhost:61616");

      // Step 5. Look-up a JMS Connection Factory object from JNDI on server 1
      ConnectionFactory cf1 = new ActiveMQConnectionFactory("tcp://localhost:61617");

      // Step 6. We create a JMS Connection connection0 which is a connection to server 0
      connection0 = cf0.createConnection();

      // Step 7. We create a JMS Connection connection1 which is a connection to server 1
      connection1 = cf1.createConnection();

      // Step 8. We create a JMS Session on server 0
      Session session0 = connection0.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Step 9. We create a JMS Session on server 1
      Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Step 10. We start the connections to ensure delivery occurs on them
      connection0.start();

      connection1.start();

      // Step 11. We create JMS MessageConsumer objects on server 0 and server 1
      MessageConsumer consumer0 = session0.createConsumer(queue);

      MessageConsumer consumer1 = session1.createConsumer(queue);

      Thread.sleep(1000);

      // Step 12. We create a JMS MessageProducer object on server 0
      MessageProducer producer = session0.createProducer(queue);

      // Step 13. We send some messages to server 0

      final int numMessages = 10;

      for (int i = 0; i < numMessages; i++) {
         TextMessage message = session0.createTextMessage("This is text message " + i);

         producer.send(message);

         System.out.println("Sent message: " + message.getText());
      }

      // Step 14. We now consume those messages on *both* server 0 and server 1.
      // We note the messages have been distributed between servers in a round robin fashion
      // JMS Queues implement point-to-point message where each message is only ever consumed by a
      // maximum of one consumer

      for (int i = 0; i < numMessages; i += 2) {
         TextMessage message0 = (TextMessage) consumer0.receive(5000);

         System.out.println("Got message: " + message0.getText() + " from node 0");

         TextMessage message1 = (TextMessage) consumer1.receive(5000);

         System.out.println("Got message: " + message1.getText() + " from node 1");
      }
   } finally {
      // Step 15. Be sure to close our resources!

      if (connection0 != null) {
         connection0.close();
      }

      if (connection1 != null) {
         connection1.close();
      }
   }
}
 
Example 18
Source File: MessageProducerTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
private void sendToTopic(final boolean persistent) throws Exception {

      Connection pconn = createConnection();
      Connection cconn = createConnection();

      try {
         Session ps = pconn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         Session cs = cconn.createSession(false, Session.AUTO_ACKNOWLEDGE);
         final MessageProducer p = ps.createProducer(ActiveMQServerTestCase.topic1);

         p.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);

         MessageConsumer c = cs.createConsumer(ActiveMQServerTestCase.topic1);

         cconn.start();

         TextMessage m1 = ps.createTextMessage("test");

         Sender sender = new Sender(p, m1);

         Thread t = new Thread(sender, "Producer Thread");

         t.start();

         TextMessage m2 = (TextMessage) c.receive(5000);

         if (sender.ex != null) {
            // If an exception was caught in sending we rethrow here so as not to lose it
            throw sender.ex;
         }

         ProxyAssertSupport.assertEquals(m2.getJMSMessageID(), m1.getJMSMessageID());
         ProxyAssertSupport.assertEquals("test", m2.getText());

         t.join();
      } finally {
         pconn.close();
         cconn.close();
      }
   }
 
Example 19
Source File: JMSTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testPersistent_NonTransactional() throws Exception {
   conn = createConnection();

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

   MessageProducer prod = session.createProducer(queue1);
   prod.setDeliveryMode(DeliveryMode.PERSISTENT);

   TextMessage m = session.createTextMessage("message one");

   prod.send(m);

   conn.close();

   conn = createConnection();

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

   MessageConsumer cons = session.createConsumer(queue1);

   conn.start();

   TextMessage rm = (TextMessage) cons.receive();

   ProxyAssertSupport.assertEquals("message one", rm.getText());
}
 
Example 20
Source File: MessageConsumerTest.java    From activemq-artemis with Apache License 2.0 3 votes vote down vote up
@Test
public void testExceptionMessageListenerStopSession() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();

      conn.start();

      Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);

      MessageConsumer cons = sess.createConsumer(queue1);

      CountDownLatch latch = new CountDownLatch(1);
      SessionCloseMessageListener listener = new SessionCloseMessageListener(sess, latch);

      cons.setMessageListener(listener);

      conn.start();

      MessageProducer prod = sessSend.createProducer(queue1);
      TextMessage m1 = sess.createTextMessage("a");

      prod.send(m1);

      ProxyAssertSupport.assertTrue(latch.await(5, TimeUnit.SECONDS));

      ProxyAssertSupport.assertNotNull(listener.exception);

      ProxyAssertSupport.assertTrue(listener.exception instanceof javax.jms.IllegalStateException);
   } finally {
      if (conn != null) {
         conn.close();
      }

      removeAllMessages(queue1.getQueueName(), true);
   }
}