Example usage for javax.jms Message getJMSMessageID

List of usage examples for javax.jms Message getJMSMessageID

Introduction

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

Prototype


String getJMSMessageID() throws JMSException;

Source Link

Document

Gets the message ID.

Usage

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

/**
 * Process the new message through Axis2
 *
 * @param message the JMS message//from w ww  . ja va 2s  .co m
 * @param ut      the UserTransaction used for receipt
 * @return true if the caller should commit
 * @throws JMSException, on JMS exceptions
 * @throws AxisFault     on Axis2 errors
 */
private boolean processThoughEngine(Message message, UserTransaction ut) throws JMSException, AxisFault {

    MessageContext msgContext = endpoint.createMessageContext();

    // set the JMS Message ID as the Message ID of the MessageContext
    try {
        msgContext.setMessageID(message.getJMSMessageID());
        String jmsCorrelationID = message.getJMSCorrelationID();
        if (jmsCorrelationID != null && jmsCorrelationID.length() > 0) {
            msgContext.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID);
        } else {
            msgContext.setProperty(JMSConstants.JMS_COORELATION_ID, message.getJMSMessageID());
        }
    } catch (JMSException ignore) {
    }

    String soapAction = JMSUtils.getProperty(message, BaseConstants.SOAPACTION);

    ContentTypeInfo contentTypeInfo = endpoint.getContentTypeRuleSet().getContentTypeInfo(message);
    if (contentTypeInfo == null) {
        throw new AxisFault("Unable to determine content type for message " + msgContext.getMessageID());
    }

    // set the message property OUT_TRANSPORT_INFO
    // the reply is assumed to be over the JMSReplyTo destination, using
    // the same incoming connection factory, if a JMSReplyTo is available
    Destination replyTo = message.getJMSReplyTo();
    if (replyTo == null) {
        // does the service specify a default reply destination ?
        String jndiReplyDestinationName = endpoint.getJndiReplyDestinationName();
        if (jndiReplyDestinationName != null) {
            replyTo = jmsConnectionFactory.getDestination(jndiReplyDestinationName,
                    endpoint.getReplyDestinationType());
        }

    }
    if (replyTo != null) {
        msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                new JMSOutTransportInfo(jmsConnectionFactory, replyTo, contentTypeInfo.getPropertyName()));
    }

    JMSUtils.setSOAPEnvelope(message, msgContext, contentTypeInfo.getContentType());
    if (ut != null) {
        msgContext.setProperty(BaseConstants.USER_TRANSACTION, ut);
    }

    jmsListener.handleIncomingMessage(msgContext, JMSUtils.getTransportHeaders(message), soapAction,
            contentTypeInfo.getContentType());

    Object o = msgContext.getProperty(BaseConstants.SET_ROLLBACK_ONLY);
    if (o != null) {
        if ((o instanceof Boolean && ((Boolean) o)) || (o instanceof String && Boolean.valueOf((String) o))) {
            return false;
        }
    }
    return true;
}

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

/**
 * Perform actual send of JMS message to the Destination selected
 *
 * @param message the JMS message/*ww w.j av  a 2 s  . c  o  m*/
 * @param msgCtx the Axis2 MessageContext
 */
