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

The following examples show how to use javax.jms.Message#setStringProperty() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: a   File: BaseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCopySelector() throws Exception{
    final String cmdLine = getConnectCommand() + "-" + CMD_COPY_QUEUE + " SOURCE.QUEUE -s \"identity='the One'\" TARGET.QUEUE";
    MessageProducer mp = session.createProducer(sourceQueue);

    Message theOne = session.createTextMessage("theOne"); // message
    theOne.setStringProperty("identity","the One");
    Message theOther = session.createTextMessage("theOther"); // message
    theOther.setStringProperty("identity","theOther");

    mp.send(theOne);
    mp.send(theOther);

    a.run(splitCmdLine(cmdLine));
    List<TextMessage> msgs = getAllMessages(session.createConsumer(sourceQueue));
    assertEquals(2,msgs.size());

    msgs = getAllMessages(session.createConsumer(targetQueue));
    assertEquals(1,msgs.size());
    assertEquals("theOne",msgs.get(0).getText());
}
 
Example 2
private List<Message> sendMessages(Session session, MessageProducer producer,
                                   final int deliveryMode,
                                   final int startIndex, final int count) throws Exception
{
    final List<Message> sentMessages = new ArrayList<>();
    for (int i = startIndex; i < startIndex + count; i++)
    {
        Message message = session.createTextMessage(UUID.randomUUID().toString());
        message.setIntProperty(INT_PROPERTY, i);
        message.setStringProperty(STRING_PROPERTY, UUID.randomUUID().toString());

        producer.send(message, deliveryMode, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
        sentMessages.add(message);
    }

    session.commit();
    return sentMessages;
}
 
Example 3
@Test
public void testBrowseWithSelector() throws Exception {
   Connection connection = createConnection();

   // Setup the scheduled Message
   scheduleMessage(connection, TimeUnit.SECONDS.toMillis(9));
   scheduleMessage(connection, TimeUnit.SECONDS.toMillis(10));
   scheduleMessage(connection, TimeUnit.SECONDS.toMillis(5));
   scheduleMessage(connection, TimeUnit.SECONDS.toMillis(45));

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

   // Create the Browse Destination and the Reply To location
   Destination requestBrowse = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION);
   Destination browseDest = session.createTemporaryTopic();

   // Create the "Browser"
   MessageConsumer browser = session.createConsumer(browseDest, ScheduledMessage.AMQ_SCHEDULED_DELAY + " = 45000");

   connection.start();

   // Send the browse request
   MessageProducer producer = session.createProducer(requestBrowse);
   Message request = session.createMessage();
   request.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_BROWSE);
   request.setJMSReplyTo(browseDest);
   producer.send(request);

   // Now try and receive the one we selected
   Message message = browser.receive(5000);
   assertNotNull(message);
   assertEquals(45000, message.getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY));

   // Now check if there are anymore, there shouldn't be
   message = browser.receive(5000);
   assertNull(message);
}
 
Example 4
@Test
public void parameterAnnotationWithJdkProxy() throws JMSException {
	ProxyFactory pf = new ProxyFactory(sample);
	listener = (JmsEndpointSampleInterface) pf.getProxy();

	containerFactory.setMessageConverter(new UpperCaseMessageConverter());

	MethodJmsListenerEndpoint endpoint = createDefaultMethodJmsEndpoint(
			JmsEndpointSampleInterface.class, "handleIt", String.class, String.class);
	Message message = new StubTextMessage("foo-bar");
	message.setStringProperty("my-header", "my-value");

	invokeListener(endpoint, message);
	assertListenerMethodInvocation("handleIt");
}
 
Example 5
@Test
public void parameterAnnotationWithJdkProxy() throws JMSException {
	ProxyFactory pf = new ProxyFactory(sample);
	listener = (JmsEndpointSampleInterface) pf.getProxy();

	containerFactory.setMessageConverter(new UpperCaseMessageConverter());

	MethodJmsListenerEndpoint endpoint = createDefaultMethodJmsEndpoint(
			JmsEndpointSampleInterface.class, "handleIt", String.class, String.class);
	Message message = new StubTextMessage("foo-bar");
	message.setStringProperty("my-header", "my-value");

	invokeListener(endpoint, message);
	assertListenerMethodInvocation("handleIt");
}
 
