Example usage for javax.jms Message getJMSCorrelationID

List of usage examples for javax.jms Message getJMSCorrelationID

Introduction

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

Prototype


String getJMSCorrelationID() throws JMSException;

Source Link

Document

Gets the correlation ID for the message.

Usage

From source file:org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener.java

/**
 * Post-process the given response message before it will be sent.
 * <p>The default implementation sets the response's correlation id
 * to the request message's correlation id, if any; otherwise to the
 * request message id./*from   w  w w. ja  v  a  2  s .  c o m*/
 * @param request the original incoming JMS message
 * @param response the outgoing JMS message about to be sent
 * @throws JMSException if thrown by JMS API methods
 * @see javax.jms.Message#setJMSCorrelationID
 */
protected void postProcessResponse(Message request, Message response) throws JMSException {
    String correlation = request.getJMSCorrelationID();
    if (correlation == null) {
        correlation = request.getJMSMessageID();
    }
    response.setJMSCorrelationID(correlation);
}

From source file:com.jaliansystems.activeMQLite.impl.RepositoryService.java

/**
 * Handles message requests for this object repository.
 * /*w  ww  . ja v  a 2s.c o  m*/
 * All messages are JMSLiteMessage the protocol of which is explained in Protocol.txt
 */
public void onMessage(Message message) {
    if (message instanceof ActiveMQBytesMessage) {
        try {
            JMSLiteMessage jmsMessage = new JMSLiteMessage((ActiveMQBytesMessage) message);
            byte message_type = (Byte) jmsMessage.read();
            if (message_type == MESSAGE_LOOKUP) {
                String className = (String) jmsMessage.read();
                handleLookup(className, message.getJMSReplyTo(), message.getJMSCorrelationID());
            } else if (message_type == MESSAGE_CALL) {
                JMSLiteMessage rmessage = new JMSLiteMessage();
                rmessage.write(MESSAGE_CALL);
                try {
                    Object returnVal = objectRepository.invoke(jmsMessage, client);
                    rmessage.write(CALL_SUCCESS);
                    rmessage.write(returnVal);
                } catch (Throwable t) {
                    if (log.isDebugEnabled())
                        t.printStackTrace();
                    rmessage.write(CALL_ERROR);
                    rmessage.write(t.getClass().getName());
                    rmessage.write(t.getMessage());
                }
                rmessage.setJMSCorrelationID(message.getJMSCorrelationID());
                rmessage.setJMSDestination(message.getJMSReplyTo());
                responseProducer.send(message.getJMSReplyTo(), rmessage);
            } else if (message_type == MESSAGE_REMOVE) {
                ObjectHandle handle = (ObjectHandle) jmsMessage.read();
                boolean b = objectRepository.removeObject(handle);
                JMSLiteMessage rmessage = new JMSLiteMessage();
                rmessage.write(MESSAGE_REMOVE);
                rmessage.write(b);
                rmessage.setJMSCorrelationID(message.getJMSCorrelationID());
                rmessage.setJMSDestination(message.getJMSReplyTo());
                responseProducer.send(message.getJMSReplyTo(), rmessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.genemania.connector.JmsEngineConnector.java

@Cacheable(cacheName = "searchResultsCache", keyGenerator = @KeyGenerator(name = "StringCacheKeyGenerator"))
public RelatedGenesWebResponseDto getRelatedGenes(final RelatedGenesWebRequestDto dto)
        throws ApplicationException {
    final String rgcid = String.valueOf(System.currentTimeMillis());
    RelatedGenesWebResponseDto ret = new RelatedGenesWebResponseDto();
    jmsTemplate.send(requestQueue, new MessageCreator() {
        public TextMessage createMessage(Session session) throws JMSException {
            LOG.debug("sending GetRelatedGenesMessage request to " + requestQueue.getQueueName());
            RelatedGenesRequestMessage request = BrokerUtils.dto2msg(dto);
            TextMessage ret = session.createTextMessage(request.toXml());
            ret.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            ret.setJMSType(MessageType.RELATED_GENES.getCode());
            replyQueue = session.createTemporaryQueue();
            ret.setJMSReplyTo(replyQueue);
            ret.setJMSCorrelationID(rgcid);
            LOG.debug("getRelatedGenes waiting for reply on " + replyQueue.getQueueName());
            return ret;
        }/*w  w  w  .  jav  a 2s .c o m*/
    });
    sentMessages++;
    Message response;
    try {
        response = jmsTemplate.receive(replyQueue);
        receivedMessages++;
        if (response == null) {
            LOG.error("getRelatedGenes JMS response is null");
        } else if (!response.getJMSCorrelationID().equals(rgcid)) {
            LOG.error("JMS response id does not match request, sent " + rgcid + ", recieved "
                    + response.getJMSCorrelationID() + ", dropping response.");
        } else {
            LOG.debug("getRelatedGenes reply received");
            String responseBody = ((TextMessage) response).getText();
            if (StringUtils.isNotEmpty(responseBody)) {
                RelatedGenesResponseMessage responseMessage = RelatedGenesResponseMessage.fromXml(responseBody);
                LOG.debug("finished fromXml");
                LOG.debug("num attributes in response message: " + responseMessage.getAttributes().size());
                if (responseMessage.getErrorCode() == 0) {
                    // friendlyPrintNetworks("networks in response message: ",
                    // responseMessage.getNetworks());
                    // friendlyPrintCategories("categories in response message: ",
                    // responseMessage.getAnnotations());
                    RelatedGenesWebResponseDto hollowResponseDto = BrokerUtils.msg2dto(responseMessage);
                    LOG.debug("finished msg2dto");
                    ret = load(hollowResponseDto);
                    LOG.debug("finished hollowResponseDto");
                } else {
                    LOG.error(responseMessage.getErrorMessage());
                    appErrors++;
                    throw new ApplicationException(responseMessage.getErrorMessage(),
                            responseMessage.getErrorCode());
                }
            } else {
                LOG.error("getRelatedGenes empty response body");
            }
        }
        processedMessages++;
    } catch (JMSException e) {
        LOG.error("getRelatedGenes JMSException: " + e.getMessage());
        errors++;
        throw new ApplicationException(Constants.ERROR_CODES.APPLICATION_ERROR);
    } catch (DataStoreException e) {
        LOG.error("getRelatedGenes DataStoreException: " + e.getMessage());
        errors++;
        throw new ApplicationException(Constants.ERROR_CODES.DATA_ERROR);
    } finally {
        LOG.debug("messages sent/received/processed/errors: " + sentMessages + "/" + receivedMessages + "/"
                + processedMessages + "/" + errors);
        // updateStats();
    }
    LOG.debug("getRelatedGenes request processing completed");
    return ret;
}

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

/**
 * Strategy to determine which correlation id to use among <tt>JMSMessageID</tt> and <tt>JMSCorrelationID</tt>.
 *
 * @param message   the JMS message/*from  w w  w .  j  a  v a  2  s . co  m*/
 * @param provisionalCorrelationId an optional provisional correlation id, which is preferred to be used
 * @return the correlation id to use
 * @throws JMSException can be thrown
 */
protected String determineCorrelationId(Message message, String provisionalCorrelationId) throws JMSException {
    if (provisionalCorrelationId != null) {
        return provisionalCorrelationId;
    }

    final String messageId = message.getJMSMessageID();
    final String correlationId = message.getJMSCorrelationID();
    if (endpoint.getConfiguration().isUseMessageIDAsCorrelationID()) {
        return messageId;
    } else if (ObjectHelper.isEmpty(correlationId)) {
        // correlation id is empty so fallback to message id
        return messageId;
    } else {
        return correlationId;
    }
}

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

protected void copyStandardHeadersFromMessageToFrame(Message message, StompFrame command) throws JMSException {
    final Map headers = command.getHeaders();
    headers.put(Stomp.Headers.Message.DESTINATION, convertDestination(message.getJMSDestination()));
    headers.put(Stomp.Headers.Message.MESSAGE_ID, message.getJMSMessageID());

    if (message.getJMSCorrelationID() != null) {
        headers.put(Stomp.Headers.Message.CORRELATION_ID, message.getJMSCorrelationID());
    }//from w w  w.  j  av a2 s  . c  o  m
    headers.put(Stomp.Headers.Message.EXPIRATION_TIME, "" + message.getJMSExpiration());

    if (message.getJMSRedelivered()) {
        headers.put(Stomp.Headers.Message.REDELIVERED, "true");
    }
    headers.put(Stomp.Headers.Message.PRORITY, "" + message.getJMSPriority());

    if (message.getJMSReplyTo() != null) {
        headers.put(Stomp.Headers.Message.REPLY_TO, convertDestination(message.getJMSReplyTo()));
    }
    headers.put(Stomp.Headers.Message.TIMESTAMP, "" + message.getJMSTimestamp());

    if (message.getJMSType() != null) {
        headers.put(Stomp.Headers.Message.TYPE, message.getJMSType());
    }

    // now lets add all the message headers
    Enumeration names = message.getPropertyNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Object value = message.getObjectProperty(name);
        headers.put(name, value);
    }
}

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

/**
 * Process a new message received//  w  w  w.j av  a2 s . c  om
 *
 * @param message the JMS message received
 * @param ut      UserTransaction which was used to receive the message
 * @return true if caller should commit
 */
public boolean onMessage(Message message, UserTransaction ut) {

    try {
        if (log.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();
            sb.append("Received new JMS message for service :").append(endpoint.getServiceName());
            sb.append("\nDestination    : ").append(message.getJMSDestination());
            sb.append("\nMessage ID     : ").append(message.getJMSMessageID());
            sb.append("\nCorrelation ID : ").append(message.getJMSCorrelationID());
            sb.append("\nReplyTo        : ").append(message.getJMSReplyTo());
            sb.append("\nRedelivery ?   : ").append(message.getJMSRedelivered());
            sb.append("\nPriority       : ").append(message.getJMSPriority());
            sb.append("\nExpiration     : ").append(message.getJMSExpiration());
            sb.append("\nTimestamp      : ").append(message.getJMSTimestamp());
            sb.append("\nMessage Type   : ").append(message.getJMSType());
            sb.append("\nPersistent ?   : ").append(DeliveryMode.PERSISTENT == message.getJMSDeliveryMode());

            log.debug(sb.toString());
            if (log.isTraceEnabled() && message instanceof TextMessage) {
                log.trace("\nMessage : " + ((TextMessage) message).getText());
            }
        }
    } catch (JMSException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error reading JMS message headers for debug logging", e);
        }
    }

    // update transport level metrics
    try {
        metrics.incrementBytesReceived(JMSUtils.getMessageSize(message));
    } catch (JMSException e) {
        log.warn("Error reading JMS message size to update transport metrics", e);
    }

    // has this message already expired? expiration time == 0 means never expires
    // TODO: explain why this is necessary; normally it is the responsibility of the provider to handle message expiration
    try {
        long expiryTime = message.getJMSExpiration();
        if (expiryTime > 0 && System.currentTimeMillis() > expiryTime) {
            if (log.isDebugEnabled()) {
                log.debug("Discard expired message with ID : " + message.getJMSMessageID());
            }
            return true;
        }
    } catch (JMSException ignore) {
    }

    boolean successful = false;
    try {
        successful = processThoughEngine(message, ut);

    } catch (JMSException e) {
        log.error("JMS Exception encountered while processing", e);
    } catch (AxisFault e) {
        log.error("Axis fault processing message", e);
    } catch (Exception e) {
        log.error("Unknown error processing message", e);

    } finally {
        if (successful) {
            metrics.incrementMessagesReceived();
        } else {
            metrics.incrementFaultsReceiving();
        }
    }

    return successful;
}

From source file:org.genemania.broker.Worker.java

public synchronized void onMessage(Message msg) {
    if (msg instanceof TextMessage) {
        String responseBody = "";
        try {/*from ww w .  j a  v  a  2s. com*/
            // extract message data
            Queue queue = (Queue) msg.getJMSDestination();
            requestMessage = (TextMessage) msg;
            LOG.debug("new " + msg.getJMSType() + " message received on queue " + queue.getQueueName()
                    + "[correlation id: " + msg.getJMSCorrelationID() + "]");
            responseMessage = session.createTextMessage();
            responseMessage.setJMSDestination(requestMessage.getJMSReplyTo());
            responseMessage.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            responseMessage.setJMSCorrelationID(msg.getJMSCorrelationID());
            // invoke engine
            if (queue.getQueueName().equalsIgnoreCase(mqRequestsQueueName)) {
                if (MessageType.RELATED_GENES.equals(MessageType.fromCode(msg.getJMSType()))) {
                    RelatedGenesRequestMessage data = RelatedGenesRequestMessage
                            .fromXml(requestMessage.getText());
                    RelatedGenesResponseMessage response = getRelatedGenes(data);
                    responseBody = response.toXml();
                } else if (MessageType.TEXT2NETWORK.equals(MessageType.fromCode(msg.getJMSType()))) {
                    UploadNetworkRequestMessage data = UploadNetworkRequestMessage
                            .fromXml(requestMessage.getText());
                    UploadNetworkResponseMessage response = uploadNetwork(data);
                    responseBody = response.toXml();
                } else if (MessageType.PROFILE2NETWORK.equals(MessageType.fromCode(msg.getJMSType()))) {
                    LOG.warn("invoking engine.profile2network: not implemented");
                } else {
                    LOG.warn("Unknown jms type: " + msg.getJMSType());
                }
            }
            processedMessages++;
        } catch (JMSException e) {
            LOG.error(e);
            try {
                responseBody = buildErrorMessage(e.getMessage(), MessageType.fromCode(msg.getJMSType()));
            } catch (JMSException x) {
                LOG.error(x);
            }
        } finally {
            if ((requestMessage != null) && (responseMessage != null)) {
                try {
                    if (StringUtils.isNotEmpty(responseBody)) {
                        responseMessage.setText(responseBody);
                        LOG.debug("Responding to " + responseMessage.getJMSDestination() + ", msg id "
                                + responseMessage.getJMSCorrelationID() + ", response body size "
                                + (int) responseBody.length());
                        responseHandler.send(responseMessage.getJMSDestination(), responseMessage);
                    } else {
                        responseBody = buildErrorMessage("Empty response body detected",
                                MessageType.fromCode(msg.getJMSType()));
                    }
                } catch (JMSException e) {
                    LOG.error("JMS Exception: " + e.getMessage());
                    try {
                        responseBody = buildErrorMessage(e.getMessage(),
                                MessageType.fromCode(msg.getJMSType()));
                        responseHandler.send(responseMessage);
                    } catch (JMSException e1) {
                        LOG.error("JMS Exception", e1);
                    }
                }
            } else {
                if (requestMessage == null) {
                    LOG.error("request message is null");
                }
                if (responseMessage == null) {
                    LOG.error("response message is null");
                }
            }
        }
    } else {
        LOG.warn("Unknown message type: " + msg);
    }
    LOG.info("successfully processed messages: " + processedMessages);
}

From source file:org.apache.servicemix.jms.endpoints.AbstractConsumerEndpoint.java

protected void setCorrelationId(Message query, Message reply) throws Exception {
    if (useMessageIdInResponse == null) {
        if (query.getJMSCorrelationID() != null) {
            reply.setJMSCorrelationID(query.getJMSCorrelationID());
        } else if (query.getJMSMessageID() != null) {
            reply.setJMSCorrelationID(query.getJMSMessageID());
        } else {/*from   w w  w.j  a  v a 2 s .  c o m*/
            throw new IllegalStateException("No JMSCorrelationID or JMSMessageID set on query message");
        }
    } else if (useMessageIdInResponse.booleanValue()) {
        if (query.getJMSMessageID() != null) {
            reply.setJMSCorrelationID(query.getJMSMessageID());
        } else {
            throw new IllegalStateException("No JMSMessageID set on query message");
        }
    } else {
        if (query.getJMSCorrelationID() != null) {
            reply.setJMSCorrelationID(query.getJMSCorrelationID());
        } else {
            throw new IllegalStateException("No JMSCorrelationID set on query message");
        }
    }
}

From source file:org.apache.jmeter.protocol.jms.sampler.Receiver.java

@Override
public void run() {
    active = true;//from  w w  w  .  ja v a2s  .c o m
    Message reply;

    while (active) {
        reply = null;
        try {
            reply = consumer.receive(5000);
            if (reply != null) {
                String messageKey;
                final MessageAdmin admin = MessageAdmin.getAdmin();
                if (useResMsgIdAsCorrelId) {
                    messageKey = reply.getJMSMessageID();
                    synchronized (admin) {// synchronize with FixedQueueExecutor
                        admin.putReply(messageKey, reply);
                    }
                } else {
                    messageKey = reply.getJMSCorrelationID();
                    if (messageKey == null) {// JMSMessageID cannot be null
                        log.warn("Received message with correlation id null. Discarding message ...");
                    } else {
                        admin.putReply(messageKey, reply);
                    }
                }
            }

        } catch (JMSException e1) {
            log.error("Error handling receive", e1);
        }
    }
    Utils.close(consumer, log);
    Utils.close(session, log);
    Utils.close(conn, log);
}

From source file:org.springframework.integration.jms.DefaultJmsHeaderMapper.java

public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<String, Object>();
    try {/*from w  w  w  .j  a va 2  s  .  c o  m*/
        try {
            String messageId = jmsMessage.getJMSMessageID();
            if (messageId != null) {
                headers.put(JmsHeaders.MESSAGE_ID, messageId);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSMessageID property, skipping", e);
        }
        try {
            String correlationId = jmsMessage.getJMSCorrelationID();
            if (correlationId != null) {
                headers.put(JmsHeaders.CORRELATION_ID, correlationId);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSCorrelationID property, skipping", e);
        }
        try {
            Destination replyTo = jmsMessage.getJMSReplyTo();
            if (replyTo != null) {
                headers.put(JmsHeaders.REPLY_TO, replyTo);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSReplyTo property, skipping", e);
        }
        try {
            headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        } catch (Exception e) {
            logger.info("failed to read JMSRedelivered property, skipping", e);
        }
        try {
            String type = jmsMessage.getJMSType();
            if (type != null) {
                headers.put(JmsHeaders.TYPE, type);
            }
        } catch (Exception e) {
            logger.info("failed to read JMSType property, skipping", e);
        }
        try {
            headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        } catch (Exception e) {
            logger.info("failed to read JMSTimestamp property, skipping", e);
        }
        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
        if (jmsPropertyNames != null) {
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                try {
                    String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                } catch (Exception e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("error occurred while mapping JMS property '" + propertyName
                                + "' to Message header", e);
                    }
                }
            }
        }
    } catch (JMSException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("error occurred while mapping from JMS properties to MessageHeaders", e);
        }
    }
    return headers;
}