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

The following examples show how to use javax.jms.TextMessage#setStringProperty() . 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: SelectorTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Test the IN condition in message selector.
 * <br />
 * <ul>
 * <li>"Country IN ('UK', 'US', 'France')" is <code>true</code> for 'UK' and <code>false</code> for 'Peru'</li>
 * </ul>
 */
@Test
public void testIn() throws Exception {
   if (receiver != null) {
      receiver.close();
   }
   receiver = receiverSession.createReceiver(receiverQueue, "Country IN ('UK', 'US', 'France')");

   TextMessage dummyMessage = senderSession.createTextMessage();
   dummyMessage.setStringProperty("Country", "Peru");
   dummyMessage.setText("testIn:1");
   sender.send(dummyMessage);

   TextMessage message = senderSession.createTextMessage();
   message.setStringProperty("Country", "UK");
   message.setText("testIn:2");
   sender.send(message);

   TextMessage msg = (TextMessage) receiver.receive(TestConfig.TIMEOUT);
   Assert.assertTrue("Message not received", msg != null);
   Assert.assertTrue("Message of another test: " + msg.getText(), msg.getText().startsWith("testIn"));
   Assert.assertEquals("testIn:2", msg.getText());
}
 
Example 2
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 3
Source File: JMSNonDestructiveTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendLVQ(ConnectionSupplier producerConnectionSupplier, String queueName, String lastValueKey) 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("hello");
      producer.send(message1);

      TextMessage message2 = session.createTextMessage();
      message2.setStringProperty(lastValueKey, "KEY");
      message2.setText("how are you");
      producer.send(message2);
   }
}
 
Example 4
Source File: ActiveMqFacade.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public TextMessage createTextMessage(String messageText) throws JMSException {
    TextMessage message = session.createTextMessage(messageText);
    message.setStringProperty("test_string_property", "test123");
    message.setIntProperty("test_int_property", 123);
    message.setStringProperty("passwd", "secret");
    message.setStringProperty("null_property", null);
    return message;
}
 
Example 5
Source File: TradeDirect.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
private void publishQuotePriceChange(QuoteDataBean quoteData, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) throws Exception {
    if (Log.doTrace()) {
        Log.trace("TradeDirect:publishQuotePrice PUBLISHING to MDB quoteData = " + quoteData);
    }
    
    try (JMSContext context = tConnFactory.createContext();){
		TextMessage message = context.createTextMessage();

		message.setStringProperty("command", "updateQuote");
        message.setStringProperty("symbol", quoteData.getSymbol());
        message.setStringProperty("company", quoteData.getCompanyName());
        message.setStringProperty("price", quoteData.getPrice().toString());
        message.setStringProperty("oldPrice", oldPrice.toString());
        message.setStringProperty("open", quoteData.getOpen().toString());
        message.setStringProperty("low", quoteData.getLow().toString());
        message.setStringProperty("high", quoteData.getHigh().toString());
        message.setDoubleProperty("volume", quoteData.getVolume());

        message.setStringProperty("changeFactor", changeFactor.toString());
        message.setDoubleProperty("sharesTraded", sharesTraded);
        message.setLongProperty("publishTime", System.currentTimeMillis());
        message.setText("Update Stock price for " + quoteData.getSymbol() + " old price = " + oldPrice + " new price = " + quoteData.getPrice());

  		
		context.createProducer().send(streamerTopic, message);

    } catch (Exception e) {
        throw e; // pass exception back

    }
}
 
Example 6
Source File: AmqpExpiredMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/** This test is validating a broker feature where the message copy through the DLQ will receive an annotation.
 *  It is also testing filter on that annotation. */