Example 6
public void testSetNullPropertyName() throws JMSException {
   Message msg = new ActiveMQMessage();

   try {
      msg.setStringProperty(null, "Cheese");
      fail("Should have thrown exception");
   } catch (IllegalArgumentException e) {
      LOG.info("Worked, caught: " + e);
   }
}
 
Example 7
/**
 * if a property is set as a <code>java.lang.String</code>,
 * it can also be read as a <code>double</code> as long as the <code>String</code>
 * is a correct representation of a <code>double</code> (e.g. <code>"3.14159"</code>).
 */
@Test
public void testString2Double_1() {
   try {
      Message message = senderSession.createMessage();
      message.setStringProperty("pi", "3.14159");
      Assert.assertEquals(3.14159, message.getDoubleProperty("pi"), 0);
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 8
/**
 * if a property is set as a <code>java.lang.String</code>,
 * it can also be read as a <code>float</code> as long as the <code>String</code>
 * is a correct representation of a <code>float</code> (e.g. <code>"3.14159"</code>).
 */
@Test
public void testString2Float_1() {
   try {
      Message message = senderSession.createMessage();
      message.setStringProperty("pi", "3.14159");
      Assert.assertEquals(3.14159F, message.getFloatProperty("pi"), 0);
   } catch (JMSException e) {
      fail(e);
   }
}
 
Example 9
@Test
public void selector() throws Exception
{
    Topic topic = createTopic(getTestName());
    final Connection connection = getConnection();
    try
    {
        final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MessageConsumer subscriber = session.createConsumer(topic, "id='B'");
        final MessageProducer producer = session.createProducer(topic);
        Message message1 = session.createMessage();
        message1.setStringProperty("id", "A");
        producer.send(message1);
        Message message2 = session.createMessage();
        message2.setStringProperty("id", "B");
        producer.send(message2);

        connection.start();
        final Message receivedMessage = subscriber.receive(getReceiveTimeout());
        assertNotNull("Message not received", receivedMessage);
        assertEquals("Unexpected message received", "B", receivedMessage.getStringProperty("id"));
    }
    finally
    {
        connection.close();
    }
}
 
Example 10
Source Project: qpid-broker-j   File: MessageProvider.java    License: Apache License 2.0 5 votes vote down vote up
protected void setCustomProperty(Message message, String propertyName, Object propertyValue) throws JMSException
{
    if (propertyValue instanceof Integer)
    {
        message.setIntProperty(propertyName, ((Integer) propertyValue).intValue());
    }
    else if (propertyValue instanceof Long)
    {
        message.setLongProperty(propertyName, ((Long) propertyValue).longValue());
    }
    else if (propertyValue instanceof Boolean)
    {
        message.setBooleanProperty(propertyName, ((Boolean) propertyValue).booleanValue());
    }
    else if (propertyValue instanceof Byte)
    {
        message.setByteProperty(propertyName, ((Byte) propertyValue).byteValue());
    }
    else if (propertyValue instanceof Double)
    {
        message.setDoubleProperty(propertyName, ((Double) propertyValue).doubleValue());
    }
    else if (propertyValue instanceof Float)
    {
        message.setFloatProperty(propertyName, ((Float) propertyValue).floatValue());
    }
    else if (propertyValue instanceof Short)
    {
        message.setShortProperty(propertyName, ((Short) propertyValue).shortValue());
    }
    else if (propertyValue instanceof String)
    {
        message.setStringProperty(propertyName, (String) propertyValue);
    }
    else
    {
        message.setObjectProperty(propertyName, propertyValue);
    }
}
 
Example 11
private Message createTextMessage(Session session1, String group) throws JMSException {
   Message message = session1.createTextMessage("hello");
   message.setStringProperty("JMSXGroupID", group);
   return message;
}
 
Example 12
@Test(timeout = 60 * 1000)
public void testInterleavedOfflineSubscriptionCanConsumeAfterUnsub() throws Exception {
   // create offline subs 1
   Connection con = createConnection("offCli1");
   Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);
   session.close();
   con.close();

   // create offline subs 2
   con = createConnection("offCli2");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", null, true);
   session.close();
   con.close();

   // send messages
   con = createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(null);

   int sent = 0;
   for (int i = 0; i < 10; i++) {
      boolean filter = (int) (Math.random() * 2) >= 1;

      sent++;

      Message message = session.createMessage();
      message.setStringProperty("filter", filter ? "true" : "false");
      producer.send(topic, message);
   }

   Thread.sleep(1 * 1000);

   Connection con2 = createConnection("offCli1");
   Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session2.unsubscribe("SubsId");
   session2.close();
   con2.close();

   // consume all messages
   con = createConnection("offCli2");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", null, true);
   DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener("SubsId");
   consumer.setMessageListener(listener);

   Thread.sleep(3 * 1000);

   session.close();
   con.close();

   assertEquals("offline consumer got all", sent, listener.count);
}
 
Example 13
@Test
public void testOfflineSubscriptionCanConsumeAfterOnlineSubs() throws Exception {
   Connection con = createConnection("offCli1");
   Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);
   session.close();
   con.close();

   con = createConnection("offCli2");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);
   session.close();
   con.close();

   Connection con2 = createConnection("onlineCli1");
   Session session2 = con2.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer2 = session2.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);
   DurableSubscriptionOfflineTestListener listener2 = new DurableSubscriptionOfflineTestListener();
   consumer2.setMessageListener(listener2);

   // send messages
   con = createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(null);

   int sent = 0;
   for (int i = 0; i < 10; i++) {
      sent++;
      Message message = session.createMessage();
      message.setStringProperty("filter", "true");
      producer.send(topic, message);
   }

   Thread.sleep(1 * 1000);
   session.close();
   con.close();

   // test online subs
   Thread.sleep(3 * 1000);
   session2.close();
   con2.close();
   assertEquals(sent, listener2.count);

   // restart broker
   broker.stop();
   createBroker(false /*deleteAllMessages*/);

   // test offline
   con = createConnection("offCli1");
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);

   Connection con3 = createConnection("offCli2");
   Session session3 = con3.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer3 = session3.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true);

   DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener();
   consumer.setMessageListener(listener);
   DurableSubscriptionOfflineTestListener listener3 = new DurableSubscriptionOfflineTestListener();
   consumer3.setMessageListener(listener3);

   Thread.sleep(3 * 1000);

   session.close();
   con.close();
   session3.close();
   con3.close();

   assertEquals(sent, listener.count);
   assertEquals(sent, listener3.count);
}
 
