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

The following examples show how to use javax.jms.TextMessage#getStringProperty() . 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: JmsSendReceiveTestSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if the messages received are valid.
 *
 * @param receivedMessages - list of received messages.
 * @throws JMSException
 */
protected void assertMessagesReceivedAreValid(List<Message> receivedMessages) throws JMSException {
   List<Object> copyOfMessages = Arrays.asList(receivedMessages.toArray());
   int counter = 0;

   if (data.length != copyOfMessages.size()) {
      for (Iterator<Object> iter = copyOfMessages.iterator(); iter.hasNext(); ) {
         TextMessage message = (TextMessage) iter.next();
      }
   }

   assertEquals("Not enough messages received", data.length, receivedMessages.size());

   for (int i = 0; i < data.length; i++) {
      TextMessage received = (TextMessage) receivedMessages.get(i);
      String text = received.getText();
      String stringProperty = received.getStringProperty("stringProperty");
      int intProperty = received.getIntProperty("intProperty");

      assertEquals("Message: " + i, data[i], text);
      assertEquals(data[i], stringProperty);
      assertEquals(i, intProperty);
   }
}
 
Example 2
Source File: ManagedPropertiesMessageCoordinator.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public void onMessage(Message message) {

      try {
          if (message instanceof TextMessage) {
              TextMessage tm = (TextMessage) message;
              // TODO use MapMessage and allow update of more then one property at one
              String propertyName = tm.getText();
              String value = tm.getStringProperty(propertyName);
              System.out.printf("*****************  Processed message (listener 1) 'key=%s' 'value=%s'. hashCode={%d}\n", propertyName, value, this.hashCode());

              propertiesLoader.setProperty(propertyName, value);
          }
      } catch (JMSException e) {
          Log.error("Error while processing jms message ", e);
      }
  }
 
Example 3
Source File: ManagedPropertiesMessageCoordinator.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
*/
  @Override
  public void onMessage(Message message) {

      try {
          if (message instanceof TextMessage) {
              TextMessage tm = (TextMessage) message;
              // TODO use MapMessage and allow update of more then one property at one
              String propertyName = tm.getText();
              String value = tm.getStringProperty(propertyName);
              System.out.printf("*****************  Processed message (listener 1) 'key=%s' 'value=%s'. hashCode={%d}\n", propertyName, value, this.hashCode());

              propertiesLoader.setProperty(propertyName, value);
          }
      } catch (JMSException e) {
          Log.error("Error while processing jms message ", e);
      }
  }
 
Example 4
Source File: DlqListener.java    From oneops with Apache License 2.0 5 votes vote down vote up
private String getMessageId(TextMessage message) throws JMSException {
    String msgId = message.getStringProperty("msgId");
    if (msgId == null) {
    	msgId = message.getStringProperty("sourceId");
    }
    return msgId;
}
 
Example 5
Source File: SearchListener.java    From oneops with Apache License 2.0 5 votes vote down vote up
private static String getMessageId(TextMessage message) throws JMSException {
    String msgId = message.getStringProperty("msgId");
    String type = getMessageType(message);
    if (msgId == null || ("delete".equals(message.getStringProperty("action")) && ("cm_ci".equals(type) || "namespace".equals(type)))) {
        return message.getStringProperty("sourceId");
    }
    return msgId;
}
 
Example 6
Source File: SearchListener.java    From oneops with Apache License 2.0 5 votes vote down vote up
private static String getMessageType(TextMessage message) throws JMSException {
    String type = message.getStringProperty("type");
    if (type == null) {
        return message.getStringProperty("source");
    }
    return type;
}
 
Example 7
Source File: InterceptorExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
   ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616?incomingInterceptorList=" + SimpleInterceptor.class.getName());
   try (Connection connection = cf.createConnection()) {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Queue queue = session.createQueue("exampleQueue");

      MessageProducer producer = session.createProducer(queue);

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

      System.out.println("Sending message [" + message.getText() +
                            "] with String property: " +
                            message.getStringProperty("newproperty"));

      producer.send(message);

      MessageConsumer messageConsumer = session.createConsumer(queue);

      connection.start();

      TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

      System.out.println("Received message [" + messageReceived.getText() +
                            "] with String property: " +
                            messageReceived.getStringProperty("newproperty"));

      if (messageReceived.getStringProperty("newproperty") == null) {
         throw new IllegalStateException("Check your configuration as the example interceptor wasn't actually called!");
      }
   }
}
 
Example 8
Source File: BrokerPluginExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void sendConsumeAMQP() throws JMSException {
   Connection connection = null;
   ConnectionFactory connectionFactory = new JmsConnectionFactory("amqp://localhost:5672");

   try {

      // Create an amqp qpid 1.0 connection
      connection = connectionFactory.createConnection();

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

      // Create a sender
      Queue queue = session.createQueue("exampleQueue");
      MessageProducer sender = session.createProducer(queue);

      // send a few simple message
      sender.send(session.createTextMessage("Hello world "));

      connection.start();

      // create a moving receiver, this means the message will be removed from the queue
      MessageConsumer consumer = session.createConsumer(queue);

      // receive the simple message
      TextMessage m = (TextMessage) consumer.receive(5000);

      if (m.getStringProperty("count") == null) {
         throw new RuntimeException(("missed property count"));
      }

      System.out.println("message = " + m.getText() + " property count (added by interceptor = " + m.getStringProperty("count") + ")");

   } finally {
      if (connection != null) {
         // close the connection
         connection.close();
      }
   }
}
 