@Test(timeout = 60000)
public void testExpiryQpidJMS() throws Exception {
   ConnectionFactory factory = CFUtil.createConnectionFactory("AMQP", getBrokerAmqpConnectionURI().toString());
   Connection connection = factory.createConnection();
   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      javax.jms.Queue queue = session.createQueue(getQueueName());
      MessageProducer sender = session.createProducer(queue);

      // Get the Queue View early to avoid racing the delivery.
      final Queue queueView = getProxyToQueue(getQueueName());
      assertNotNull(queueView);

      sender.setTimeToLive(1);
      TextMessage message = session.createTextMessage("Test-Message");
      message.setStringProperty("key1", "Value1");
      sender.send(message);
      sender.close();

      Wait.assertEquals(1, queueView::getMessagesExpired);
      final Queue dlqView = getProxyToQueue(getDeadLetterAddress());
      assertNotNull(dlqView);
      Wait.assertEquals(1, dlqView::getMessageCount);

      connection.start();
      javax.jms.Queue queueDLQ = session.createQueue(getDeadLetterAddress());
      MessageConsumer receiverDLQ = session.createConsumer(queueDLQ, "\"m.x-opt-ORIG-ADDRESS\"='" + getQueueName() + "'");
      Message received = receiverDLQ.receive(5000);
      Assert.assertNotNull(received);
      receiverDLQ.close();
   } finally {
      connection.close();
   }

}
 
Example 7
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 8
Source File: TradeSLSBBean.java    From sample.daytrader7 with Apache License 2.0 5 votes vote down vote up
@Override
public void queueOrder(Integer orderID, boolean twoPhase) {
    if (Log.doTrace()) {
        Log.trace("TradeSLSBBean:queueOrder", orderID);
    }
            	
    if (TradeConfig.getOrderProcessingMode() == TradeConfig.ASYNCH_MANAGEDTHREAD) {
    
        Thread thread = managedThreadFactory.newThread(new CompleteOrderThread(orderID, twoPhase));
        
        thread.start();
    
    } else {
    
        try (JMSContext queueContext = queueConnectionFactory.createContext();) {
            TextMessage message = queueContext.createTextMessage();

            message.setStringProperty("command", "neworder");
            message.setIntProperty("orderID", orderID);
            message.setBooleanProperty("twoPhase", twoPhase);
            message.setText("neworder: orderID=" + orderID + " runtimeMode=EJB twoPhase=" + twoPhase);
            message.setLongProperty("publishTime", System.currentTimeMillis());
    		        		
            queueContext.createProducer().send(tradeBrokerQueue, message);
    		
        } catch (Exception e) {
            throw new EJBException(e.getMessage(), e); // pass the exception
        }
    }
}
 
Example 9
Source File: SearchJmsSender.java    From oneops with Apache License 2.0 5 votes vote down vote up
protected TextMessage createTextMessage(MessageData data) throws JMSException {
	TextMessage message = session.createTextMessage(data.getPayload());
	Map<String, String> headers = data.getHeaders();
	for (String key : headers.keySet()) {
		message.setStringProperty(key, headers.get(key));
	}
	return message;
}
 
Example 10
Source File: BaseTest.java    From a with Apache License 2.0 5 votes vote down vote up
private TextMessage createTextMessage(String testCorrId, String stringPropertyValue, String utfText, Queue replyQueue) throws JMSException {
    final TextMessage tm1 = session.createTextMessage(utfText);
    tm1.setStringProperty("myStringProperty", stringPropertyValue);
    tm1.setIntProperty("myIntProperty", 42);
    tm1.setDoubleProperty("myDoubleProperty", Math.PI);
    tm1.setJMSType("myJmsType");
    tm1.setJMSCorrelationID(testCorrId);
    tm1.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
    tm1.setJMSPriority(2);
    tm1.setJMSReplyTo(replyQueue);
    return tm1;
}
 
