Example usage for javax.jms TextMessage setJMSCorrelationID

List of usage examples for javax.jms TextMessage setJMSCorrelationID

Introduction

In this page you can find the example usage for javax.jms TextMessage setJMSCorrelationID.

Prototype


void setJMSCorrelationID(String correlationID) throws JMSException;

Source Link

Document

Sets the correlation ID for the message.

Usage

From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java

@SuppressWarnings("resource")
@Test/*ww  w  . jav  a  2  s .  c om*/
public void messageCorrelationBasedOnRequestMessageId() throws Exception {
    ActiveMqTestUtils.prepare();

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "producer-temp-reply-consumers.xml", this.getClass());
    RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class);
    CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class);
    final JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);

    final Destination requestDestination = context.getBean("siOutQueue", Destination.class);

    new Thread(() -> {
        final Message requestMessage = jmsTemplate.receive(requestDestination);
        Destination replyTo = null;
        try {
            replyTo = requestMessage.getJMSReplyTo();
        } catch (Exception e) {
            fail();
        }
        jmsTemplate.send(replyTo, (MessageCreator) session -> {
            try {
                TextMessage message = session.createTextMessage();
                message.setText("bar");
                message.setJMSCorrelationID(requestMessage.getJMSMessageID());
                return message;
            } catch (Exception e) {
                // ignore
            }
            return null;
        });
    }).start();
    gateway.exchange(new GenericMessage<String>("foo"));
    context.close();
}

From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java

@Test
public void messageCorrelationBasedOnRequestCorrelationIdTimedOutFirstReply() throws Exception {
    ActiveMqTestUtils.prepare();/*from   w  w w .jav  a2s  .c o  m*/
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "producer-temp-reply-consumers.xml", this.getClass());
    RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class);
    ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class);

    final Destination requestDestination = context.getBean("siOutQueue", Destination.class);

    DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer();
    dmlc.setConnectionFactory(connectionFactory);
    dmlc.setDestination(requestDestination);
    dmlc.setMessageListener((SessionAwareMessageListener<Message>) (message, session) -> {
        Destination replyTo = null;
        try {
            replyTo = message.getJMSReplyTo();
        } catch (Exception e1) {
            fail();
        }
        String requestPayload = (String) extractPayload(message);
        if (requestPayload.equals("foo")) {
            try {
                Thread.sleep(6000);
            } catch (Exception e2) {
                /*ignore*/ }
        }
        try {
            TextMessage replyMessage = session.createTextMessage();
            replyMessage.setText(requestPayload);
            replyMessage.setJMSCorrelationID(message.getJMSMessageID());
            MessageProducer producer = session.createProducer(replyTo);
            producer.send(replyMessage);
        } catch (Exception e3) {
            // ignore. the test will fail
        }
    });
    dmlc.afterPropertiesSet();
    dmlc.start();

    try {
        gateway.exchange(new GenericMessage<String>("foo"));
    } catch (Exception e) {
        // ignore
    }
    Thread.sleep(1000);
    try {
        assertEquals("bar", gateway.exchange(new GenericMessage<String>("bar")).getPayload());
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
    context.close();
}

From source file:org.apache.activemq.web.RestTest.java

@Test(timeout = 15 * 1000)
public void testCorrelation() throws Exception {
    int port = getPort();

    HttpClient httpClient = new HttpClient();
    httpClient.start();//ww  w  .  j a va 2  s.  c  om

    for (int i = 0; i < 200; i++) {
        String correlId = "RESTY" + RandomStringUtils.randomNumeric(10);

        TextMessage message = session.createTextMessage(correlId);
        message.setStringProperty("correlationId", correlId);
        message.setJMSCorrelationID(correlId);

        LOG.info("Sending: " + correlId);
        producer.send(message);

        final StringBuffer buf = new StringBuffer();
        final CountDownLatch latch = asyncRequest(httpClient,
                "http://localhost:" + port + "/message/test?readTimeout=1000&type=queue&clientId=test", buf);

        latch.await();
        LOG.info("Received: " + buf.toString());
        // assertEquals(200, contentExchange.getResponseStatus());
        assertEquals(correlId, buf.toString());
    }
    httpClient.stop();
}

From source file:gov.nih.nci.cabig.caaers.esb.client.impl.CtmsCaaersMessageConsumer.java

/**
 * This method sends the response out. It uses a producer which is connected to "ctms-caaers.outputQueue"
 * @param responseXml//from w w  w  .j  a v a  2s.  c o  m
 * @param jmsCorelationID
 * @param messageType
 */
private void sendResponse(String responseXml, String jmsCorelationID, String messageType) {
    try {
        TextMessage message = session.createTextMessage();
        message.setJMSCorrelationID(jmsCorelationID);
        message.setStringProperty("MESSAGE_TYPE", messageType);
        message.setText(responseXml);
        producer.send(message);
    } catch (JMSException e) {
        logger.error("caught sendResponse", e);
    }
}

From source file:org.oxymores.chronix.engine.Runner.java

public void sendParameterValue(String value, UUID paramID, PipelineJob pj) throws JMSException {
    // This is a loopback send (used by static parameter value mostly)
    log.debug(String.format(/*from  www .jav a 2 s .  c  o  m*/
            "A param value resolved locally (static) will be sent to the local engine ( value is %s)", value));

    TextMessage m = jmsSession.createTextMessage(value);
    m.setJMSCorrelationID(pj.getId() + "|" + paramID.toString());
    producerRunDescription.send(destEndJob, m);
    jmsSession.commit();
}

From source file:Replier.java

