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

The following examples show how to use javax.jms.TextMessage#getText() . 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: LoadClient.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected String consume() throws Exception {
   Connection con = null;
   MessageConsumer c = consumer;
   if (connectionPerMessage) {
      con = factory.createConnection();
      con.start();
      Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      c = s.createConsumer(getConsumeDestination());
   }
   TextMessage result = (TextMessage) c.receive(timeout);
   if (result != null) {
      if (audit.isDuplicate(result.getJMSMessageID())) {
         throw new JMSException("Received duplicate " + result.getText());
      }
      if (!audit.isInOrder(result.getJMSMessageID())) {
         throw new JMSException("Out of order " + result.getText());
      }

      if (connectionPerMessage) {
         Thread.sleep(SLEEP_TIME);//give the broker a chance
         con.close();
      }
   }
   return result != null ? result.getText() : null;
}
 
Example 2
Source File: ProducerTool.java    From chipster with MIT License 6 votes vote down vote up
protected void sendLoop(Session session, MessageProducer producer) throws Exception {

        for (int i = 0; i < messageCount || messageCount == 0; i++) {

            TextMessage message = session.createTextMessage(createMessageText(i));

            if (verbose) {
                String msg = message.getText();
                if (msg.length() > 50) {
                    msg = msg.substring(0, 50) + "...";
                }
                System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
            }

            producer.send(message);

            if (transacted && (i % batch == 0)) {
                System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
                session.commit();
            }
            Thread.sleep(sleepTime);
        }
    }
 
Example 3
Source File: IntegrationTest.java    From kubernetes-integration-test with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetry() throws Exception {
    log.info("Send testRetry");
    jmsTemplate.convertAndSend("user.in", "{\"email\":\"[email protected]\"}");
    TextMessage message = (TextMessage) jmsTemplate.receive("user.out");
    String response = message.getText();

    log.info("Response: {}",response);

    assertEquals("[email protected]", JsonPath.read(response, "$.email"));
    assertEquals("5551230000", JsonPath.read(response, "$.phone"));
    assertEquals("Test State", JsonPath.read(response, "$.address.state"));
    assertEquals("Test City", JsonPath.read(response, "$.address.city"));
    assertEquals("2 Test St", JsonPath.read(response, "$.address.address"));
    assertEquals("T002", JsonPath.read(response, "$.address.zip"));
}
 
Example 4
Source File: IntegrationTest.java    From kubernetes-integration-test with Apache License 2.0 6 votes vote down vote up
@Test
public void testSucc() throws Exception {
    log.info("Send testSucc");
    jmsTemplate.convertAndSend("user.in", "{\"email\":\"[email protected]\"}");
    TextMessage message = (TextMessage) jmsTemplate.receive("user.out");
    String response = message.getText();

    log.info("Response: {}",response);

    assertEquals("[email protected]", JsonPath.read(response, "$.email"));
    assertEquals("5551234567", JsonPath.read(response, "$.phone"));
    assertEquals("Test State", JsonPath.read(response, "$.address.state"));
    assertEquals("Test City", JsonPath.read(response, "$.address.city"));
    assertEquals("1 Test St", JsonPath.read(response, "$.address.address"));
    assertEquals("T001", JsonPath.read(response, "$.address.zip"));

}
 