Example 11
Source File: JMSMessageTypesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void testTextMessageSendReceive(Connection producerConnection, Connection consumerConnection) throws Throwable {
   long time = System.currentTimeMillis();

   Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(getQueueName());

   MessageProducer producer = session.createProducer(queue);
   for (int i = 0; i < NUM_MESSAGES; i++) {
      instanceLog.debug("Sending " + i);
      TextMessage message = session.createTextMessage("text" + i);
      message.setStringProperty("text", "text" + i);
      producer.send(message);
   }

   Session sessionConsumer = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue consumerQueue = sessionConsumer.createQueue(getQueueName());
   final MessageConsumer consumer = sessionConsumer.createConsumer(consumerQueue);

   for (int i = 0; i < NUM_MESSAGES; i++) {
      TextMessage m = (TextMessage) consumer.receive(5000);
      Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m);
      Assert.assertEquals("text" + i, m.getText());
   }

   long taken = (System.currentTimeMillis() - time) / 1000;
   instanceLog.debug("taken = " + taken);
}
 
Example 12
Source File: InductorPublisher.java    From oneops with Apache License 2.0 5 votes vote down vote up
/**
 * Publish message.
 *
 * @param waitTaskName the wait task name
 * @param woType       the wo type
 * @throws JMSException the jMS exception
 */
