Java Code Examples for javax.jms.TextMessage#setText()

The following examples show how to use javax.jms.TextMessage#setText() . 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: JMSMessageProducerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testAnonymousProducerWithAutoCreation() throws Exception {
   Connection connection = createConnection();

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic(UUID.randomUUID().toString());
      MessageProducer p = session.createProducer(null);

      TextMessage message = session.createTextMessage();
      message.setText("hello");
      // this will auto-create the address
      p.send(topic, message);

      {
         MessageConsumer consumer = session.createConsumer(topic);
         p.send(topic, message);
         Message msg = consumer.receive(2000);
         assertNotNull(msg);
         assertTrue(msg instanceof TextMessage);
         consumer.close();
      }
   } finally {
      connection.close();
   }
}
 
Example 2
Source File: ClientRequestMessageConverterTest.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testDeviceClassNamesMessageConversion() {
  ClientRequestImpl<DeviceClassNameResponse> request = new ClientRequestImpl<>(DeviceClassNameResponse.class);

  TextMessage message = new ActiveMQTextMessage();
  try {
    message.setText(request.toJson());
    ClientRequest receivedRequest = ClientRequestMessageConverter.fromMessage(message);

    assertTrue(receivedRequest.getRequestType() == ClientRequest.RequestType.DEVICE_CLASS_NAMES_REQUEST);
    assertTrue(receivedRequest.getResultType() == ClientRequest.ResultType.TRANSFER_DEVICE_CLASS_NAMES);
  }
  catch (JMSException e) {
    assertTrue(e.getMessage(), false);
  }
}
 
Example 3
Source File: TemporaryTopicTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test a TemporaryTopic
 */
