Example usage for javax.jms Message getJMSExpiration

List of usage examples for javax.jms Message getJMSExpiration

Introduction

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

Prototype


long getJMSExpiration() throws JMSException;

Source Link

Document

Gets the message's expiration time.

Usage

From source file:com.jmstoolkit.beans.MessageTableModel.java

/**
 *
 * @param message//from ww w. j  a  v  a  2  s. c o m
 */
@Override
public void onMessage(Message message) {
    LOGGER.log(Level.FINE, "Message Received");
    messagesReceived++;
    try {
        MessageTableRecord qRecord = new MessageTableRecord();
        qRecord.setJMSCorrelationID(message.getJMSCorrelationID());
        qRecord.setJMSDeliveryMode(message.getJMSDeliveryMode());
        qRecord.setJMSExpiration(message.getJMSExpiration());
        qRecord.setJMSMessageID(message.getJMSMessageID());
        qRecord.setJMSTimestamp(message.getJMSTimestamp());
        qRecord.setJMSType(message.getJMSType());
        qRecord.setJMSDestination(message.getJMSDestination());
        qRecord.setJMSCorrelationIDAsBytes(message.getJMSCorrelationIDAsBytes());
        qRecord.setJMSPriority(message.getJMSPriority());
        qRecord.setJMSType(message.getJMSType());
        qRecord.setJMSReplyTo(message.getJMSReplyTo());
        qRecord.setJMSRedelivered(message.getJMSRedelivered());
        Enumeration pEnumerator = message.getPropertyNames();
        Properties props = new Properties();
        while (pEnumerator.hasMoreElements()) {
            String pElement = (String) pEnumerator.nextElement();
            props.put(pElement, message.getStringProperty(pElement));
        }
        qRecord.setProperties(props);

        if (message instanceof TextMessage) {
            qRecord.setText(((TextMessage) message).getText());
        }
        if (message instanceof ObjectMessage) {
            qRecord.setObject(((ObjectMessage) message).getObject());
        }

        List newData = data;
        newData.add(qRecord);
        this.setData(newData);
    } catch (JMSException e) {
        LOGGER.log(Level.WARNING, "JMS problem", e);
    }
}

From source file:com.adaptris.core.jms.MessageTypeTranslatorCase.java

public void testMoveJmsHeadersAdaptrisMessageToJmsMessage() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    try {// w w w. jav  a2  s  .c  o  m
        broker.start();
        Session session = broker.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);

        AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
        addMetadata(msg);
        addRedundantJmsHeaders(msg);

        trans.setMoveJmsHeaders(true);
        start(trans, session);

        Message jmsMsg = trans.translate(msg);
        assertEquals(msg.getMetadataValue(JMS_TYPE), jmsMsg.getJMSType());
        assertNotSame(msg.getMetadataValue(JMS_CORRELATION_ID), jmsMsg.getJMSCorrelationID());
        assertNotSame(msg.getMetadataValue(JMS_TIMESTAMP), jmsMsg.getJMSTimestamp());
        assertNotSame(msg.getMetadataValue(JMS_REDELIVERED), jmsMsg.getJMSPriority());
        assertNotSame(msg.getMetadataValue(JMS_MESSAGE_ID), jmsMsg.getJMSMessageID());
        assertNotSame(msg.getMetadataValue(JMS_EXPIRATION), jmsMsg.getJMSExpiration());
        assertNotSame(msg.getMetadataValue(JMS_DELIVERY_MODE), jmsMsg.getJMSDeliveryMode());
        assertJmsProperties(jmsMsg);
    } finally {
        stop(trans);
        broker.destroy();
    }

}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

