Example usage for javax.jms Message setJMSCorrelationID

List of usage examples for javax.jms Message setJMSCorrelationID

Introduction

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

Prototype


void setJMSCorrelationID(String correlationID) throws JMSException;

Source Link

Document

Sets the correlation ID for the message.

Usage

From source file:org.apache.axis2.transport.jms.MockEchoEndpoint.java

@Setup
@SuppressWarnings("unused")
private void setUp(JMSTestEnvironment env, JMSRequestResponseChannel channel) throws Exception {
    Destination destination = channel.getDestination();
    Destination replyDestination = channel.getReplyDestination();
    connection = env.getConnectionFactory().createConnection();
    connection.setExceptionListener(this);
    connection.start();/*from   w  w  w.ja  v  a  2s.com*/
    replyConnection = env.getConnectionFactory().createConnection();
    replyConnection.setExceptionListener(this);
    final Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final MessageProducer producer = replySession.createProducer(replyDestination);
    MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)
            .createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            try {
                log.info("Message received: ID = " + message.getJMSMessageID());
                Message reply;
                if (message instanceof BytesMessage) {
                    reply = replySession.createBytesMessage();
                    IOUtils.copy(new BytesMessageInputStream((BytesMessage) message),
                            new BytesMessageOutputStream((BytesMessage) reply));
                } else if (message instanceof TextMessage) {
                    reply = replySession.createTextMessage();
                    ((TextMessage) reply).setText(((TextMessage) message).getText());
                } else {
                    // TODO
                    throw new UnsupportedOperationException("Unsupported message type");
                }
                reply.setJMSCorrelationID(message.getJMSMessageID());
                reply.setStringProperty(BaseConstants.CONTENT_TYPE,
                        message.getStringProperty(BaseConstants.CONTENT_TYPE));
                producer.send(reply);
                log.info("Message sent: ID = " + reply.getJMSMessageID());
            } catch (Throwable ex) {
                fireEndpointError(ex);
            }
        }
    });
}

From source file:org.apache.camel.component.jms.EndpointMessageListener.java

protected void sendReply(Destination replyDestination, final Message message, final Exchange exchange,
        final JmsMessage out, final Exception cause) {
    if (replyDestination == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot send reply message as there is no replyDestination for: " + out);
        }/*from   w w  w. ja  v a  2  s. c om*/
        return;
    }
    getTemplate().send(replyDestination, new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            Message reply = endpoint.getBinding().makeJmsMessage(exchange, out, session, cause);
            final String correlationID = determineCorrelationId(message);
            reply.setJMSCorrelationID(correlationID);

            if (LOG.isDebugEnabled()) {
                LOG.debug(endpoint + " sending reply JMS message [correlationId:" + correlationID + "]: "
                        + reply);
            }
            return reply;
        }
    });
}

From source file:org.apache.camel.component.jms.EndpointMessageListener.java

protected void sendReply(String replyDestination, final Message message, final Exchange exchange,
        final JmsMessage out, final Exception cause) {
    if (replyDestination == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot send reply message as there is no replyDestination for: " + out);
        }// ww  w .j  a  v a2 s .  c  om
        return;
    }
    getTemplate().send(replyDestination, new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            Message reply = endpoint.getBinding().makeJmsMessage(exchange, out, session, cause);
            final String correlationID = determineCorrelationId(message);
            reply.setJMSCorrelationID(correlationID);

            if (LOG.isDebugEnabled()) {
                LOG.debug(endpoint + " sending reply JMS message [correlationId:" + correlationID + "]: "
                        + reply);
            }
            return reply;
        }
    });
}

From source file:org.apache.camel.component.jms.JmsBinding.java