public void publishMessage(String processId, String execId, CmsWorkOrderSimpleBase wo, String waitTaskName, String woType) throws JMSException {
    SimpleDateFormat format = new SimpleDateFormat(CmsConstants.SEARCH_TS_PATTERN);
    wo.getSearchTags().put(CmsConstants.REQUEST_ENQUE_TS, format.format(new Date()));
    //guarantee non empty-value for searchMap
    if (version != null && StringUtils.isNotBlank(version.getGitVersion())) {
        wo.getSearchTags().put(CONTROLLLER_VERSION_SEARCH_TAG, version.getGitVersion());
    } else {
        wo.getSearchTags().put(CONTROLLLER_VERSION_SEARCH_TAG, DEFAULT_VERSION);
    }
    TextMessage message = session.createTextMessage(gson.toJson(wo));
    String corelationId = processId + "!" + execId + "!" + waitTaskName+"!"+getCtxtId(wo);
    message.setJMSCorrelationID(corelationId);
    message.setStringProperty("task_id", corelationId);
    message.setStringProperty("type", woType);

    String queueName = getQueue(wo);
    bindingQueusMap.computeIfAbsent(queueName, k -> {
        try {
            return newMessageProducer(k);
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }).send(message);
    
    if (logger.isDebugEnabled()) {
        logger.debug("Published: " + message.getText());
    }

    logger.info("Posted message with id "+ corelationId +" to q: "+queueName);

}
 
Example 13
Source File: JMSConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void testDurableConsumerSelectorChange() throws Exception {

      // Receive a message with the JMS API
      connection.setClientID("test");
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destination = createDestination(session, destinationType);
      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(deliveryMode);
      MessageConsumer consumer = session.createDurableSubscriber((Topic) destination, "test", "color='red'", false);

      // Send the messages
      TextMessage message = session.createTextMessage("1st");
      message.setStringProperty("color", "red");
      producer.send(message);

      Message m = consumer.receive(1000);
      assertNotNull(m);
      assertEquals("1st", ((TextMessage) m).getText());

      // Change the subscription.
      consumer.close();
      consumer = session.createDurableSubscriber((Topic) destination, "test", "color='blue'", false);

      message = session.createTextMessage("2nd");
      message.setStringProperty("color", "red");
      producer.send(message);
      message = session.createTextMessage("3rd");
      message.setStringProperty("color", "blue");
      producer.send(message);

      // Selector should skip the 2nd message.
      m = consumer.receive(1000);
      assertNotNull(m);
      assertEquals("3rd", ((TextMessage) m).getText());

      assertNull(consumer.receiveNoWait());
   }
 
Example 14
Source File: PropertyFilterTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void filterProperties_message_allTypes() throws JMSException {
  TextMessage message = newMessageWithAllTypes();
  message.setStringProperty("b3", "00f067aa0ba902b7-00f067aa0ba902b7-1");

  PropertyFilter.filterProperties(message, Collections.singleton("b3"));

  assertThat(message).isEqualToIgnoringGivenFields(newMessageWithAllTypes(), "processAsExpired");
}
 
Example 15
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithString() throws JMSException {
    WeldContainer container = prepare();

    RawMessageConsumerBean bean = container.select(RawMessageConsumerBean.class).get();
    assertThat(bean.messages()).isEmpty();

    Queue q = jms.createQueue("queue-one");
    JMSProducer producer = jms.createProducer();
    TextMessage message = jms.createTextMessage("hello");
    message.setStringProperty("string", "value");
    message.setBooleanProperty("bool", true);
    message.setLongProperty("long", 100L);
    message.setByteProperty("byte", (byte) 5);
    message.setFloatProperty("float", 5.5f);
    message.setDoubleProperty("double", 10.3);
    message.setIntProperty("int", 23);
    message.setObjectProperty("object", "yop");
    message.setShortProperty("short", (short) 3);
    producer.send(q, message);

    await().until(() -> bean.messages().size() == 1);
    IncomingJmsMessage<?> incomingJmsMessage = bean.messages().get(0);
    IncomingJmsMessageMetadata metadata = incomingJmsMessage.getMetadata(IncomingJmsMessageMetadata.class)
            .orElseThrow(() -> new AssertionError("Metadata expected"));
    assertThat(incomingJmsMessage.getPayload()).isEqualTo("hello");
    assertThat(metadata.getBody(String.class)).isEqualTo("hello");
    assertThat(metadata.propertyExists("string")).isTrue();
    assertThat(metadata.propertyExists("missing")).isFalse();
    assertThat(metadata.getStringProperty("string")).isEqualTo("value");
    assertThat(metadata.getBooleanProperty("bool")).isTrue();
    assertThat(metadata.getLongProperty("long")).isEqualTo(100L);
    assertThat(metadata.getByteProperty("byte")).isEqualTo((byte) 5);
    assertThat(metadata.getFloatProperty("float")).isEqualTo(5.5f);
    assertThat(metadata.getDoubleProperty("double")).isEqualTo(10.3);
    assertThat(metadata.getIntProperty("int")).isEqualTo(23);
    assertThat(metadata.getObjectProperty("object")).isInstanceOf(String.class);
    assertThat(((String) message.getObjectProperty("object"))).isEqualTo("yop");
    assertThat(message.getShortProperty("short")).isEqualTo((short) 3);
}
 
Example 16
Source File: DurableSubscriptionTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
/**
 * JMS 1.1 6.11.1: A client can change an existing durable subscription by creating a durable
 * TopicSubscriber with the same name and a new topic and/or message selector, or NoLocal
 * attribute. Changing a durable subscription is equivalent to deleting and recreating it.
 * <br>
 * Test with a different selector.
 */
@Test
public void testDurableSubscriptionDifferentSelector() throws Exception {
   Connection conn = null;

   try {
      conn = createConnection();

      conn.setClientID("brookeburke");

      Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer prod = s.createProducer(ActiveMQServerTestCase.topic1);
      prod.setDeliveryMode(DeliveryMode.PERSISTENT);

      MessageConsumer durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci", "color = 'red' AND shape = 'square'", false);

      TextMessage tm = s.createTextMessage("A red square message");
      tm.setStringProperty("color", "red");
      tm.setStringProperty("shape", "square");

      prod.send(tm);

      conn.start();

      TextMessage rm = (TextMessage) durable.receive(5000);
      ProxyAssertSupport.assertEquals("A red square message", rm.getText());

      tm = s.createTextMessage("Another red square message");
      tm.setStringProperty("color", "red");
      tm.setStringProperty("shape", "square");
      prod.send(tm);

      // TODO: when subscriptions/durable subscription will be registered as MBean, use the JMX
      // interface to make sure the 'another red square message' is maintained by the
      // durable subascription
      // http://jira.jboss.org/jira/browse/JBMESSAGING-217

      conn.close();

      conn = createConnection();

      conn.setClientID("brookeburke");

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

      // modify the selector
      durable = s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "monicabelucci", "color = 'red'", false);

      conn.start();

      Message m = durable.receiveNoWait();

      // the durable subscription is destroyed and re-created. The red square message stored by
      // the previous durable subscription is lost and (hopefully) garbage collected.
      ProxyAssertSupport.assertNull(m);

      durable.close();

      s.unsubscribe("monicabelucci");
   } finally {
      if (conn != null) {
         conn.close();
      }
   }
}
 