private static String formatHeaders(Message message) {
    Destination dest = null;// www .j  a  va 2s .c  o  m
    int delMode = 0;
    long expiration = 0;
    Time expTime = null;
    int priority = 0;
    String msgID = null;
    long timestamp = 0;
    Time timestampTime = null;
    String correlID = null;
    Destination replyTo = null;
    boolean redelivered = false;
    String type = null;

    StringBuilder sb = new StringBuilder();
    try {

        try {
            dest = message.getJMSDestination();
            sb.append("  JMSDestination: ");
            sb.append(dest);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSDestination header\n", e);
        }

        try {
            delMode = message.getJMSDeliveryMode();
            if (delMode == DeliveryMode.NON_PERSISTENT) {
                sb.append("  JMSDeliveryMode: non-persistent\n");
            } else if (delMode == DeliveryMode.PERSISTENT) {
                sb.append("  JMSDeliveryMode: persistent\n");
            } else {
                sb.append("  JMSDeliveryMode: neither persistent nor non-persistent; error\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSDeliveryMode header\n", e);
        }

        try {
            expiration = message.getJMSExpiration();
            if (expiration != 0) {
                expTime = new Time(expiration);
                sb.append("  JMSExpiration: ");
                sb.append(expTime);
                sb.append("\n");
            } else {
                sb.append("  JMSExpiration: 0\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSExpiration header\n", e);
        }

        try {
            priority = message.getJMSPriority();
            sb.append("  JMSPriority: ");
            sb.append(priority);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSPriority header\n", e);
        }

        try {
            msgID = message.getJMSMessageID();
            sb.append("  JMSMessageID: ");
            sb.append(msgID);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSMessageID header\n", e);
        }

        try {
            timestamp = message.getJMSTimestamp();
            if (timestamp != 0) {
                timestampTime = new Time(timestamp);
                sb.append("  JMSTimestamp: ");
                sb.append(timestampTime);
                sb.append("\n");
            } else {
                sb.append("  JMSTimestamp: 0\n");
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSTimestamp header\n", e);
        }

        try {
            correlID = message.getJMSCorrelationID();
            sb.append("  JMSCorrelationID: ");
            sb.append(correlID);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSCorrelationID header\n", e);
        }

        try {
            replyTo = message.getJMSReplyTo();
            sb.append("  JMSReplyTo: ");
            sb.append(replyTo);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSReplyTo header\n", e);
        }

        try {
            redelivered = message.getJMSRedelivered();
            sb.append("  JMSRedelivered: ");
            sb.append(redelivered);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSRedelivered header\n", e);
        }

        try {
            type = message.getJMSType();
            sb.append("  JMSType: ");
            sb.append(type);
            sb.append("\n");
        } catch (Exception e) {
            log.log(Level.WARNING, "Unable to generate JMSType header\n", e);
        }

    } catch (Exception e) {
        log.log(Level.WARNING, "Unable to generate JMS headers\n", e);
    }
    return sb.toString();
}

From source file:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {//ww w. ja va 2 s. c om
        XMLMessage rval = factory.createXMLMessage();

        if (message instanceof TextMessage) {
            rval = factory.createXMLTextMessage();

            XMLTextMessage textRval = (XMLTextMessage) rval;
            TextMessage textMessage = (TextMessage) message;

            if (isBase64EncodeTextMessages()) {
                byte[] bytes = base64EncoderTL.get().encode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
                textRval.setCodec(BASE64_CODEC);
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof MapMessage) {
            rval = factory.createXMLMapMessage();

            XMLMapMessage mapRval = (XMLMapMessage) rval;
            MapMessage mapMessage = (MapMessage) message;

            for (Enumeration iter = mapMessage.getMapNames(); iter.hasMoreElements();) {
                String propertyName = (String) iter.nextElement();
                Object propertyValue = mapMessage.getObject(propertyName);
                Property xmlProperty = factory.createProperty();

                if (propertyValue != null) {
                    xmlProperty.setValue(propertyValue.toString());
                    xmlProperty.setType(propertyValue.getClass().getName());
                }
                xmlProperty.setName(propertyName);

                mapRval.getBodyProperty().add(xmlProperty);
            }
        } else if (message instanceof BytesMessage) {
            rval = factory.createXMLBytesMessage();

            XMLBytesMessage bytesRval = (XMLBytesMessage) rval;
            BytesMessage bytesMessage = (BytesMessage) message;
            ByteArrayOutputStream bosream = new ByteArrayOutputStream();

            bytesMessage.reset();

            try {
                for (;;) {
                    bosream.write(bytesMessage.readByte());
                }
            } catch (MessageEOFException ex) {
                // NOP
            }

            bytesRval.setBytes(new String(base64EncoderTL.get().encode(bosream.toByteArray())));
        } else if (message instanceof ObjectMessage) {
            rval = factory.createXMLObjectMessage();

            XMLObjectMessage objectRval = (XMLObjectMessage) rval;
            ObjectMessage objectMessage = (ObjectMessage) message;

            ByteArrayOutputStream bostream = new ByteArrayOutputStream();
            ObjectOutputStream oostream = new ObjectOutputStream(bostream);

            oostream.writeObject(objectMessage.getObject());
            oostream.flush();
            byte b[] = base64EncoderTL.get().encode(bostream.toByteArray());
            String s = new String(b, "ASCII");
            objectRval.setObject(s);
        }

        if (message.getJMSReplyTo() != null) {
            rval.setJMSReplyTo(JMSUtils.getDestinationName(message.getJMSReplyTo()));
            rval.setJMSReplyToDomain(Domain.getDomain(message.getJMSReplyTo()).getId());
        }

        // try/catch each individually as we sometime find some JMS
        // providers
        // can barf
        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSExpiration(message.getJMSExpiration());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSPriority(message.getJMSPriority());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSRedelivered(message.getJMSRedelivered());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        } catch (IllegalStateException ex) {
            // http://hermesjms.com/forum/viewtopic.php?f=4&t=346

            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSTimestamp(message.getJMSTimestamp());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSType(message.getJMSType());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            if (message.getJMSDestination() != null) {
                rval.setJMSDestination(JMSUtils.getDestinationName(message.getJMSDestination()));
                rval.setFromQueue(JMSUtils.isQueue(message.getJMSDestination()));
            }
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        for (final Enumeration iter = message.getPropertyNames(); iter.hasMoreElements();) {
            String propertyName = (String) iter.nextElement();

            if (!propertyName.startsWith("JMS")) {
                Object propertyValue = message.getObjectProperty(propertyName);
                Property property = factory.createProperty();

                property.setName(propertyName);

                if (propertyValue != null) {
                    property.setValue(StringEscapeUtils.escapeXml(propertyValue.toString()));
                    property.setType(propertyValue.getClass().getName());
                }

                rval.getHeaderProperty().add(property);
            }
        }

        return rval;
    } catch (Exception ex) {
        throw new HermesException(ex);
    }
}

From source file:nl.nn.adapterframework.jms.JMSFacade.java

public String send(MessageProducer messageProducer, Message message, boolean ignoreInvalidDestinationException)
        throws NamingException, JMSException {
    if (log.isDebugEnabled()) {
        log.debug(getLogPrefix() + "sender on [" + getDestinationName()
                + "] will send message with JMSDeliveryMode=[" + message.getJMSDeliveryMode()
                + "] \n  JMSMessageID=[" + message.getJMSMessageID() + "] \n  JMSCorrelationID=["
                + message.getJMSCorrelationID() + "] \n  JMSTimestamp=["
                + DateUtils.format(message.getJMSTimestamp()) + "] \n  JMSExpiration=["
                + message.getJMSExpiration() + "] \n  JMSPriority=[" + message.getJMSPriority()
                + "] \n Message=[" + message.toString() + "]");
    }//from   www  .  j  ava2 s  . c  o  m
    try {
        if (useJms102()) {
            if (messageProducer instanceof TopicPublisher) {
                ((TopicPublisher) messageProducer).publish(message);
            } else {
                ((QueueSender) messageProducer).send(message);
            }
            return message.getJMSMessageID();
        } else {
            messageProducer.send(message);
            return message.getJMSMessageID();
        }
    } catch (InvalidDestinationException e) {
        if (ignoreInvalidDestinationException) {
            log.warn("queue [" + messageProducer.getDestination() + "] doesn't exist");
            return null;
        } else {
            throw e;
        }
    }
}

From source file:nl.nn.adapterframework.jms.PullingJmsListener.java

public void afterMessageProcessed(PipeLineResult plr, Object rawMessage, Map threadContext)
        throws ListenerException {
    String cid = (String) threadContext.get(IPipeLineSession.technicalCorrelationIdKey);

    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "in PullingJmsListener.afterMessageProcessed()");

    try {//from   w  ww  .  j  a  v  a  2 s . co  m
        Destination replyTo = (Destination) threadContext.get("replyTo");

        // handle reply
        if (isUseReplyTo() && (replyTo != null)) {
            Session session = null;

            log.debug(getLogPrefix() + "sending reply message with correlationID [" + cid + "], replyTo ["
                    + replyTo.toString() + "]");
            long timeToLive = getReplyMessageTimeToLive();
            boolean ignoreInvalidDestinationException = false;
            if (timeToLive == 0) {
                Message messageSent = (Message) rawMessage;
                long expiration = messageSent.getJMSExpiration();
                if (expiration != 0) {
                    timeToLive = expiration - new Date().getTime();
                    if (timeToLive <= 0) {
                        log.warn(getLogPrefix() + "message [" + cid + "] expired [" + timeToLive
                                + "]ms, sending response with 1 second time to live");
                        timeToLive = 1000;
                        // In case of a temporary queue it might already
                        // have disappeared.
                        ignoreInvalidDestinationException = true;
                    }
                }
            }
            if (threadContext != null) {
                session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
            }
            if (session == null) {
                try {
                    session = getSession(threadContext);
                    send(session, replyTo, cid, prepareReply(plr.getResult(), threadContext),
                            getReplyMessageType(), timeToLive, stringToDeliveryMode(getReplyDeliveryMode()),
                            getReplyPriority(), ignoreInvalidDestinationException);
                } finally {
                    releaseSession(session);
                }
            } else {
                send(session, replyTo, cid, plr.getResult(), getReplyMessageType(), timeToLive,
                        stringToDeliveryMode(getReplyDeliveryMode()), getReplyPriority(),
                        ignoreInvalidDestinationException);
            }
        } else {
            if (getSender() == null) {
                log.debug(getLogPrefix()
                        + "itself has no sender to send the result (An enclosing Receiver might still have one).");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix()
                            + "no replyTo address found or not configured to use replyTo, using default destination"
                            + "sending message with correlationID[" + cid + "] [" + plr.getResult() + "]");
                }
                getSender().sendMessage(cid, plr.getResult());
            }
        }

        // TODO Do we still need this? Should we rollback too? See
        // PushingJmsListener.afterMessageProcessed() too (which does a
        // rollback, but no commit).
        if (!isTransacted()) {
            if (isJmsTransacted()) {
                // the following if transacted using transacted sessions, instead of XA-enabled sessions.
                Session session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
                if (session == null) {
                    log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                            + "] has no session to commit or rollback");
                } else {
                    String successState = getCommitOnState();
                    if (successState != null && successState.equals(plr.getState())) {
                        session.commit();
                    } else {
                        log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                                + "] not committed nor rolled back either");
                        //TODO: enable rollback, or remove support for JmsTransacted altogether (XA-transactions should do it all)
                        // session.rollback();
                    }
                    if (isSessionsArePooled()) {
                        threadContext.remove(THREAD_CONTEXT_SESSION_KEY);
                        releaseSession(session);
                    }
                }
            } else {
                // TODO: dit weghalen. Het hoort hier niet, en zit ook al in getIdFromRawMessage. Daar hoort het ook niet, overigens...
                if (getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                    log.debug("[" + getName() + "] acknowledges message with id [" + cid + "]");
                    ((TextMessage) rawMessage).acknowledge();
                }
            }
        }
    } catch (Exception e) {
        throw new ListenerException(e);
    }
}