public void appendJmsProperty(Message jmsMessage, Exchange exchange, org.apache.camel.Message in,
        String headerName, Object headerValue) throws JMSException {
    if (isStandardJMSHeader(headerName)) {
        if (headerName.equals("JMSCorrelationID")) {
            jmsMessage.setJMSCorrelationID(ExchangeHelper.convertToType(exchange, String.class, headerValue));
        } else if (headerName.equals("JMSReplyTo") && headerValue != null) {
            if (headerValue instanceof String) {
                // if the value is a String we must normalize it first
                headerValue = normalizeDestinationName((String) headerValue);
            }//from ww  w . ja v a 2 s  .c  om
            jmsMessage.setJMSReplyTo(ExchangeHelper.convertToType(exchange, Destination.class, headerValue));
        } else if (headerName.equals("JMSType")) {
            jmsMessage.setJMSType(ExchangeHelper.convertToType(exchange, String.class, headerValue));
        } else if (headerName.equals("JMSPriority")) {
            jmsMessage.setJMSPriority(ExchangeHelper.convertToType(exchange, Integer.class, headerValue));
        } else if (headerName.equals("JMSDeliveryMode")) {
            Integer deliveryMode = ExchangeHelper.convertToType(exchange, Integer.class, headerValue);
            jmsMessage.setJMSDeliveryMode(deliveryMode);
            jmsMessage.setIntProperty(JmsConstants.JMS_DELIVERY_MODE, deliveryMode);
        } else if (headerName.equals("JMSExpiration")) {
            jmsMessage.setJMSExpiration(ExchangeHelper.convertToType(exchange, Long.class, headerValue));
        } else if (LOG.isTraceEnabled()) {
            // The following properties are set by the MessageProducer:
            // JMSDestination
            // The following are set on the underlying JMS provider:
            // JMSMessageID, JMSTimestamp, JMSRedelivered
            // log at trace level to not spam log
            LOG.trace("Ignoring JMS header: " + headerName + " with value: " + headerValue);
        }
    } else if (shouldOutputHeader(in, headerName, headerValue, exchange)) {
        // only primitive headers and strings is allowed as properties
        // see message properties: http://java.sun.com/j2ee/1.4/docs/api/javax/jms/Message.html
        Object value = getValidJMSHeaderValue(headerName, headerValue);
        if (value != null) {
            // must encode to safe JMS header name before setting property on jmsMessage
            String key = jmsKeyFormatStrategy.encodeKey(headerName);
            // set the property
            JmsMessageHelper.setProperty(jmsMessage, key, value);
        } else if (LOG.isDebugEnabled()) {
            // okay the value is not a primitive or string so we cannot sent it over the wire
            LOG.debug("Ignoring non primitive header: " + headerName + " of class: "
                    + headerValue.getClass().getName() + " with value: " + headerValue);
        }
    }
}

From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java