Example 14
Source Project: Thunder   File: MQSelectorUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void setResponseSelector(Message message, String selector) throws JMSException {
    message.setStringProperty(SelectorType.RESPONSE_SELECTOR.toString(), selector);
}
 
Example 15
Source Project: qpid-jms   File: MessageIntegrationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testSendMessageWithApplicationProperties() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

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

        ApplicationPropertiesSectionMatcher appPropsMatcher = new ApplicationPropertiesSectionMatcher(true);
        appPropsMatcher.withEntry(NULL_STRING_PROP, nullValue());
        appPropsMatcher.withEntry(STRING_PROP, equalTo(STRING_PROP_VALUE));
        appPropsMatcher.withEntry(BOOLEAN_PROP, equalTo(BOOLEAN_PROP_VALUE));
        appPropsMatcher.withEntry(BYTE_PROP, equalTo(BYTE_PROP_VALUE));
        appPropsMatcher.withEntry(SHORT_PROP, equalTo(SHORT_PROP_VALUE));
        appPropsMatcher.withEntry(INT_PROP, equalTo(INT_PROP_VALUE));
        appPropsMatcher.withEntry(LONG_PROP, equalTo(LONG_PROP_VALUE));
        appPropsMatcher.withEntry(FLOAT_PROP, equalTo(FLOAT_PROP_VALUE));
        appPropsMatcher.withEntry(DOUBLE_PROP, equalTo(DOUBLE_PROP_VALUE));

        MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true).withDurable(equalTo(true));

        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);

        MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true).withTo(equalTo(queueName));

        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(headersMatcher);
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(propsMatcher);
        messageMatcher.setApplicationPropertiesMatcher(appPropsMatcher);
        //TODO: currently we aren't sending any body section, decide if this is allowed
        //messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(null));
        testPeer.expectTransfer(messageMatcher);

        Message message = session.createMessage();
        message.setStringProperty(NULL_STRING_PROP, NULL_STRING_PROP_VALUE);
        message.setStringProperty(STRING_PROP, STRING_PROP_VALUE);
        message.setBooleanProperty(BOOLEAN_PROP, BOOLEAN_PROP_VALUE);
        message.setByteProperty(BYTE_PROP, BYTE_PROP_VALUE);
        message.setShortProperty(SHORT_PROP, SHORT_PROP_VALUE);
        message.setIntProperty(INT_PROP, INT_PROP_VALUE);
        message.setLongProperty(LONG_PROP, LONG_PROP_VALUE);
        message.setFloatProperty(FLOAT_PROP, FLOAT_PROP_VALUE);
        message.setDoubleProperty(DOUBLE_PROP, DOUBLE_PROP_VALUE);

        producer.send(message);

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

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 16
@Test(timeout = 30 * 1000)
public void testConsumerLateToBigPartyGetsNewGroup() throws Exception {

   final int perBatch = 2;
   int[] counters = {perBatch, perBatch, perBatch};

   CountDownLatch startSignal = new CountDownLatch(0);
   CountDownLatch doneSignal = new CountDownLatch(2);
   CountDownLatch worker1Started = new CountDownLatch(1);
   CountDownLatch worker2Started = new CountDownLatch(1);

   messageCount.put("worker1", 0);
   messageGroups.put("worker1", new HashSet<String>());
   Worker worker1 = new Worker(connection, destination, "worker1", startSignal, doneSignal, counters, messageCount, messageGroups, worker1Started);
   messageCount.put("worker2", 0);
   messageGroups.put("worker2", new HashSet<String>());
   Worker worker2 = new Worker(connection, destination, "worker2", startSignal, doneSignal, counters, messageCount, messageGroups, worker2Started);

   new Thread(worker1).start();

   for (int i = 0; i < perBatch; i++) {
      Message msga = session.createTextMessage("hello c");
      msga.setStringProperty("JMSXGroupID", "A");
      producer.send(msga);

      Message msgb = session.createTextMessage("hello b");
      msgb.setStringProperty("JMSXGroupID", "B");
      producer.send(msgb);
   }

   // ensure this chap, late to the party gets a new group
   new Thread(worker2).start();

   // wait for presence before new group
   worker2Started.await();

   for (int i = 0; i < perBatch; i++) {
      Message msgc = session.createTextMessage("hello a");
      msgc.setStringProperty("JMSXGroupID", "C");
      producer.send(msgc);
   }

   doneSignal.await();

   log.info("worker1  received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"));
   assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2 * perBatch, messageCount.get("worker1").intValue());
   assertEquals("worker1 received " + messageCount.get("worker1") + " messages from groups " + messageGroups.get("worker1"), 2, messageGroups.get("worker1").size());

   log.info("worker2  received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"));
   assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 2 * perBatch, messageCount.get("worker1").intValue());
   assertEquals("worker2 received " + messageCount.get("worker2") + " messages from groups " + messageGroups.get("worker2"), 1, messageGroups.get("worker2").size());
}
 