From source file:nl.nn.adapterframework.jms.PushingJmsListener.java

public void afterMessageProcessed(PipeLineResult plr, Object rawMessage, Map threadContext)
        throws ListenerException {
    String cid = (String) threadContext.get(IPipeLineSession.technicalCorrelationIdKey);
    Session session = (Session) threadContext.get(jmsConnector.THREAD_CONTEXT_SESSION_KEY); // session is/must be saved in threadcontext by JmsConnector

    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "in PushingJmsListener.afterMessageProcessed()");
    try {/*from  w  ww  .  j a  v  a2s .co m*/
        Destination replyTo = (Destination) threadContext.get("replyTo");

        // handle reply
        if (isUseReplyTo() && (replyTo != null)) {

            log.debug("sending reply message with correlationID[" + cid + "], replyTo [" + replyTo.toString()
                    + "]");
            long timeToLive = getReplyMessageTimeToLive();
            boolean ignoreInvalidDestinationException = false;
            if (timeToLive == 0) {
                Message messageReceived = (Message) rawMessage;
                long expiration = messageReceived.getJMSExpiration();
                if (expiration != 0) {
                    timeToLive = expiration - new Date().getTime();
                    if (timeToLive <= 0) {
                        log.warn("message [" + cid + "] expired [" + timeToLive
                                + "]ms, sending response with 1 second time to live");
                        timeToLive = 1000;
                        // In case of a temporary queue it might already
                        // have disappeared.
                        ignoreInvalidDestinationException = true;
                    }
                }
            }
            Map properties = getMessagePropertiesToSet(threadContext);
            send(session, replyTo, cid, prepareReply(plr.getResult(), threadContext), getReplyMessageType(),
                    timeToLive, stringToDeliveryMode(getReplyDeliveryMode()), getReplyPriority(),
                    ignoreInvalidDestinationException, properties);
        } else {
            if (getSender() == null) {
                log.info("[" + getName() + "] has no sender, not sending the result.");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("[" + getName()
                            + "] no replyTo address found or not configured to use replyTo, using default destination"
                            + "sending message with correlationID[" + cid + "] [" + plr.getResult() + "]");
                }
                getSender().sendMessage(cid, plr.getResult());
            }
        }

        // TODO Do we still need this? Should we commit too? See
        // PullingJmsListener.afterMessageProcessed() too (which does a
        // commit, but no rollback).
        if (plr != null && !isTransacted() && isJmsTransacted() && StringUtils.isNotEmpty(getCommitOnState())
                && !getCommitOnState().equals(plr.getState())) {
            if (session == null) {
                log.error(getLogPrefix() + "session is null, cannot roll back session");
            } else {
                log.warn(getLogPrefix() + "got exit state [" + plr.getState() + "], rolling back session");
                session.rollback();
            }
        }
    } catch (Exception e) {
        if (e instanceof ListenerException) {
            throw (ListenerException) e;
        } else {
            throw new ListenerException(e);
        }
    }
}

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

/**
 * Process a new message received/*from w ww . j  av a2s  .com*/
 *
 * @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.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   w w  w . j  av a 2s. co m*/
 * @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.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 {/*from   w  w w  . ja va 2 s. co 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;
}