public void process(MessageExchange exchange) throws Exception {
    Context context = (Context) pendingMessages.remove(exchange.getExchangeId());
    Message message = (Message) context.getProperty(Message.class.getName());
    Message response = null;
    Connection connection = null;
    try {/* w  w w  .j a  va2s  . co m*/
        if (exchange.getStatus() == ExchangeStatus.DONE) {
            return;
        } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
            if (endpoint.isRollbackOnError()) {
                TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent()
                        .getComponentContext().getTransactionManager();
                tm.setRollbackOnly();
                return;
            } else if (exchange instanceof InOnly) {
                LOG.info("Exchange in error: " + exchange, exchange.getError());
                return;
            } else {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Exception error = exchange.getError();
                if (error == null) {
                    error = new Exception("Exchange in error");
                }
                response = session.createObjectMessage(error);
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        } else {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            response = fromNMSResponse(exchange, context, session);
            if (response != null) {
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    }
}

From source file:org.apache.synapse.transport.jms.JMSSender.java

/**
 * Create a JMS Message from the given MessageContext and using the given
 * session/*from   w w w  .  ja  va  2 s .c om*/
 *
 * @param msgContext the MessageContext
 * @param session    the JMS session
 * @return a JMS message from the context and session
 * @throws JMSException on exception
 * @throws AxisFault on exception
 */
private Message createJMSMessage(MessageContext msgContext, Session session) throws JMSException, AxisFault {

    Message message = null;
    String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE);

    // check the first element of the SOAP body, do we have content wrapped using the
    // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages
    // for JMS but just get the payload in its native format
    String jmsPayloadType = guessMessageType(msgContext);

    if (jmsPayloadType == null) {

        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = TransportUtils.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new JMSException("Unable to get the message formatter to use");
        }

        String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            messageFormatter.writeTo(msgContext, format, baos, true);
            baos.flush();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }

        if (msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType)
                || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1) {
            message = session.createBytesMessage();
            BytesMessage bytesMsg = (BytesMessage) message;
            bytesMsg.writeBytes(baos.toByteArray());
        } else {
            message = session.createTextMessage(); // default
            TextMessage txtMsg = (TextMessage) message;
            txtMsg.setText(new String(baos.toByteArray()));
        }
        message.setStringProperty(BaseConstants.CONTENT_TYPE, contentType);

    } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) {
        message = session.createBytesMessage();
        BytesMessage bytesMsg = (BytesMessage) message;
        OMElement wrapper = msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER);
        OMNode omNode = wrapper.getFirstOMChild();
        if (omNode != null && omNode instanceof OMText) {
            Object dh = ((OMText) omNode).getDataHandler();
            if (dh != null && dh instanceof DataHandler) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ((DataHandler) dh).writeTo(baos);
                } catch (IOException e) {
                    handleException("Error serializing binary content of element : "
                            + BaseConstants.DEFAULT_BINARY_WRAPPER, e);
                }
                bytesMsg.writeBytes(baos.toByteArray());
            }
        }

    } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) {
        message = session.createTextMessage();
        TextMessage txtMsg = (TextMessage) message;
        txtMsg.setText(msgContext.getEnvelope().getBody()
                .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText());
    }

    // set the JMS correlation ID if specified
    String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID);
    if (correlationId == null && msgContext.getRelatesTo() != null) {
        correlationId = msgContext.getRelatesTo().getValue();
    }

    if (correlationId != null) {
        message.setJMSCorrelationID(correlationId);
    }

    if (msgContext.isServerSide()) {
        // set SOAP Action as a property on the JMS message
        setProperty(message, msgContext, BaseConstants.SOAPACTION);
    } else {
        String action = msgContext.getOptions().getAction();
        if (action != null) {
            message.setStringProperty(BaseConstants.SOAPACTION, action);
        }
    }

    JMSUtils.setTransportHeaders(msgContext, message);
    return message;
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Set transport headers from the axis message context, into the JMS message
 *
 * @param msgContext the axis message context
 * @param message the JMS Message/*from  w ww .j  a va 2s .  c  o  m*/
 * @throws JMSException on exception
 */
public static void setTransportHeaders(MessageContext msgContext, Message message) throws JMSException {

    Map headerMap = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    if (headerMap == null) {
        return;
    }

    Iterator iter = headerMap.keySet().iterator();
    while (iter.hasNext()) {

        String name = (String) iter.next();

        if (JMSConstants.JMS_COORELATION_ID.equals(name)) {
            message.setJMSCorrelationID((String) headerMap.get(JMSConstants.JMS_COORELATION_ID));
        } else if (JMSConstants.JMS_DELIVERY_MODE.equals(name)) {
            Object o = headerMap.get(JMSConstants.JMS_DELIVERY_MODE);
            if (o instanceof Integer) {
                message.setJMSDeliveryMode(((Integer) o).intValue());
            } else if (o instanceof String) {
                try {
                    message.setJMSDeliveryMode(Integer.parseInt((String) o));
                } catch (NumberFormatException nfe) {
                    log.warn("Invalid delivery mode ignored : " + o, nfe);
                }
            } else {
                log.warn("Invalid delivery mode ignored : " + o);
            }
        } else if (JMSConstants.JMS_EXPIRATION.equals(name)) {
            message.setJMSExpiration(Long.parseLong((String) headerMap.get(JMSConstants.JMS_EXPIRATION)));
        } else if (JMSConstants.JMS_MESSAGE_ID.equals(name)) {
            message.setJMSMessageID((String) headerMap.get(JMSConstants.JMS_MESSAGE_ID));
        } else if (JMSConstants.JMS_PRIORITY.equals(name)) {
            message.setJMSPriority(Integer.parseInt((String) headerMap.get(JMSConstants.JMS_PRIORITY)));
        } else if (JMSConstants.JMS_TIMESTAMP.equals(name)) {
            message.setJMSTimestamp(Long.parseLong((String) headerMap.get(JMSConstants.JMS_TIMESTAMP)));
        } else if (JMSConstants.JMS_MESSAGE_TYPE.equals(name)) {
            message.setJMSType((String) headerMap.get(JMSConstants.JMS_MESSAGE_TYPE));
        } else {
            Object value = headerMap.get(name);
            if (value instanceof String) {
                message.setStringProperty(name, (String) value);
            } else if (value instanceof Boolean) {
                message.setBooleanProperty(name, ((Boolean) value).booleanValue());
            } else if (value instanceof Integer) {
                message.setIntProperty(name, ((Integer) value).intValue());
            } else if (value instanceof Long) {
                message.setLongProperty(name, ((Long) value).longValue());
            } else if (value instanceof Double) {
                message.setDoubleProperty(name, ((Double) value).doubleValue());
            } else if (value instanceof Float) {
                message.setFloatProperty(name, ((Float) value).floatValue());
            }
        }
    }
}