public void send(Message message, MessageContext msgCtx) {

    Boolean jtaCommit = getBooleanProperty(msgCtx, BaseConstants.JTA_COMMIT_AFTER_SEND);
    Boolean rollbackOnly = getBooleanProperty(msgCtx, BaseConstants.SET_ROLLBACK_ONLY);
    Boolean persistent = getBooleanProperty(msgCtx, JMSConstants.JMS_DELIVERY_MODE);
    Integer priority = getIntegerProperty(msgCtx, JMSConstants.JMS_PRIORITY);
    Integer timeToLive = getIntegerProperty(msgCtx, JMSConstants.JMS_TIME_TO_LIVE);

    // Do not commit, if message is marked for rollback
    if (rollbackOnly != null && rollbackOnly) {
        jtaCommit = Boolean.FALSE;
    }

    if (persistent != null) {
        try {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer for PERSISTENT delivery", e);
        }
    }
    if (priority != null) {
        try {
            producer.setPriority(priority);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer priority to : " + priority, e);
        }
    }
    if (timeToLive != null) {
        try {
            producer.setTimeToLive(timeToLive);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer TTL to : " + timeToLive, e);
        }
    }

    boolean sendingSuccessful = false;
    // perform actual message sending
    try {
        if (jmsSpec11 || isQueue == null) {
            producer.send(message);

        } else {
            if (isQueue) {
                ((QueueSender) producer).send(message);

            } else {
                ((TopicPublisher) producer).publish(message);
            }
        }

        // set the actual MessageID to the message context for use by any others down the line
        String msgId = null;
        try {
            msgId = message.getJMSMessageID();
            if (msgId != null) {
                msgCtx.setProperty(JMSConstants.JMS_MESSAGE_ID, msgId);
            }
        } catch (JMSException ignore) {
        }

        sendingSuccessful = true;

        if (log.isDebugEnabled()) {
            log.debug("Sent Message Context ID : " + msgCtx.getMessageID() + " with JMS Message ID : " + msgId
                    + " to destination : " + producer.getDestination());
        }

    } catch (JMSException e) {
        log.error("Error sending message with MessageContext ID : " + msgCtx.getMessageID()
                + " to destination : " + destination, e);

    } finally {

        if (jtaCommit != null) {

            UserTransaction ut = (UserTransaction) msgCtx.getProperty(BaseConstants.USER_TRANSACTION);
            if (ut != null) {

                try {
                    if (sendingSuccessful && jtaCommit) {
                        ut.commit();
                    } else {
                        ut.rollback();
                    }
                    msgCtx.removeProperty(BaseConstants.USER_TRANSACTION);

                    if (log.isDebugEnabled()) {
                        log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " JTA Transaction");
                    }

                } catch (Exception e) {
                    handleException("Error committing/rolling back JTA transaction after "
                            + "sending of message with MessageContext ID : " + msgCtx.getMessageID()
                            + " to destination : " + destination, e);
                }
            }

        } else {
            try {
                if (session.getTransacted()) {
                    if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) {
                        session.commit();
                    } else {
                        session.rollback();
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug((sendingSuccessful ? "Committed" : "Rolled back")
                            + " local (JMS Session) Transaction");
                }

            } catch (JMSException e) {
                handleException("Error committing/rolling back local (i.e. session) "
                        + "transaction after sending of message with MessageContext ID : "
                        + msgCtx.getMessageID() + " to destination : " + destination, e);
            }
        }
    }
}

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

/**
 * Perform actual sending of the JMS message
 *//* w  ww  . j  av a  2s .c  o m*/
private void sendOverJMS(MessageContext msgCtx, JMSMessageSender messageSender, String contentTypeProperty,
        JMSConnectionFactory jmsConnectionFactory, JMSOutTransportInfo jmsOut) throws AxisFault {

    // convert the axis message context into a JMS Message that we can send over JMS
    Message message = null;
    String correlationId = null;
    try {
        message = createJMSMessage(msgCtx, messageSender.getSession(), contentTypeProperty);
    } catch (JMSException e) {
        handleException("Error creating a JMS message from the message context", e);
    }

    // should we wait for a synchronous response on this same thread?
    boolean waitForResponse = waitForSynchronousResponse(msgCtx);
    Destination replyDestination = jmsOut.getReplyDestination();

    // if this is a synchronous out-in, prepare to listen on the response destination
    if (waitForResponse) {

        String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO);
        if (replyDestName == null && jmsConnectionFactory != null) {
            replyDestName = jmsConnectionFactory.getReplyToDestination();
        }

        String replyDestType = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO_TYPE);
        if (replyDestType == null && jmsConnectionFactory != null) {
            replyDestType = jmsConnectionFactory.getReplyDestinationType();
        }

        if (replyDestName != null) {
            if (jmsConnectionFactory != null) {
                replyDestination = jmsConnectionFactory.getDestination(replyDestName, replyDestType);
            } else {
                replyDestination = jmsOut.getReplyDestination(replyDestName);
            }
        }
        replyDestination = JMSUtils.setReplyDestination(replyDestination, messageSender.getSession(), message);
    }

    try {
        messageSender.send(message, msgCtx);
        metrics.incrementMessagesSent(msgCtx);

    } catch (AxisJMSException e) {
        metrics.incrementFaultsSending();
        handleException("Error sending JMS message", e);
    }

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

    // if we are expecting a synchronous response back for the message sent out
    if (waitForResponse) {
        // TODO ********************************************************************************
        // TODO **** replace with asynchronous polling via a poller task to process this *******
        // information would be given. Then it should poll (until timeout) the
        // requested destination for the response message and inject it from a
        // asynchronous worker thread
        try {
            messageSender.getConnection().start(); // multiple calls are safely ignored
        } catch (JMSException ignore) {
        }

        try {
            String jmsCorrelationID = message.getJMSCorrelationID();
            if (jmsCorrelationID != null && jmsCorrelationID.length() > 0) {
                correlationId = jmsCorrelationID;
            } else {
                correlationId = message.getJMSMessageID();
            }
        } catch (JMSException ignore) {
        }

        // We assume here that the response uses the same message property to
        // specify the content type of the message.
        waitForResponseAndProcess(messageSender.getSession(), replyDestination, msgCtx, correlationId,
                contentTypeProperty);
        // TODO ********************************************************************************
    }
}

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