Example 9
Source File: GroupingTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void send(JMSContext ctx, Queue testQueue, String groupID1, JMSProducer producer1, int j) throws JMSException {
   TextMessage message = ctx.createTextMessage("Message" + j);
   producer1.send(testQueue, message);
   String prop = message.getStringProperty("JMSXGroupID");
   assertNotNull(prop);
   assertEquals(groupID1, prop);
}
 
Example 10
Source File: JmsSendReceiveTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if the messages received are valid.
 *
 * @param receivedMessages - list of received messages.
 * @throws JMSException
 */
protected void assertMessagesReceivedAreValid(List<Message> receivedMessages) throws JMSException {
   List<Object> copyOfMessages = Arrays.asList(receivedMessages.toArray());
   int counter = 0;

   if (data.length != copyOfMessages.size()) {
      for (Iterator<Object> iter = copyOfMessages.iterator(); iter.hasNext(); ) {
         TextMessage message = (TextMessage) iter.next();
         if (LOG.isInfoEnabled()) {
            LOG.info("<== " + counter++ + " = " + message.getText());
         }
      }
   }

   assertEquals("Not enough messages received", data.length, receivedMessages.size());

   for (int i = 0; i < data.length; i++) {
      TextMessage received = (TextMessage) receivedMessages.get(i);
      String text = received.getText();
      String stringProperty = received.getStringProperty("stringProperty");
      int intProperty = received.getIntProperty("intProperty");

      if (verbose) {
         if (LOG.isDebugEnabled()) {
            LOG.info("Received Text: " + text);
         }
      }

      assertEquals("Message: " + i, data[i], text);
      assertEquals(data[i], stringProperty);
      assertEquals(i, intProperty);
   }
}
 
Example 11
Source File: TraceeMessageListenerAndProducerIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testContextIsPropagatedForthAndBack() throws JMSException, InterruptedException {

	Tracee.getBackend().put("foo", "bar");

	final Connection connection = connectionFactory.createConnection();
	try {
		connection.start();
		final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		try {
			final MessageConsumer consumer = session.createConsumer(responses);

			final TextMessage textMessage = session.createTextMessage("foo");
			final MessageProducer producer = TraceeMessageWriter.wrap(session.createProducer(mdb));
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			producer.send(textMessage);

			final TextMessage response = (TextMessage) consumer.receive(1000);

			assertThat("response within 1 second", response, notNullValue());
			assertThat(response.getText(), equalTo("foo"));
			final String traceeContextAsString = response.getStringProperty(TraceeConstants.TPIC_HEADER);
			final Map<String, String> traceeContext = new HttpHeaderTransport().parse(singletonList(traceeContextAsString));
			assertThat(traceeContext, Matchers.hasEntry("foo", "bar"));
		} finally {
			session.close();
		}
	} finally {
		connection.close();
	}
}
 
Example 12
Source File: JmsPropertyTypeTest.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 testStringProperty(String port,
                               String adminUsername,
                               String adminPassword,
                               String brokerHostname) throws NamingException, JMSException {
    String queueName = "testStringProperty";

    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port)
            .withQueue(queueName)
            .build();

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

    // send messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);
    String stringPropertyName = "StringProperty";
    String stringProperty = "!@#$%^QWERTYqwerty123456";
    TextMessage textMessage = producerSession.createTextMessage("Test message");
    textMessage.setStringProperty(stringPropertyName, stringProperty);
    producer.send(textMessage);
    producerSession.close();

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

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message, "Message was not received");
    String receivedStringProperty = message.getStringProperty(stringPropertyName);
    Assert.assertEquals(stringProperty, receivedStringProperty, "String property not matched.");

    subscriberSession.close();
    connection.close();
}
 