@Test
public void testTemporaryTopic() {
   try {
      // we stop both publisher and subscriber connections
      publisherConnection.stop();
      subscriberConnection.stop();
      // we create a temporary topic to receive messages
      tempTopic = subscriberSession.createTemporaryTopic();
      // we recreate the sender because it has been
      // already created with another Destination as parameter
      publisher = publisherSession.createPublisher(tempTopic);
      // we create a temporary subscriber on the temporary topic
      tempSubscriber = subscriberSession.createSubscriber(tempTopic);
      subscriberConnection.start();
      publisherConnection.start();

      TextMessage message = publisherSession.createTextMessage();
      message.setText("testTemporaryTopic");
      publisher.publish(message);

      Message m = tempSubscriber.receive(TestConfig.TIMEOUT);
      Assert.assertTrue(m instanceof TextMessage);
      TextMessage msg = (TextMessage) m;
      Assert.assertEquals("testTemporaryTopic", msg.getText());
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 4
Source File: JMSNonDestructiveTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void sendLVQTombstone(ConnectionSupplier producerConnectionSupplier, String queueName, String lastValueKey, int tombstoneTimeToLive) throws JMSException {
   try (Connection connection = producerConnectionSupplier.createConnection();
        Session session = connection.createSession();
        MessageProducer producer = session.createProducer(session.createQueue(queueName))) {
      TextMessage message1 = session.createTextMessage();
      message1.setStringProperty(lastValueKey, "KEY");
      message1.setText("tombstone");
      producer.send(message1, javax.jms.Message.DEFAULT_DELIVERY_MODE, javax.jms.Message.DEFAULT_PRIORITY, tombstoneTimeToLive);
   }
}
 
Example 5
Source File: ProduceToOpenWireTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void singleSendProfile() throws Exception {
    connection = createActiveMQConnection();

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(getDestinationName());
    MessageProducer producer = session.createProducer(topic);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    TextMessage message = session.createTextMessage();
    message.setText("hello");
    producer.send(message);
}
 
Example 6
Source File: PeerTransportTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception
 */
public void testSendReceive() throws Exception {
   for (int i = 0; i < MESSAGE_COUNT; i++) {
      for (int x = 0; x < producers.length; x++) {
         TextMessage textMessage = new ActiveMQTextMessage();
         textMessage.setText("MSG-NO: " + i + " in cluster: " + x);
         producers[x].send(textMessage);
      }
   }

   for (int i = 0; i < NUMBER_IN_CLUSTER; i++) {
      messageIdList[i].assertMessagesReceived(expectedReceiveCount());
   }
}
 
Example 7
Source File: MessageBodyTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the <code>TextMessage.clearBody()</code> effectively clear the body of the message
 */
@Test
public void testClearBody_1() {
   try {
      TextMessage message = senderSession.createTextMessage();
      message.setText("bar");
      message.clearBody();
      Assert.assertEquals("sec. 3 .11.1 the clearBody method of Message resets the value of the message body " + "to the 'empty' initial message value as set by the message type's create " + "method provided by Session.\n", null, message.getText());
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 8
Source File: TopicBridgeSpringTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message msg) {
   try {
      TextMessage textMsg = (TextMessage) msg;
      String payload = "REPLY: " + textMsg.getText();
      Destination replyTo;
      replyTo = msg.getJMSReplyTo();
      textMsg.clearBody();
      textMsg.setText(payload);
      LOG.info("Sending response: " + textMsg);
      requestServerProducer.send(replyTo, textMsg);
   } catch (JMSException e) {
      e.printStackTrace();
   }
}
 
Example 9
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testSentTextMessageCanBeModified() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

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

        // Create and transfer a new message
        String text = "myMessage";
        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true);
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(text));
        testPeer.expectTransfer(messageMatcher);
        testPeer.expectClose();

        TextMessage message = session.createTextMessage(text);
        producer.send(message);

        assertEquals(text, message.getText());
        message.setText(text + text);
        assertEquals(text + text, message.getText());

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 10
Source File: MessageProvider.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
protected Message createTextMessage(Session ssn, final CreateProducerCommand command) throws JMSException
{
    String payload = getMessagePayload(command);

    TextMessage msg = null;
    synchronized(ssn)
    {
        msg = ssn.createTextMessage();
    }
    msg.setText(payload);

    return msg;
}
 
Example 11
Source File: DataRecord2JmsMsgProperties.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Message createMsg(DataRecord record) throws JMSException {
	TextMessage msg = session.createTextMessage();
	int fieldCnt = record.getNumFields();
	if (bodyField > -1) {
		msg.setText(record.getField(bodyField).toString());
	}
	for (int fieldIdx = 0; fieldIdx < fieldCnt; fieldIdx++) {
		if (fieldIdx == bodyField) {
			continue;
		}
		DataField field = record.getField(fieldIdx);
		// TODO Labels:
		//msg.setStringProperty(field.getMetadata().getLabelOrName(), field.toString());
		switch(field.getMetadata().getContainerType()){
		case SINGLE:
			msg.setStringProperty(field.getMetadata().getName(), field.toString());
			break;
		case MAP:
			@SuppressWarnings("unchecked")
			Map<String,CloverString> map= ((MapDataField)field).getValue(CloverString.class);
			for(Map.Entry<String,CloverString> entry: map.entrySet()){
				msg.setStringProperty(entry.getKey(), entry.getValue().toString());
			}
			break;
		default:
				throw new JMSException(String.format("Can not map field \"%s\" of type List<%s>.",field.getMetadata().getName(),
						field.getMetadata().getDataType().toString()));
		}
	}
	msg.setJMSPriority(Message.DEFAULT_PRIORITY);
	return msg;
}
 
Example 12
Source File: QueueBridgeTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Message msg) {
   try {
      TextMessage textMsg = (TextMessage) msg;
      String payload = "REPLY: " + textMsg.getText();
      Destination replyTo;
      replyTo = msg.getJMSReplyTo();
      textMsg.clearBody();
      textMsg.setText(payload);
      requestServerProducer.send(replyTo, textMsg);
   } catch (JMSException e) {
      e.printStackTrace();
   }
}
 