Example 5
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 6
Source File: ProperConnectionShutdownTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public String receiveMessage() throws JMSException {

            Connection connection = null;
            Session session = null;
            MessageConsumer consumer = null;
            try {
                connection = connectionFactory.createConnection();
                connection.start();

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

                // Create a MessageConsumer from the Session to the Topic or Queue
                consumer = session.createConsumer(chatQueue);

                // Wait for a message
                TextMessage message = (TextMessage) consumer.receive(1000);

                return message.getText();
            } finally {
                if (consumer != null) {
                    consumer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            }

        }
 
Example 7
Source File: RequesterTool.java    From chipster with MIT License 5 votes vote down vote up
protected void requestLoop() throws Exception {

        for (int i = 0; i < messageCount || messageCount == 0; i++) {

            TextMessage message = session.createTextMessage(createMessageText(i));
            message.setJMSReplyTo(replyDest);

            if (verbose) {
                String msg = message.getText();
                if (msg.length() > 50) {
                    msg = msg.substring(0, 50) + "...";
                }
                System.out.println("Sending message: " + msg);
            }

            producer.send(message);
            if (transacted) {
                session.commit();
            }

            System.out.println("Waiting for reponse message...");
            Message message2 = consumer.receive();
            if (message2 instanceof TextMessage) {
                System.out.println("Reponse message: " + ((TextMessage)message2).getText());
            } else {
                System.out.println("Reponse message: " + message2);
            }
            if (transacted) {
                session.commit();
            }

            Thread.sleep(sleepTime);

        }
    }
 
Example 8
Source File: PersonMessageConverter.java    From spring-jms with MIT License 5 votes vote down vote up
@Override
public Object fromMessage(Message message) throws JMSException {
  TextMessage textMessage = (TextMessage) message;
  String payload = textMessage.getText();
  LOGGER.info("inbound json='{}'", payload);

  Person person = null;
  try {
    person = mapper.readValue(payload, Person.class);
  } catch (Exception e) {
    LOGGER.error("error converting to person", e);
  }

  return person;
}
 
Example 9
Source File: CargoHandledConsumer.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
@Override
public void onMessage(Message message) {
    try {
        TextMessage textMessage = (TextMessage) message;
        String trackingIdString = textMessage.getText();

        cargoInspectionService.inspectCargo(new TrackingId(trackingIdString));
    } catch (JMSException e) {
        logger.log(Level.SEVERE, "Error procesing JMS message", e);
    }
}
 
Example 10
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 11
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 12
Source File: SecureConfigurationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private <D extends Destination> String sendAndReceiveText(ConnectionFactory connectionFactory, String clientId, String message, DestinationSupplier<D> destinationSupplier, ConsumerSupplier<D> consumerSupplier) throws JMSException {
   String messageRecieved;
   Connection connection = null;
   try {
      connection = connectionFactory.createConnection();
      if (clientId != null && !clientId.isEmpty()) {
         connection.setClientID(clientId);
      }
      connection.start();
      try (Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
         D destination = destinationSupplier.create(session);
         MessageConsumer messageConsumer = consumerSupplier.create(destination, session);
         Assert.assertNull(messageConsumer.receiveNoWait());

         TextMessage messageToSend = session.createTextMessage(message);
         session.createProducer(destination).send(messageToSend);

         TextMessage received = (TextMessage) messageConsumer.receive(100);
         messageRecieved = received != null ? received.getText() : null;
      }
   } catch (JMSException | JMSRuntimeException e) {
      // Exception Should not be fatal
      assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
      throw e;
   } finally {
      connection.close();
   }
   return messageRecieved;
}
 
Example 13
Source File: Consumer.java    From jms with MIT License 5 votes vote down vote up
public String getGreeting(int timeout, boolean acknowledge)
    throws JMSException {

  String greeting = NO_GREETING;

  // read a message from the queue destination
  Message message = messageConsumer.receive(timeout);

  // check if a message was received
  if (message != null) {
    // cast the message to the correct type
    TextMessage textMessage = (TextMessage) message;

    // retrieve the message content
    String text = textMessage.getText();
    LOGGER.debug(clientId + ": received message with text='{}'",
        text);

    if (acknowledge) {
      // acknowledge the successful processing of the message
      message.acknowledge();
      LOGGER.debug(clientId + ": message acknowledged");
    } else {
      LOGGER.debug(clientId + ": message not acknowledged");
    }

    // create greeting
    greeting = "Hello " + text + "!";
  } else {
    LOGGER.debug(clientId + ": no message received");
  }

  LOGGER.info("greeting={}", greeting);
  return greeting;
}
 
Example 14
Source File: JmsSendReceiveTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void assertMessageValid(int index, Message message) throws JMSException {
   TextMessage textMessage = (TextMessage) message;
   String text = textMessage.getText();

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

   assertEquals("Message: " + index, data[index], text);
}
 
Example 15
Source File: ChatBean.java    From tomee with Apache License 2.0 4 votes vote down vote up
public void onMessage(Message message) {
    try {

        final TextMessage textMessage = (TextMessage) message;
        final String question = textMessage.getText();

        if ("Hello World!".equals(question)) {

            respond("Hello, Test Case!");

        } else if ("How are you?".equals(question)) {

            respond("I'm doing well.");

        } else if ("Still spinning?".equals(question)) {

            respond("Once every day, as usual.");

        }
    } catch (JMSException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 16
Source File: MessageStringConverter.java    From message-queue-client-framework with Apache License 2.0 3 votes vote down vote up
@Override
public Object fromMessage(Message message) throws JMSException,
        MessageConversionException {

    logger.debug("Method : fromMessage");

    TextMessage textMessage = (TextMessage) message;

    String msg = textMessage.getText();

    logger.debug("Convert Success, The Receive Message is " + msg);

    return msg;
}
 
Example 17
Source File: SimpleMessageConverter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Extract a String from the given TextMessage.
 * @param message the message to convert
 * @return the resulting String
 * @throws JMSException if thrown by JMS methods
 */
protected String extractStringFromMessage(TextMessage message) throws JMSException {
	return message.getText();
}
 
Example 18
Source File: JMSLargeMessageTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
@Test
public void testHugeString() throws Exception {
   int msgSize = 1024 * 1024;

   conn = cf.createConnection();

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

   MessageProducer prod = session.createProducer(queue1);

   TextMessage m = session.createTextMessage();

   StringBuffer buffer = new StringBuffer();
   while (buffer.length() < msgSize) {
      buffer.append(UUIDGenerator.getInstance().generateStringUUID());
   }

   final String originalString = buffer.toString();

   m.setText(originalString);

   buffer = null;

   prod.send(m);

   conn.close();

   validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 1);

   conn = cf.createConnection();

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

   MessageConsumer cons = session.createConsumer(queue1);

   conn.start();

   TextMessage rm = (TextMessage) cons.receive(10000);
   Assert.assertNotNull(rm);

   String str = rm.getText();
   Assert.assertEquals(originalString, str);
   conn.close();
   validateNoFilesOnLargeDir(server.getConfiguration().getLargeMessagesDirectory(), 0);

}
 
Example 19
Source File: JMSWrapper.java    From core with GNU General Public License v3.0 2 votes vote down vote up
/**
 * For reading a string message from a Topic or a Queue.
 * 
 * @param consumer
 * @return the read string object
 * @throws JMSException
 */
public static String receiveTextMessage(MessageConsumer consumer) 
		throws JMSException {
	TextMessage receivedMessage = (TextMessage) consumer.receive();
	return receivedMessage.getText();
}
 
Example 20
Source File: LargeMessageQueueAutoCreationTest.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
private void sendStringOfSize(int msgSize) throws JMSException {

      ConnectionFactory factoryToUse = usingCore ? coreCf : factory;

      Connection conn = factoryToUse.createConnection();

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

         MessageProducer prod = session.createProducer(queue1);

         TextMessage m = session.createTextMessage();

         m.setJMSDeliveryMode(DeliveryMode.PERSISTENT);

         StringBuffer buffer = new StringBuffer();
         while (buffer.length() < msgSize) {
            buffer.append(UUIDGenerator.getInstance().generateStringUUID());
         }

         final String originalString = buffer.toString();

         m.setText(originalString);

         prod.send(m);

         conn.close();

         conn = factoryToUse.createConnection();

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

         MessageConsumer cons = session.createConsumer(queue1);

         conn.start();

         TextMessage rm = (TextMessage) cons.receive(5000);
         Assert.assertNotNull(rm);

         String str = rm.getText();
         Assert.assertEquals(originalString, str);
      } finally {
         if (conn != null) {
            conn.close();
         }
      }
   }