Example 13
Source File: CmsListener.java    From oneops with Apache License 2.0 4 votes vote down vote up
private void processMessage(TextMessage message) throws JsonSyntaxException, JMSException {
  String source = message.getStringProperty("source");
  logger.info("Message from source: " + source);
  String processKey;
  String pokeActivitiProcessId = null;
  Map<String, Object> wfParams = new HashMap<String, Object>();
  if (source.equals("deployment")) {
    CmsDeployment dpmt = gson.fromJson(message.getText(), CmsDeployment.class);
    if (dpmt == null) {
      logger.error("Got bad message:" + message.getText() + "/n end msg");
      return;
    } else {
      if (isDeployerEnabled(dpmt.getNsPath())) {
        notifyIfRequired(dpmt);
        logger.info("Executing deployment using Deployer : " + dpmt.getDeploymentId());
        startDeployment(dpmt);
      } else {
        logger.info("Executing deployment using activiti : " + dpmt.getDeploymentId());
        processKey = getDpmtProcessKey(dpmt);

        if (processKey != null && !processKey.equals("skip")) {
          wfParams.put("dpmt", dpmt);
          wfParams.put("execOrder", 1);
          pokeActivitiProcessId = wfController.startDpmtProcess(processKey, wfParams);
        } else {
          notifyIfRequired(dpmt);
        }
      }
    }


  } else if (source.equals("opsprocedure")) {
    CmsOpsProcedure proc = gson.fromJson(message.getText(), CmsOpsProcedure.class);
    if (proc == null) {
      logger.error("Got bad message:" + message.getText() + "/n end msg");
      return;
    }
    //logger.info()
    if (isDeployerEnabled(proc.getNsPath())) {
      logger.info("Executing procedure using ProcedureRunner : " + proc.getProcedureId());
      startProcedure(proc);
    }
    else {
      processKey = getOpsProcedureProcessKey(proc);
      if (processKey != null && !processKey.equals("skip")) {
        wfParams.put("proc", proc);
        wfParams.put("execOrder", 1);
      } else {
        return;
      }
      pokeActivitiProcessId = wfController.startOpsProcess(processKey, wfParams);
    }
  } else if (source.equals("release")) {
    CmsRelease release = gson.fromJson(message.getText(), CmsRelease.class);
    if (release == null) {
      logger.error("Got bad message:" + message.getText() + "/n end msg");
      return;
    }
    processKey = getDeployReleaseProcessKey(release);
    if (processKey != null && !processKey.equals("skip")) {
      wfParams.put("release", release);
    } else {
      return;
    }
    pokeActivitiProcessId = wfController.startReleaseProcess(processKey, wfParams);
  } else {
    logger.error("Unsupported source:" + source);
    return;
  }
  if (pokeActivitiProcessId != null) {
    wfController.pokeProcess(pokeActivitiProcessId);
  }
}
 
Example 14
Source File: BrokerPluginExample.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private static void sendConsumeCore() throws JMSException {
   Connection connection = null;
   try {
      // Perform a lookup on the Connection Factory
      ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");

      Queue queue = new ActiveMQQueue("exampleQueue");

      // Create a JMS Connection
      connection = cf.createConnection();

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

      // Create a JMS Message Producer
      MessageProducer producer = session.createProducer(queue);

      // Create a Text Message
      TextMessage message = session.createTextMessage("This is a text message");

      // Send the Message
      producer.send(message);

      // Create a JMS Message Consumer
      MessageConsumer messageConsumer = session.createConsumer(queue);

      // Start the Connection
      connection.start();

      // Receive the message
      TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

      if (messageReceived.getStringProperty("count") == null) {
         throw new RuntimeException(("missed property count"));
      }

      System.out.println("message = " + messageReceived.getText() + " property count (added by interceptor = " + messageReceived.getStringProperty("count") + ")");

   } finally {
      if (connection != null) {
         connection.close();
      }
   }

}
 
Example 15
Source File: GroupingTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testGrouping() throws Exception {
   ConnectionFactory fact = getCF();
   Connection connection = fact.createConnection();

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

   MessageProducer producer = session.createProducer(queue);

   MessageConsumer consumer1 = session.createConsumer(queue);
   MessageConsumer consumer2 = session.createConsumer(queue);
   MessageConsumer consumer3 = session.createConsumer(queue);

   connection.start();

   String jmsxgroupID = null;

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

      message.setText("Message" + j);

      setProperty(message);

      producer.send(message);

      String prop = message.getStringProperty("JMSXGroupID");

      assertNotNull(prop);

      if (jmsxgroupID != null) {
         assertEquals(jmsxgroupID, prop);
      } else {
         jmsxgroupID = prop;
      }
   }

   //All msgs should go to the first consumer
   for (int j = 0; j < 100; j++) {
      TextMessage tm = (TextMessage) consumer1.receive(10000);

      assertNotNull(tm);

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

      assertEquals(tm.getStringProperty("JMSXGroupID"), jmsxgroupID);
   }

   connection.close();

}
 
Example 16
Source File: GroupingTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testManyGroups() throws Exception {
   ConnectionFactory fact = getCF();
   Assume.assumeFalse("only makes sense withOUT auto-group", ((ActiveMQConnectionFactory) fact).isAutoGroup());

   Connection connection = fact.createConnection();

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

   MessageProducer producer = session.createProducer(queue);

   MessageConsumer consumer1 = session.createConsumer(queue);
   MessageConsumer consumer2 = session.createConsumer(queue);
   MessageConsumer consumer3 = session.createConsumer(queue);

   connection.start();

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

      message.setText("Message" + j);

      message.setStringProperty("_AMQ_GROUP_ID", "" + (j % 10));

      producer.send(message);

      String prop = message.getStringProperty("JMSXGroupID");

      assertNotNull(prop);

   }

   int msg1 = flushMessages(consumer1);
   int msg2 = flushMessages(consumer2);
   int msg3 = flushMessages(consumer3);

   assertNotSame(0, msg1);
   assertNotSame(0, msg2);
   assertNotSame(0, msg2);

   consumer1.close();
   consumer2.close();
   consumer3.close();

   connection.close();

}