Example 13
Source File: TextMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendReceiveNullBody() throws Exception {
   conn = cf.createConnection();

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

   MessageProducer prod = sess.createProducer(queue);

   conn.start();

   MessageConsumer cons = sess.createConsumer(queue);

   TextMessage msg1 = sess.createTextMessage(null);
   prod.send(msg1);
   TextMessage received1 = (TextMessage) cons.receive(1000);
   Assert.assertNotNull(received1);
   Assert.assertNull(received1.getText());

   TextMessage msg2 = sess.createTextMessage();
   msg2.setText(null);
   prod.send(msg2);
   TextMessage received2 = (TextMessage) cons.receive(1000);
   Assert.assertNotNull(received2);
   Assert.assertNull(received2.getText());

   TextMessage msg3 = sess.createTextMessage();
   prod.send(msg3);
   TextMessage received3 = (TextMessage) cons.receive(1000);
   Assert.assertNotNull(received3);
   Assert.assertNull(received3.getText());
}
 
Example 14
Source File: DurableSubscriptionHangTestCase.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void sendRandomMessage(TopicSession session, MessageProducer producer) throws JMSException {
   TextMessage textMessage = session.createTextMessage();
   textMessage.setText(RandomStringUtils.random(500, "abcdefghijklmnopqrstuvwxyz"));
   producer.send(textMessage);
}
 
Example 15
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void testBrokerRestart(Connection connection1, Connection connection2) throws Exception {
   try {
      Session session1 = connection1.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

      javax.jms.Queue queue1 = session1.createQueue(getQueueName());
      javax.jms.Queue queue2 = session2.createQueue(getQueueName());

      final MessageConsumer consumer2 = session2.createConsumer(queue2);

      MessageProducer producer = session1.createProducer(queue1);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);
      connection1.start();

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

      Message received = consumer2.receive(100);

      assertNotNull("Should have received a message by now.", received);
      assertTrue("Should be an instance of TextMessage", received instanceof TextMessage);
      assertEquals(DeliveryMode.PERSISTENT, received.getJMSDeliveryMode());


      server.stop();
      Wait.waitFor(() -> !server.isStarted(), 1000);

      server.start();

      TextMessage message2 = session1.createTextMessage();
      message2.setText("hello");
      producer.send(message2);

      Message received2 = consumer2.receive(100);

      assertNotNull("Should have received a message by now.", received2);
      assertTrue("Should be an instance of TextMessage", received2 instanceof TextMessage);
      assertEquals(DeliveryMode.PERSISTENT, received2.getJMSDeliveryMode());


   } finally {
      connection1.close();
      connection2.close();
   }
}
 
Example 16
Source File: ExceptionListenerForConnectionTimedOutExceptionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testOnSend(boolean blockOnFailover) throws Exception {
   mayBlock.set(blockOnFailover);
   Connection sendConnection = null;
   Connection connection = null;
   AtomicReference<JMSException> exceptionOnConnection = new AtomicReference<>();

   try {
      ((ActiveMQConnectionFactory) cf).setOutgoingInterceptorList(OutBoundPacketCapture.class.getName());
      ((ActiveMQConnectionFactory) cf).setIncomingInterceptorList(SessSendCauseResponseTimeout.class.getName());
      ((ActiveMQConnectionFactory) cf).setCallTimeout(500);

      sendConnection = cf.createConnection();
      sendConnection.setExceptionListener(exceptionOnConnection::set);
      final Session sendSession = sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      final MessageProducer producer = sendSession.createProducer(queue);

      TextMessage message = sendSession.createTextMessage();

      message.setText("Message");

      producer.send(message);

      fail("JMSException expected");

   } catch (JMSException e) {
      if (blockOnFailover) {
         Wait.assertTrue(blocked::get);
         unblock();
      }
      assertTrue(e.getCause() instanceof ActiveMQConnectionTimedOutException);
      //Ensure JMS Connection ExceptionListener was also invoked
      assertTrue(Wait.waitFor(() -> exceptionOnConnection.get() != null, 2000, 100));
      assertTrue(exceptionOnConnection.get().getCause() instanceof ActiveMQConnectionTimedOutException);

   } finally {
      if (connection != null) {
         connection.close();
      }
      if (sendConnection != null) {
         sendConnection.close();
      }
   }
}
 
