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

The following examples show how to use javax.jms.TextMessage#setJMSReplyTo() . 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: MQWatcher.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 初始化key-value值
 * 
 * @throws JMSException
 */
private void initKeyValues() throws JMSException {
	TemporaryQueue responseQueue = null;
	MessageProducer producer = null;
	MessageConsumer consumer = null;
	Queue queue = queueSession.createQueue(QUEUE);

	TextMessage requestMessage = queueSession.createTextMessage();
	requestMessage.setText(generateKeyString());
	responseQueue = queueSession.createTemporaryQueue();
	producer = queueSession.createProducer(queue);
	consumer = queueSession.createConsumer(responseQueue);
	requestMessage.setJMSReplyTo(responseQueue);
	producer.send(requestMessage);

	MapMessage receiveMap = (MapMessage) consumer.receive();
	@SuppressWarnings("unchecked")
	Enumeration<String> mapNames = receiveMap.getPropertyNames();
	while (mapNames.hasMoreElements()) {
		String key = mapNames.nextElement();
		String value = receiveMap.getStringProperty(key);
		keyValueMap.put(key, value);
		LOGGER.info("init key = " + key + ",value = " + value);
	}
}
 
Example 2
Source File: PooledConnectionTempQueueTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
private void sendWithReplyToTemp(ConnectionFactory cf, String serviceQueue) throws JMSException, InterruptedException {
    Connection connection = cf.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();
        TextMessage msg = session.createTextMessage("Request");
        msg.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(serviceQueue));
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(tempQueue);
        Message replyMsg = consumer.receive();
        assertNotNull(replyMsg);

        LOG.debug("Reply message: {}", replyMsg);

        consumer.close();

        producer.close();
        session.close();
    } finally {
        connection.close();
    }
}
 
Example 3
Source File: PooledConnectionTempQueueTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void sendWithReplyToTemp(ConnectionFactory cf, String serviceQueue) throws JMSException,
    InterruptedException {
    Connection con = cf.createConnection();
    con.start();
    Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TemporaryQueue tempQueue = session.createTemporaryQueue();
    TextMessage msg = session.createTextMessage("Request");
    msg.setJMSReplyTo(tempQueue);
    MessageProducer producer = session.createProducer(session.createQueue(serviceQueue));
    producer.send(msg);

    // This sleep also seems to matter
    Thread.sleep(500L);

    MessageConsumer consumer = session.createConsumer(tempQueue);
    Message replyMsg = consumer.receive();
    assertNotNull(replyMsg);
    //System.out.println(replyMsg.getJMSCorrelationID());

    consumer.close();

    producer.close();
    session.close();
    con.close();
}
 
Example 4
Source File: MessageProducer.java    From ditto-examples with Eclipse Public License 2.0 5 votes vote down vote up
private void setResponse(final Session session, final TextMessage message,
    final String correlationId) throws JMSException {
  final Destination responseDestination =
      jmsTemplate.getDestinationResolver().resolveDestinationName(session, response, true);

  message.setJMSCorrelationID(correlationId);
  message.setJMSReplyTo(responseDestination);
}
 
Example 5
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Message mockMessage() throws JMSException {
    final AmqpJmsTextMessageFacade amqpJmsTextMessageFacade = new AmqpJmsTextMessageFacade();
    amqpJmsTextMessageFacade.setContentType(Symbol.getSymbol(DittoConstants.DITTO_PROTOCOL_CONTENT_TYPE));
    amqpJmsTextMessageFacade.initialize(Mockito.mock(AmqpConnection.class));

    final TextMessage jmsTextMessage = new JmsTextMessage(amqpJmsTextMessageFacade);
    jmsTextMessage.setJMSCorrelationID("cid");
    jmsTextMessage.setJMSReplyTo(new JmsQueue("reply"));
    jmsTextMessage.setText(TestConstants.modifyThing());
    return jmsTextMessage;
}
 