Example 17
Source Project: qpid-broker-j   File: SortedQueueTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSortedQueueWithAscendingSortedKeys() throws Exception
{
    final String queueName = getTestName();
    final Queue queue = createSortedQueue(queueName, TEST_SORT_KEY);

    final Connection consumerConnection = getConnectionBuilder().setPrefetch(0).build();
    try
    {
        final Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MessageConsumer consumer = consumerSession.createConsumer(queue);
        final CountDownLatch receiveLatch = new CountDownLatch(NUMBER_OF_MESSAGES);
        consumer.setMessageListener(new CountingMessageListener(receiveLatch, consumerSession));
        consumerConnection.start();

        final Connection producerConnection = getConnection();
        try
        {
            final Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
            final MessageProducer producer = producerSession.createProducer(queue);

            for (int i = 0; i < NUMBER_OF_MESSAGES; i++)
            {
                final Message message = producerSession.createMessage();
                message.setStringProperty(TEST_SORT_KEY, AscendingSortedKeys.getNextKey());
                producer.send(message);
                producerSession.commit();
            }
        }
        finally
        {
            producerConnection.close();
        }
        assertTrue("Messages were not received during expected time",
                   receiveLatch.await(getReceiveTimeout() * NUMBER_OF_MESSAGES, TimeUnit.MILLISECONDS));
    }
    finally
    {
        consumerConnection.close();
    }
}
 