Example 17
Source File: JMSSelectorTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"broker-port", "admin-username", "admin-password", "broker-hostname"})
@Test
public void testNegativeJMSSelectorConsumerProducer(String port,
                                                    String adminUsername,
                                                    String adminPassword,
                                                    String brokerHostname) throws NamingException, JMSException {
    String queueName = "testNegativeJMSSelectorConsumerProducer";
    InitialContext initialContext = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withTopic(queueName)
            .build();

    TopicConnectionFactory connectionFactory
            = (TopicConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.start();

    TopicSession subscriberSession = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    Topic topic = (Topic) initialContext.lookup(queueName);

    // Subscribe with a selector
    String propertyName = "MyProperty";
    String propertyValue = "propertyValue";
    String jmsPropertySelector = propertyName + " = '" + propertyValue + "'";
    TopicSubscriber consumer = subscriberSession.createSubscriber(topic, jmsPropertySelector, false);

    // publish messages with property
    TopicSession producerSession = connection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    TopicPublisher producer = producerSession.createPublisher(topic);

    // Send messages with a different property value
    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        TextMessage textMessage = producerSession.createTextMessage("Test message " + i);
        textMessage.setStringProperty(propertyName, propertyValue + "-1");
        producer.send(textMessage);
    }

    // consume messages
    Message message = consumer.receive(100);
    Assert.assertNull(message, "Message received. Shouldn't receive any messages.");

    producerSession.close();
    connection.close();
}
 
Example 18
Source File: InterceptorExample.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
   JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:61616");

   try (Connection connection = factory.createConnection()) {

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

      Queue interceptorQueue = session.createQueue("interceptorQueue");

      MessageProducer producer = session.createProducer(interceptorQueue);

      TextMessage textMessage = session.createTextMessage("A text message");
      textMessage.setStringProperty("SimpleAmqpInterceptor", "SimpleAmqpInterceptorValue");
      producer.send(textMessage);
   }
}
 
Example 19
Source File: JMSMessageConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void doTestSelectorsWithJMSXGroupID(boolean topic) throws Exception {

      Connection connection = createConnection();

      try {
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         Destination destination = null;
         if (topic) {
            destination = session.createTopic(getTopicName());
         } else {
            destination = session.createQueue(getQueueName());
         }

         MessageProducer producer = session.createProducer(destination);
         MessageConsumer consumer = session.createConsumer(destination, "JMSXGroupID = '1'");

         TextMessage message = session.createTextMessage();
         message.setText("group 1 - 1");
         message.setStringProperty("JMSXGroupID", "1");
         message.setIntProperty("JMSXGroupSeq", 1);
         producer.send(message);

         message = session.createTextMessage();
         message.setText("group 2");
         message.setStringProperty("JMSXGroupID", "2");
         producer.send(message);

         message = session.createTextMessage();
         message.setText("group 1 - 2");
         message.setStringProperty("JMSXGroupID", "1");
         message.setIntProperty("JMSXGroupSeq", -1);
         producer.send(message);

         connection.start();

         Message msg = consumer.receive(2000);
         assertNotNull(msg);
         assertTrue(msg instanceof TextMessage);
         assertEquals("group 1 - 1", ((TextMessage) msg).getText());
         msg = consumer.receive(2000);
         assertNotNull(msg);
         assertTrue(msg instanceof TextMessage);
         assertEquals("group 1 - 2", ((TextMessage) msg).getText());
      } finally {
         connection.close();
      }
   }
 
Example 20
Source File: LVQTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testLastValueQueueTopicConsumerUsingAddressQueueParameters() 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=true");
      assertEquals("topic", topic.getTopicName());

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

      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(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());

      //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();
   }
}