Example 6
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 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: BasicRequestor.java    From solace-samples-jms with Apache License 2.0 4 votes vote down vote up
public void run(String... args) throws Exception {

        String[] split = args[1].split("@");

        String host = args[0];
        String vpnName = split[1];
        String username = split[0];
        String password = args[2];

        System.out.printf("BasicRequestor is connecting to Solace messaging at %s...%n", host);

        // Programmatically create the connection factory using default settings
        SolConnectionFactory connectionFactory = SolJmsUtility.createConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setVPN(vpnName);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);

        // Create connection to the Solace router
        Connection connection = connectionFactory.createConnection();

        // Create a non-transacted, auto ACK session.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        System.out.printf("Connected to the Solace Message VPN '%s' with client username '%s'.%n", vpnName,
                username);

        // Create the request topic programmatically
        Topic requestTopic = session.createTopic(REQUEST_TOPIC_NAME);

        // Create the message producer for the created queue
        MessageProducer requestProducer = session.createProducer(requestTopic);

        // The response will be received on this temporary queue.
        TemporaryQueue replyToQueue = session.createTemporaryQueue();

        // Create consumer for receiving the request's reply
        MessageConsumer replyConsumer = session.createConsumer(replyToQueue);

        // Start receiving replies
        connection.start();

        // Create a request.
        TextMessage request = session.createTextMessage("Sample Request");
        // The application must put the destination of the reply in the replyTo field of the request
        request.setJMSReplyTo(replyToQueue);
        // The application must put a correlation ID in the request
        String correlationId = UUID.randomUUID().toString();
        request.setJMSCorrelationID(correlationId);

        System.out.printf("Sending request '%s' to topic '%s'...%n", request.getText(), requestTopic.toString());

        // Send the request
        requestProducer.send(requestTopic, request, DeliveryMode.NON_PERSISTENT,
                Message.DEFAULT_PRIORITY,
                Message.DEFAULT_TIME_TO_LIVE);

        System.out.println("Sent successfully. Waiting for reply...");

        // the main thread blocks at the next statement until a message received or the timeout occurs
        Message reply = replyConsumer.receive(REPLY_TIMEOUT_MS);

        if (reply == null) {
            throw new Exception("Failed to receive a reply in " + REPLY_TIMEOUT_MS + " msecs");
        }

        // Process the reply
        if (reply.getJMSCorrelationID() == null) {
            throw new Exception(
                    "Received a reply message with no correlationID. This field is needed for a direct request.");
        }

        // Apache Qpid JMS prefixes correlation ID with string "ID:" so remove such prefix for interoperability
        if (!reply.getJMSCorrelationID().replaceAll("ID:", "").equals(correlationId)) {
            throw new Exception("Received invalid correlationID in reply message.");
        }

        if (reply instanceof TextMessage) {
            System.out.printf("TextMessage response received: '%s'%n", ((TextMessage) reply).getText());
            if (!reply.getBooleanProperty(SupportedProperty.SOLACE_JMS_PROP_IS_REPLY_MESSAGE)) {
                System.out.println("Warning: Received a reply message without the isReplyMsg flag set.");
            }
        } else {
            System.out.println("Message response received.");
        }

        System.out.printf("Message Content:%n%s%n", SolJmsUtility.dumpMessage(reply));

        connection.stop();
        // Close everything in the order reversed from the opening order
        // NOTE: as the interfaces below extend AutoCloseable,
        // with them it's possible to use the "try-with-resources" Java statement
        // see details at https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
        replyConsumer.close();
        requestProducer.close();
        session.close();
        connection.close();
    }
 
Example 9
Source File: JmsTopicRequestReplyTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendAndReceive() throws Exception {
   clientConnection = createConnection();
   clientConnection.setClientID("ClientConnection:" + name.getMethodName());

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

   clientConnection.start();

   Destination replyDestination = createTemporaryDestination(session);

   MessageConsumer replyConsumer = session.createConsumer(replyDestination);

   // lets test the destination
   clientSideClientID = clientConnection.getClientID();

   // TODO
   // String value = ActiveMQDestination.getClientId((ActiveMQDestination)
   // replyDestination);
   // assertEquals("clientID from the temporary destination must be the
   // same", clientSideClientID, value);

   /* build queues */

   /* build requestmessage */
   TextMessage requestMessage = session.createTextMessage("Olivier");
   requestMessage.setJMSReplyTo(replyDestination);

   MessageProducer requestProducer = session.createProducer(requestDestination);

   requestProducer.send(requestMessage);


   Message msg = replyConsumer.receive(5000);

   if (msg instanceof TextMessage) {
      TextMessage replyMessage = (TextMessage) msg;
      assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText());
   } else {
      fail("Should have received a reply by now");
   }
   replyConsumer.close();
   deleteTemporaryDestination(replyDestination);

   assertEquals("Should not have had any failures: " + failures, 0, failures.size());
}
 