/**
 * Extract transport level headers for JMS from the given message into a Map
 *
 * @param message the JMS message//from  www .ja  v  a  2 s  .com
 * @return a Map of the transport headers
 */
public static Map<String, Object> getTransportHeaders(Message message) {
    // create a Map to hold transport headers
    Map<String, Object> map = new HashMap<String, Object>();

    // correlation ID
    try {
        if (message.getJMSCorrelationID() != null) {
            map.put(JMSConstants.JMS_COORELATION_ID, message.getJMSCorrelationID());
        }
    } catch (JMSException ignore) {
    }

    // set the delivery mode as persistent or not
    try {
        map.put(JMSConstants.JMS_DELIVERY_MODE, Integer.toString(message.getJMSDeliveryMode()));
    } catch (JMSException ignore) {
    }

    // destination name
    try {
        if (message.getJMSDestination() != null) {
            Destination dest = message.getJMSDestination();
            map.put(JMSConstants.JMS_DESTINATION,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // expiration
    try {
        map.put(JMSConstants.JMS_EXPIRATION, Long.toString(message.getJMSExpiration()));
    } catch (JMSException ignore) {
    }

    // if a JMS message ID is found
    try {
        if (message.getJMSMessageID() != null) {
            map.put(JMSConstants.JMS_MESSAGE_ID, message.getJMSMessageID());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_PRIORITY, Long.toString(message.getJMSPriority()));
    } catch (JMSException ignore) {
    }

    // redelivered
    try {
        map.put(JMSConstants.JMS_REDELIVERED, Boolean.toString(message.getJMSRedelivered()));
    } catch (JMSException ignore) {
    }

    // replyto destination name
    try {
        if (message.getJMSReplyTo() != null) {
            Destination dest = message.getJMSReplyTo();
            map.put(JMSConstants.JMS_REPLY_TO,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_TIMESTAMP, Long.toString(message.getJMSTimestamp()));
    } catch (JMSException ignore) {
    }

    // message type
    try {
        if (message.getJMSType() != null) {
            map.put(JMSConstants.JMS_TYPE, message.getJMSType());
        }
    } catch (JMSException ignore) {
    }

    // any other transport properties / headers
    Enumeration<?> e = null;
    try {
        e = message.getPropertyNames();
    } catch (JMSException ignore) {
    }

    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            try {
                map.put(headerName, message.getStringProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getBooleanProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getIntProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getLongProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getDoubleProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, message.getFloatProperty(headerName));
            } catch (JMSException ignore) {
            }
        }
    }

    return map;
}

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

@Before("(call(void javax.jms.MessageProducer.send(javax.jms.Message)) ||"
        + " call(void javax.jms.TopicPublisher.publish(javax.jms.Message))) && args(message)")
public void beforeSend(Message message) {
    try {//from w  w  w .  ja  v  a2s .c om
        OutputStream out = LogManager.INSTANCE.createLog("jms");
        try {
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(out), false);
            pw.println("Type: " + message.getClass().getName());
            pw.println("JMS message ID: " + message.getJMSMessageID());
            pw.println("JMS correlation ID: " + message.getJMSCorrelationID());
            pw.println("JMS reply to: " + message.getJMSReplyTo());
            for (Enumeration<?> e = message.getPropertyNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                pw.print(name);
                pw.print(": ");
                pw.println(message.getStringProperty(name));
            }
            pw.println();
            pw.flush();
            if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                bytesMessage.reset();
                IOUtils.copy(new BytesMessageInputStream(bytesMessage), out);
            } else if (message instanceof TextMessage) {
                pw.print(((TextMessage) message).getText());
                pw.flush();
            }
        } finally {
            out.close();
        }
    } catch (Throwable ex) {
        log.error("Failed to dump JMS message", ex);
    }
}

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   ww w  .ja va2  s.c om
    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