Example 17
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testLastValueQueueUsingAddressQueueParameters() throws Exception {
   ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();

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

   try {

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

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

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

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

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

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

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

      assertNotNull(tm);

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

   } finally {
      connection.close();
   }
}
 
Example 18
Source File: TopicRedeliverTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception {
   Destination destination = createDestination(getClass().getName());
   Connection connection = createConnection();
   final AtomicBoolean gotException = new AtomicBoolean();
   connection.setExceptionListener(new ExceptionListener() {
      @Override
      public void onException(JMSException exception) {
         LOG.error("unexpected ex:" + exception);
         gotException.set(true);
      }
   });
   connection.setClientID(idGen.generateId());
   connection.start();
   Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
   MessageConsumer consumer = null;
   if (topic) {
      consumer = consumerSession.createConsumer(destination);
   } else {
      consumer = consumerSession.createConsumer(destination);
   }
   Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = producerSession.createProducer(destination);
   producer.setDeliveryMode(deliveryMode);

   TextMessage sentMsg = producerSession.createTextMessage();
   sentMsg.setText("msg1");
   producer.send(sentMsg);
   producerSession.commit();

   Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertFalse(recMsg.getJMSRedelivered());
   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   consumerSession.rollback();
   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertTrue(recMsg.getJMSRedelivered());
   consumerSession.rollback();
   recMsg = consumer.receive(RECEIVE_TIMEOUT);
   assertTrue(recMsg.getJMSRedelivered());
   consumerSession.commit();
   assertTrue(recMsg.equals(sentMsg));
   assertTrue(recMsg.getJMSRedelivered());
   connection.close();

   assertFalse("no exception", gotException.get());
}
 
Example 19
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testLastValueKeyTopicConsumerUsingAddressQueueParameters() throws Exception {
   ActiveMQConnectionFactory fact = (ActiveMQConnectionFactory) getCF();

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

   try {

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

      Topic topic = session.createTopic("topic?last-value-key=reuters_code");
      assertEquals("topic", topic.getTopicName());

      ActiveMQDestination a = (ActiveMQDestination) topic;
      assertEquals("reuters_code", a.getQueueAttributes().getLastValueKey().toString());
      assertEquals("reuters_code", a.getQueueConfiguration().getLastValueKey().toString());

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

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

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



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

      assertNotNull(tm);

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

      //Last message only should go to the other consumer as well.
      TextMessage tm2 = (TextMessage) consumer2.receive(10000);

      assertNotNull(tm2);

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

   } finally {
      connection.close();
   }
}
 
Example 20
Source File: ConsumerPriorityTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testConsumerPriorityQueueConsumerRoundRobin() throws Exception {
   ConnectionFactory fact = getCF();
   Connection connection = fact.createConnection();
   String queueName = getName();

   try {

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

      Queue queue = session.createQueue(queueName);
      Queue queue1 = session.createQueue(queueName + "?consumer-priority=3");
      Queue queue2 = session.createQueue(queueName + "?consumer-priority=3");
      Queue queue3 = session.createQueue(queueName + "?consumer-priority=1");


      MessageProducer producer = session.createProducer(queue);

      MessageConsumer consumer1 = session.createConsumer(queue1);
      MessageConsumer consumer2 = session.createConsumer(queue2);
      MessageConsumer consumer3 = session.createConsumer(queue3);

      connection.start();

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

         message.setText("Message" + j);
         message.setIntProperty("counter", j);
         producer.send(message);
      }


      //All msgs should go to the first two consumers, round robin'd
      for (int j = 0; j < 50; j += 2) {
         TextMessage tm = (TextMessage) consumer1.receive(10000);

         assertNotNull(tm);

         assertEquals("Message" + j, tm.getText());

         TextMessage tm2 = (TextMessage) consumer2.receive(10000);
         assertNotNull(tm2);

         assertEquals("Message" + (j + 1), tm2.getText());



         TextMessage tm3 = (TextMessage) consumer3.receiveNoWait();
         assertNull(tm3);
      }
   } finally {
      connection.close();
   }
}