Example 10
Source File: TemporaryJMSQueueClusterTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testDuplicateCacheCleanupForTempQueues() throws Exception {
   setupServer(0, isFileStorage(), isNetty());
   setupServer(1, isFileStorage(), isNetty());

   setupClusterConnection("cluster0", "", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), 0, 1);
   servers[0].getConfiguration().getClusterConfigurations().get(0).setDuplicateDetection(true);
   servers[0].getAddressSettingsRepository().addMatch("#", new AddressSettings().setRedistributionDelay(0));

   setupClusterConnection("cluster1", "", MessageLoadBalancingType.ON_DEMAND, 1, isNetty(), 1, 0);
   servers[1].getConfiguration().getClusterConfigurations().get(0).setDuplicateDetection(true);
   servers[1].getAddressSettingsRepository().addMatch("#", new AddressSettings().setRedistributionDelay(0));

   startServers(0, 1);

   final Map<String, TextMessage> requestMap = new HashMap<>();
   ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");

   for (int j = 0; j < 10; j++) {
      try (Connection connection = cf.createConnection()) {
         SimpleMessageListener server = new SimpleMessageListener().start();
         Queue requestQueue = ActiveMQJMSClient.createQueue("exampleQueue");
         connection.start();
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         MessageProducer producer = session.createProducer(requestQueue);
         TemporaryQueue replyQueue = session.createTemporaryQueue();
         MessageConsumer replyConsumer = session.createConsumer(replyQueue);

         int numMessages = 10;
         for (int i = 0; i < numMessages; i++) {

            TextMessage requestMsg = session.createTextMessage("A request message");
            requestMsg.setJMSReplyTo(replyQueue);
            producer.send(requestMsg);
            requestMap.put(requestMsg.getJMSMessageID(), requestMsg);
         }

         for (int i = 0; i < numMessages; i++) {
            TextMessage replyMessageReceived = (TextMessage) replyConsumer.receive();
            assertNotNull(requestMap.get(replyMessageReceived.getJMSCorrelationID()));
         }

         replyConsumer.close();
         replyQueue.delete();
         server.shutdown();
      }

   }

   assertTrue(((PostOfficeImpl) servers[0].getPostOffice()).getDuplicateIDCaches().size() <= 1);
   assertTrue(((PostOfficeImpl) servers[1].getPostOffice()).getDuplicateIDCaches().size() <= 1);

}
 
Example 11
Source File: JmsTopicRequestReplyTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testSendAndReceive() throws Exception {
   clientConnection = createConnection();
   clientConnection.setClientID("ClientConnection:" + getSubject());

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

   clientConnection.start();

   Destination replyDestination = createTemporaryDestination(session);

   // lets test the destination
   clientSideClientID = clientConnection.getClientID();

   // TODO
   // String value = ActiveMQDestination.getClientId((ActiveMQDestination)
   // replyDestination);
   // assertEquals("clientID from the temporary destination must be the
   // same", clientSideClientID, value);
   LOG.info("Both the clientID and destination clientID match properly: " + clientSideClientID);

     /* build queues */
   MessageProducer requestProducer = session.createProducer(requestDestination);
   MessageConsumer replyConsumer = session.createConsumer(replyDestination);

     /* build requestmessage */
   TextMessage requestMessage = session.createTextMessage("Olivier");
   requestMessage.setJMSReplyTo(replyDestination);
   requestProducer.send(requestMessage);

   LOG.info("Sent request.");
   LOG.info(requestMessage.toString());

   Message msg = replyConsumer.receive(5000);

   if (msg instanceof TextMessage) {
      TextMessage replyMessage = (TextMessage) msg;
      LOG.info("Received reply.");
      LOG.info(replyMessage.toString());
      assertEquals("Wrong message content", "Hello: Olivier", replyMessage.getText());
   } else {
      fail("Should have received a reply by now");
   }
   replyConsumer.close();
   deleteTemporaryDestination(replyDestination);

   assertEquals("Should not have had any failures: " + failures, 0, failures.size());
}
 
Example 12
Source File: RequestReplyToTopicViaThreeNetworkHopsTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void testMessages(Session sess,
                         MessageProducer req_prod,
                         Destination resp_dest,
                         int num_msg) throws Exception {
   MessageConsumer resp_cons;
   TextMessage msg;
   MessageClient cons_client;
   int cur;
   int tot_expected;

   resp_cons = sess.createConsumer(resp_dest);

   cons_client = new MessageClient(resp_cons, num_msg);
   cons_client.start();

   cur = 0;
   while ((cur < num_msg) && (!fatalTestError)) {
      msg = sess.createTextMessage("MSG AAAA " + cur);
      msg.setIntProperty("SEQ", 100 + cur);
      msg.setStringProperty("TEST", "TOPO");
      msg.setJMSReplyTo(resp_dest);

      if (cur == (num_msg - 1))
         msg.setBooleanProperty("end-of-response", true);

      sendWithRetryOnDeletedDest(req_prod, msg);
      LOG.debug("Sent:" + msg);

      cur++;
   }

   //
   // Give the consumer some time to receive the response.
   //
   cons_client.waitShutdown(5000);

   //
   // Now shutdown the consumer if it's still running.
   //
   if (cons_client.shutdown())
      LOG.debug("Consumer client shutdown complete");
   else
      LOG.debug("Consumer client shutdown incomplete!!!");

   //
   // Check that the correct number of messages was received.
   //
   tot_expected = num_msg * (echoResponseFill + 1);

   if (cons_client.getNumMsgReceived() == tot_expected) {
      LOG.debug("Have " + tot_expected + " messages, as-expected");
   } else {
      testError = true;

      if (cons_client.getNumMsgReceived() == 0)
         fatalTestError = true;

      LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest);
   }

   resp_cons.close();
}
 