/**
 * Strategy to determine which correlation id to use among <tt>JMSMessageID</tt> and <tt>JMSCorrelationID</tt>.
 *
 * @param message the JMS message//  w w  w .  ja va2 s  . c  o  m
 * @return the correlation id to use
 * @throws JMSException can be thrown
 */
protected String determineCorrelationId(final Message message) throws JMSException {
    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.apache.camel.component.jms.JmsBinding.java

public Map<String, Object> extractHeadersFromJms(Message jmsMessage, Exchange exchange) {
    Map<String, Object> map = new HashMap<String, Object>();
    if (jmsMessage != null) {
        // lets populate the standard JMS message headers
        try {/*w ww  .  ja v  a2  s  . c o  m*/
            map.put("JMSCorrelationID", jmsMessage.getJMSCorrelationID());
            map.put("JMSDeliveryMode", jmsMessage.getJMSDeliveryMode());
            map.put("JMSDestination", jmsMessage.getJMSDestination());
            map.put("JMSExpiration", jmsMessage.getJMSExpiration());
            map.put("JMSMessageID", jmsMessage.getJMSMessageID());
            map.put("JMSPriority", jmsMessage.getJMSPriority());
            map.put("JMSRedelivered", jmsMessage.getJMSRedelivered());
            map.put("JMSTimestamp", jmsMessage.getJMSTimestamp());

            // to work around OracleAQ not supporting the JMSReplyTo header (CAMEL-2909)
            try {
                map.put("JMSReplyTo", jmsMessage.getJMSReplyTo());
            } catch (JMSException e) {
                LOG.trace("Cannot read JMSReplyTo header. Will ignore this exception.", e);
            }
            // to work around OracleAQ not supporting the JMSType header (CAMEL-2909)
            try {
                map.put("JMSType", jmsMessage.getJMSType());
            } catch (JMSException e) {
                LOG.trace("Cannot read JMSType header. Will ignore this exception.", e);
            }

            // this works around a bug in the ActiveMQ property handling
            map.put("JMSXGroupID", jmsMessage.getStringProperty("JMSXGroupID"));
        } catch (JMSException e) {
            throw new RuntimeCamelException(e);
        }

        Enumeration names;
        try {
            names = jmsMessage.getPropertyNames();
        } catch (JMSException e) {
            throw new RuntimeCamelException(e);
        }
        while (names.hasMoreElements()) {
            String name = names.nextElement().toString();
            try {
                Object value = jmsMessage.getObjectProperty(name);
                if (headerFilterStrategy != null
                        && headerFilterStrategy.applyFilterToExternalHeaders(name, value, exchange)) {
                    continue;
                }

                // must decode back from safe JMS header name to original header name
                // when storing on this Camel JmsMessage object.
                String key = jmsKeyFormatStrategy.decodeKey(name);
                map.put(key, value);
            } catch (JMSException e) {
                throw new RuntimeCamelException(name, e);
            }
        }
    }

    return map;
}

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

public void setJmsMessage(Message jmsMessage) {
    if (jmsMessage != null) {
        try {/*  w ww .j  a va 2s.c  o m*/
            setMessageId(jmsMessage.getJMSMessageID());
        } catch (JMSException e) {
            LOG.warn("Unable to retrieve JMSMessageID from JMS Message", e);
        }
    }
    this.jmsMessage = jmsMessage;
}

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/*  w ww  .  ja  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;
    }
}