Example 18
Source Project: qpid-jms   File: MessageIntegrationTest.java    License: Apache License 2.0 4 votes vote down vote up
private void doSendMessageWithInvalidPropertyNameTestImpl(boolean disableValidation) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer, "?jms.validatePropertyNames=" + !disableValidation);
        connection.start();

        testPeer.expectBegin();

        String invalidPropName = "invalid-name";
        String value = "valueA";
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");

        Message message = session.createMessage();

        if (!disableValidation) {
            try {
                message.setStringProperty(invalidPropName, value);
                fail("Expected exception to be thrown");
            } catch (IllegalArgumentException iae) {
                // expected
            }
        } else {
            message.setStringProperty(invalidPropName, value);

            MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true);
            MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
            MessagePropertiesSectionMatcher propsMatcher = new MessagePropertiesSectionMatcher(true);
            ApplicationPropertiesSectionMatcher appPropsMatcher = new ApplicationPropertiesSectionMatcher(true);
            appPropsMatcher.withEntry(invalidPropName, equalTo(value));

            TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
            messageMatcher.setHeadersMatcher(headersMatcher);
            messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
            messageMatcher.setPropertiesMatcher(propsMatcher);

            testPeer.expectSenderAttach();

            MessageProducer producer = session.createProducer(queue);

            testPeer.expectTransfer(messageMatcher);

            producer.send(message);
        }

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

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 19
/**
 * Set a type id for the given payload object on the given JMS Message.
 * <p>The default implementation consults the configured type id mapping and
 * sets the resulting value (either a mapped id or the raw Java class name)
 * into the configured type id message property.
 * @param object the payload object to set a type id for
 * @param message the JMS Message to set the type id on
 * @throws JMSException if thrown by JMS methods
 * @see #getJavaTypeForMessage(javax.jms.Message)
 * @see #setTypeIdPropertyName(String)
 * @see #setTypeIdMappings(java.util.Map)
 */
protected void setTypeIdOnMessage(Object object, Message message) throws JMSException {
	if (this.typeIdPropertyName != null) {
		String typeId = this.classIdMappings.get(object.getClass());
		if (typeId == null) {
			typeId = object.getClass().getName();
		}
		message.setStringProperty(this.typeIdPropertyName, typeId);
	}
}
 
Example 20
protected void applyErrorDetails(final Message destinationMessage, final Exception exception) throws JMSException {

        destinationMessage.setStringProperty(EXCEPTION_MESSAGE_PROPERTY, exception.getMessage());

        StringWriter stackTraceWriter = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTraceWriter));

        destinationMessage.setStringProperty(EXCEPTION_STACKTRACE_PROPERTY, stackTraceWriter.toString());
    }