Example 13
Source File: RequestReplyNoAdvisoryNetworkTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void doTestNonAdvisoryNetworkRequestReply() throws Exception {

      waitForBridgeFormation(a, 1, 0);
      waitForBridgeFormation(b, 1, 0);

      ActiveMQConnectionFactory sendFactory = createConnectionFactory(a);
      ActiveMQConnection sendConnection = createConnection(sendFactory);

      ActiveMQSession sendSession = (ActiveMQSession) sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = sendSession.createProducer(sendQ);
      ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue();
      TextMessage message = sendSession.createTextMessage("1");
      message.setJMSReplyTo(realReplyQ);
      producer.send(message);
      LOG.info("request sent");

      // responder
      ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b);
      ActiveMQConnection consumerConnection = createConnection(consumerFactory);

      ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = consumerSession.createConsumer(sendQ);
      TextMessage received = (TextMessage) consumer.receive(receiveTimeout);
      assertNotNull("got request from sender ok", received);

      LOG.info("got request, sending reply");

      MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo());
      consumerProducer.send(consumerSession.createTextMessage("got " + received.getText()));
      // temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures
      // message gets delivered before destination is removed
      consumerConnection.close();

      // reply consumer
      MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ);
      TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout);
      assertNotNull("expected reply message", reply);
      assertEquals("text is as expected", "got 1", reply.getText());
      sendConnection.close();

      LOG.info("checking for dangling temp destinations");
      // ensure all temp dests get cleaned up on all brokers
      for (BrokerService brokerService : brokers) {
         final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker();
         assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
               Map<?, ?> tempTopics = regionBroker.getTempTopicRegion().getDestinationMap();
               LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics);
               Map<?, ?> tempQ = regionBroker.getTempQueueRegion().getDestinationMap();
               LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ);
               return tempQ.isEmpty() && tempTopics.isEmpty();
            }
         }));
      }
   }
 
Example 14
Source File: Client.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        // The configuration for the Qpid InitialContextFactory has been supplied in
        // a jndi.properties file in the classpath, which results in it being picked
        // up automatically by the InitialContext constructor.
        Context context = new InitialContext();

        ConnectionFactory factory = (ConnectionFactory) context.lookup("myFactoryLookup");
        Destination queue = (Destination) context.lookup("myQueueLookup");

        Connection connection = factory.createConnection(System.getProperty("USER"), System.getProperty("PASSWORD"));
        connection.setExceptionListener(new MyExceptionListener());
        connection.start();

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

        //Create a temporary queue and consumer to receive responses, and a producer to send requests.
        TemporaryQueue responseQueue = session.createTemporaryQueue();
        MessageConsumer messageConsumer = session.createConsumer(responseQueue);
        MessageProducer messageProducer = session.createProducer(queue);

        //Send some requests and receive the responses.
        String[] requests = new String[] { "Twas brillig, and the slithy toves",
                                           "Did gire and gymble in the wabe.",
                                           "All mimsy were the borogroves,",
                                           "And the mome raths outgrabe." };

        for (String request : requests) {
            TextMessage requestMessage = session.createTextMessage(request);
            requestMessage.setJMSReplyTo(responseQueue);

            messageProducer.send(requestMessage, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);

            TextMessage responseMessage = (TextMessage) messageConsumer.receive(2000);
            if (responseMessage != null) {
                System.out.println("[CLIENT] " + request + " ---> " + responseMessage.getText());
            } else {
                System.out.println("[CLIENT] Response for '" + request +"' was not received within the timeout, exiting.");
                break;
            }
        }

        connection.close();
    } catch (Exception exp) {
        System.out.println("[CLIENT] Caught exception, exiting.");
        exp.printStackTrace(System.out);
        System.exit(1);
    }
}