/**
 * Handle the message./*from  w  w  w.  j av a2  s.  c  om*/
 * (as specified in the javax.jms.MessageListener interface).
 *
 * IMPORTANT NOTES:
 * (1)We must follow the design paradigm for JMS
 *    synchronous requests.  That is, we must:
 *     - get the message
 *     - look for the header specifying JMSReplyTo
 *     - send a reply to the queue specified there.
 *    Failing to follow these steps might leave the originator
 *    of the request waiting forever.
 * (2)Unlike the 'Talk' sample and others using an asynchronous
 *    message listener, it is possible here to use ONLY
 *    ONE SESSION because the messages being sent are sent from
 *    the same thread of control handling message delivery. For
 *    more information see the JMS spec v1.0.2 section 4.4.6.
 *
 * OPTIONAL BEHAVIOR: The following actions taken by the
 * message handler represent good programming style, but are
 * not required by the design paradigm for JMS requests.
 *   - set the JMSCorrelationID (tying the response back to
 *     the original request.
 *   - use transacted session "commit" so receipt of request
 *     won't happen without the reply being sent.
 *
 */
public void onMessage(javax.jms.Message aMessage) {
    try {
        // Cast the message as a text message.
        javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage;

        // This handler reads a single String from the
        // message and prints it to the standard output.
        try {
            String string = textMessage.getText();
            System.out.println("[Request] " + string);

            // Check for a ReplyTo Queue
            javax.jms.Queue replyQueue = (javax.jms.Queue) aMessage.getJMSReplyTo();
            if (replyQueue != null) {
                // Send the modified message back.
                javax.jms.TextMessage reply = session.createTextMessage();
                if (imode == UPPERCASE)
                    reply.setText("Uppercasing-" + string.toUpperCase());
                else
                    reply.setText("Lowercasing-" + string.toLowerCase());
                reply.setJMSCorrelationID(aMessage.getJMSMessageID());
                replier.send(replyQueue, reply);
                session.commit();
            }
        } catch (javax.jms.JMSException jmse) {
            jmse.printStackTrace();
        }
    } catch (java.lang.RuntimeException rte) {
        rte.printStackTrace();
    }
}

From source file:org.openanzo.combus.endpoint.BaseServiceListener.java

private TextMessage sendJMSErrorMessage(Destination replyTo, Message request, Throwable jmex, long errorCode,
        String... args) throws JMSException {
    try {//w ww. j  a v  a2  s.  c om
        if (replyTo != null) {
            if (log.isWarnEnabled()) {
                log.warn(LogUtils.COMBUS_MARKER,
                        "Exception while ServiceListener [" + name + "] was precessing request.", jmex);

            }
            String message = null;
            if (jmex instanceof AnzoException) {
                message = ((AnzoException) jmex).getMessage(false);
            } else if (jmex instanceof AnzoRuntimeException) {
                message = ((AnzoRuntimeException) jmex).getMessage(false);
            } else {
                message = jmex.getMessage();
            }
            TextMessage response = session.createTextMessage(message);
            response.setJMSCorrelationID(request.getJMSCorrelationID());
            response.setBooleanProperty(SerializationConstants.operationFailed, true);
            response.setLongProperty(SerializationConstants.errorTags, 0);
            response.setLongProperty(SerializationConstants.errorCode, errorCode);
            response.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
            // send a single arg string for compat. with older readers
            response.setStringProperty(SerializationConstants.errorMessageArg, Arrays.toString(args));

            // send the individual error args for readers that can make use of them
            for (int i = 0; i < args.length; i++) {
                response.setStringProperty(SerializationConstants.errorMessageArg + i, args[i]);
            }

            // we log all JMS messages, even errors.
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.COMBUS_MARKER,
                        MessageUtils.prettyPrint(response, "Sending Response to " + replyTo));
            }
            mp.send(replyTo, response);
            return response;
        }
    } catch (JMSException jmsex) {
        log.debug(LogUtils.COMBUS_MARKER, "Error sending error message to client", jmsex);
    }
    return null;
}

From source file:TopicReplier.java

/**
 * Handle the message.//  w  ww.  java 2 s .c om
 * (as specified in the javax.jms.MessageListener interface).
 *
 * IMPORTANT NOTE: We must follow the design paradigm for JMS
 * synchronous requests.  That is, we must:
 *   - get the message
 *   - look for the header specifying JMSReplyTo
 *   - send a reply to the topic specified there.
 * Failing to follow these steps might leave the originator
 * of the request waiting forever.
 *
 * OPTIONAL BEHAVIOR: The following actions taken by the
 * message handler represent good programming style, but are
 * not required by the design paradigm for JMS requests.
 *   - set the JMSCorrelationID (tying the response back to
 *     the original request.
 *   - use transacted session "commit" so receipt of request
 *     won't happen without the reply being sent.
 *
 */
public void onMessage(javax.jms.Message aMessage) {
    try {
        // Cast the message as a text message.
        javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage;

        // This handler reads a single String from the
        // message and prints it to the standard output.
        try {
            String string = textMessage.getText();
            System.out.println("[Request] " + string);

            // Check for a ReplyTo topic
            javax.jms.Topic replyTopic = (javax.jms.Topic) aMessage.getJMSReplyTo();
            if (replyTopic != null) {
                // Send the modified message back.
                javax.jms.TextMessage reply = session.createTextMessage();
                if (imode == UPPERCASE)
                    reply.setText("Transformed " + string + " to all uppercase: " + string.toUpperCase());
                else
                    reply.setText("Transformed " + string + " to all lowercase " + string.toLowerCase());
                reply.setJMSCorrelationID(aMessage.getJMSMessageID());
                replier.send(replyTopic, reply);
                session.commit();
            }
        } catch (javax.jms.JMSException jmse) {
            jmse.printStackTrace();
        }
    } catch (java.lang.RuntimeException rte) {
        rte.printStackTrace();
    }
}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue//from  w  ww. j  a  va2  s .co  m
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}