From source file:org.codehaus.stomp.jms.StompSession.java

protected void copyStandardHeadersFromFrameToMessage(StompFrame command, Message msg)
        throws JMSException, ProtocolException, NamingException {
    final Map headers = new HashMap(command.getHeaders());

    // the standard JMS headers
    msg.setJMSCorrelationID((String) headers.remove(Stomp.Headers.Send.CORRELATION_ID));

    Object o = headers.remove(Stomp.Headers.Send.TYPE);
    if (o != null) {
        msg.setJMSType((String) o);
    }//from  w w  w. j  a v a  2s . c  o  m

    o = headers.remove(Stomp.Headers.Send.REPLY_TO);
    if (o != null) {
        msg.setJMSReplyTo(convertDestination((String) o, false));
    }

    // now the general headers
    for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        String name = (String) entry.getKey();
        Object value = entry.getValue();
        msg.setObjectProperty(name, value);
    }
}

From source file:org.dhatim.routing.jms.JMSRouter.java

private void setCorrelationID(ExecutionContext execContext, Message message) {
    Map<String, Object> beanMap = FreeMarkerUtils.getMergedModel(execContext);
    String correlationId = correlationIdTemplate.apply(beanMap);

    try {// www  .j  a v a2 s .  c  om
        message.setJMSCorrelationID(correlationId);
    } catch (JMSException e) {
        throw new SmooksException("Failed to set CorrelationID '" + correlationId + "' on message.", e);
    }
}

From source file:org.grouter.common.jms.QueueListenerDestination.java

/**
 * <br>/*  w  w  w .  j  a v a  2 s.  c  o m*/
 */
public void sendReplyToTemporaryDestination(Message request) {
    TemporaryQueue replyQueue = null;
    QueueSender tempsender = null;
    String temporaryDestinationName = null;
    try {
        if (request.getJMSReplyTo() == null) {
            throw new IllegalStateException("The sender of this message has not entered a JMSReplyTo field - "
                    + "impossible to send reply on temporary destination!!");
        }
        temporaryDestinationName = request.getJMSReplyTo().toString();
        request.setJMSCorrelationID(temporaryDestinationName);
        replyQueue = (TemporaryQueue) request.getJMSReplyTo();
        tempsender = queueSession.createSender(replyQueue);
        tempsender.send(request);
        logger.debug("Created a tempsender and sent reply to " + replyQueue);
    } catch (JMSException ex) {
        //ignore
        logger.warn("Failed sending reply on temporary destination : " + temporaryDestinationName);
    } finally {
        try {
            if (tempsender != null) {
                tempsender.close();
            }
            if (replyQueue != null) {
                replyQueue.delete();
            }
        } catch (JMSException ex1) {
            //ignore
        }
    }
}