Example usage for javax.jms Message getObjectProperty

List of usage examples for javax.jms Message getObjectProperty

Introduction

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

Prototype


Object getObjectProperty(String name) throws JMSException;

Source Link

Document

Returns the value of the Java object property with the specified name.

Usage

From source file:org.sdnmq.jms_demoapps.FilteringPacketInSubscriber.java

private static void printMsgProperties(Message msg) {
    try {/*from  ww  w.  j av  a 2s.c o  m*/
        Enumeration keys = msg.getPropertyNames();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            Object value = msg.getObjectProperty(key);
            System.out.println(key + " " + value.toString());
        }
    } catch (JMSException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.icesoft.net.messaging.jms.AbstractJMSConnection.java

protected static String toString(final javax.jms.Message message) {
    StringBuffer _messageString = new StringBuffer();
    try {//from   w  w w.  j a v a  2s . co  m
        Enumeration _propertyNames = message.getPropertyNames();
        while (_propertyNames.hasMoreElements()) {
            String _propertyName = (String) _propertyNames.nextElement();
            _messageString.append(_propertyName);
            _messageString.append(": ");
            _messageString.append(message.getObjectProperty(_propertyName));
            _messageString.append("\r\n");
        }
        _messageString.append("\r\n");
        if (message instanceof javax.jms.ObjectMessage) {
            _messageString.append(((javax.jms.ObjectMessage) message).getObject());
        } else if (message instanceof javax.jms.TextMessage) {
            _messageString.append(((javax.jms.TextMessage) message).getText());
        }
        _messageString.append("\r\n");
    } catch (JMSException exception) {
        // do nothing (this is just a toString() method)
    }
    return _messageString.toString();
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSUtils.java

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

    try {
        Enumeration<?> propertyNamesEnm = message.getPropertyNames();

        while (propertyNamesEnm.hasMoreElements()) {
            String headerName = (String) propertyNamesEnm.nextElement();
            Object headerValue = message.getObjectProperty(headerName);

            if (headerValue instanceof String) {
                if (isHyphenReplaceMode(msgContext)) {
                    map.put(inverseTransformHyphenatedString(headerName),
                            message.getStringProperty(headerName));
                } else {
                    map.put(headerName, message.getStringProperty(headerName));
                }
            } else if (headerValue instanceof Integer) {
                map.put(headerName, message.getIntProperty(headerName));
            } else if (headerValue instanceof Boolean) {
                map.put(headerName, message.getBooleanProperty(headerName));
            } else if (headerValue instanceof Long) {
                map.put(headerName, message.getLongProperty(headerName));
            } else if (headerValue instanceof Double) {
                map.put(headerName, message.getDoubleProperty(headerName));
            } else if (headerValue instanceof Float) {
                map.put(headerName, message.getFloatProperty(headerName));
            } else {
                map.put(headerName, headerValue);
            }
        }

    } catch (JMSException e) {
        log.error("Error while reading the Transport Headers from JMS Message", e);
    }

    return map;
}

From source file:org.jbpm.bpel.integration.jms.RequestListener.java

public static String messageToString(Message message) throws JMSException {
    StringBuffer result = new StringBuffer();
    // ID & destination
    result.append("id=").append(message.getJMSMessageID()).append(", destination=")
            .append(message.getJMSDestination());
    // replyTo & correlationID
    Destination replyTo = message.getJMSReplyTo();
    if (replyTo != null) {
        result.append(", replyTo=").append(replyTo).append(", correlationId=")
                .append(message.getJMSCorrelationID());
    }/* w  w  w . ja va2 s  . c o m*/
    // properties
    Enumeration propertyNames = message.getPropertyNames();
    while (propertyNames.hasMoreElements()) {
        String propertyName = (String) propertyNames.nextElement();
        result.append(", ").append(propertyName).append('=').append(message.getObjectProperty(propertyName));
    }
    return result.toString();
}

From source file:org.mule.transport.jms.filters.JmsPropertyFilter.java

public boolean accept(MuleMessage message) {
    if (StringUtils.isBlank(propertyName)) {
        logger.warn("No property name was specified");
        return false;
    }// ww  w. j av  a2  s.  com

    if (StringUtils.isBlank(expression) && pattern == null) {
        logger.warn("Either no expression or pattern was specified");
        return false;
    }

    if (message.getPayload() instanceof javax.jms.Message) {
        try {
            Message m = (javax.jms.Message) message.getPayload();

            if (StringUtils.isBlank(propertyClass)) {
                Object object = m.getObjectProperty(propertyName);
                if (object == null) {
                    return false;
                }
                String value = object.toString();

                if (pattern != null) {
                    return pattern.matcher(value).find();
                } else {
                    return value.equals(expression);
                }
            } else if (propertyClass.equals("java.lang.String")) {
                String value = m.getStringProperty(propertyName);
                if (value == null) {
                    return false;
                }

                if (pattern != null) {
                    return pattern.matcher(value).find();
                } else {
                    return value.equals(expression);
                }
            } else if (propertyClass.equals("java.lang.Integer")) {
                int value = m.getIntProperty(propertyName);
                int match = Integer.parseInt(expression);
                return (value == match);
            } else if (propertyClass.equals("java.lang.Short")) {
                short value = m.getShortProperty(propertyName);
                short match = Short.parseShort(expression);
                return (value == match);
            }
        } catch (NumberFormatException nfe) {
            logger.warn("Unable to convert expression " + expression + " to " + propertyClass + ": "
                    + nfe.toString());
        } catch (Exception e) {
            logger.warn("Error filtering on property " + propertyName + ": " + e.toString());
        }
    } else {
        logger.warn("Expected a payload of javax.jms.Message but instead received "
                + ClassUtils.getSimpleName(message.getPayload().getClass()));
    }

    return false;
}

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

public static String formatMessage(Message message) {
    StringBuilder sb = new StringBuilder();

    try {/*  w w w .  j  a  v  a  2s  . c o m*/
        String headers = formatHeaders(message);
        if (headers.length() > 0) {
            sb.append("Message Headers:\n");
            sb.append(headers);
        }

        sb.append("Message Properties:\n");
        @SuppressWarnings("unchecked")
        Enumeration<String> propNames = message.getPropertyNames();
        while (propNames.hasMoreElements()) {
            String propertyName = propNames.nextElement();
            sb.append("  ");
            sb.append(propertyName);
            sb.append(": ");
            if (message.getObjectProperty(propertyName) != null) {
                sb.append(message.getObjectProperty(propertyName).toString());
            }
            sb.append("\n");
        }

        sb.append("Message Content:\n");
        if (message instanceof TextMessage) {
            sb.append(((TextMessage) message).getText());
        } else if (message instanceof MapMessage) {
            MapMessage mm = (MapMessage) message;
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode root = mapper.createObjectNode();

            @SuppressWarnings("unchecked")
            Enumeration<String> e = mm.getMapNames();
            while (e.hasMoreElements()) {
                String field = e.nextElement();
                root.put(field, mapper.convertValue(mm.getObject(field), JsonNode.class));
            }
            sb.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
        } else if (message instanceof BytesMessage) {
            BytesMessage bm = (BytesMessage) message;
            bm.reset();
            byte[] bytes = new byte[(int) bm.getBodyLength()];
            if (bm.readBytes(bytes) == bm.getBodyLength()) {
                sb.append(new String(bytes));
            }
        } else {
            sb.append("  Unhandled message type: " + message.getJMSType());
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unable to format message:", e);
    }

    return sb.toString();
}

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

public void onMessage(Message message) {

    String destinationName = (String) headers.get(Stomp.Headers.Subscribe.DESTINATION);
    try {//  w  w w.j  a  va2  s.c  o  m
        log.debug("Received from HQ: " + message.getJMSMessageID());
        log.debug("received: " + destinationName + " for: " + message.getObjectProperty("messagereplyto"));
    } catch (JMSException e) {
        log.warn("received: " + destinationName + " with trouble getting the message properties");
    }
    if (message != null) {
        log.debug("Locking session to send a message");
        // Lock the session so that the connection cannot be started before
        // the acknowledge is done
        synchronized (session) {
            // Send the message to the server
            log.debug("Sending message: " + session);
            try {
                session.sendToStomp(message, subscriptionId);
                try {
                    session.wait();
                } catch (InterruptedException e) {
                    log.error("Could not wait to be woken", e);
                }
                // Acknowledge the message for this connection as we know
                // the server has received it now
                try {
                    log.debug("Acking message: " + message.getJMSMessageID());
                    message.acknowledge();
                    log.debug("Acked message: " + message.getJMSMessageID());
                } catch (JMSException e) {
                    log.error("Could not acknowledge the message: " + e, e);
                }
            } catch (IOException e) {
                log.warn("Could not send to stomp: " + e, e);
                try {
                    session.recover();
                } catch (JMSException e1) {
                    log.fatal("Could not recover the session, possible lost message: " + e, e);
                }
            } catch (JMSException e) {
                log.warn("Could not convert message to send to stomp: " + e, e);
                try {
                    session.recover();
                } catch (JMSException e1) {
                    log.fatal("Could not recover the session, possible lost message: " + e, e);
                }
            }
        }
    }
}

From source file:org.springframework.flex.messaging.jms.FlexMessageConverter.java

/**
 * //from   ww w  .  ja  v  a  2  s  . co  m
 * {@inheritDoc}
 */
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
    Object messageBody = this.targetConverter.fromMessage(message);
    AsyncMessage flexMessage = new AsyncMessage();
    flexMessage.setBody(messageBody);
    flexMessage.setMessageId(message.getJMSMessageID());
    flexMessage.setClientId(message.getObjectProperty(FLEX_CLIENT_ID));
    flexMessage.setTimestamp(message.getJMSTimestamp());
    Object timeToLive = message.getObjectProperty(FLEX_TIME_TO_LIVE);
    if (timeToLive != null && long.class.isAssignableFrom(timeToLive.getClass())) {
        flexMessage.setTimeToLive(Long.parseLong(timeToLive.toString()));
    }
    Enumeration<?> propertyNames = message.getPropertyNames();
    while (propertyNames.hasMoreElements()) {
        String name = (String) propertyNames.nextElement();
        if (!name.startsWith(HEADER_PREFIX)) {
            flexMessage.setHeader(name, message.getObjectProperty(name));
        }
    }
    return flexMessage;
}

From source file:org.apache.hadoop.chukwa.datacollection.adaptor.jms.JMSMessagePropertyTransformer.java

/**
 * Transforms message propertes into a byte array delimtied by delimiter. If
 * all of the configured message properties are not found, returns null.
 * <P>//from www .  j  a  va2 s .  co  m
 * The could be enhanced to support the concept of optional/required properties.
 * @param message
 * @return
 * @throws JMSException
 */
public byte[] transform(Message message) throws JMSException {

    if (propertyNames == null || propertyNames.size() == 0) {
        log.error("No message properties configured for this JMS transformer.");
        return null;
    }

    int valuesFound = 0;
    StringBuilder sb = new StringBuilder();
    for (String propertyName : propertyNames) {
        Object propertyValue = message.getObjectProperty(propertyName);
        String value = transformValue(propertyName, propertyValue);

        // is a required value not found?
        if (value == null && (requiredPropertyNames == null || requiredPropertyNames.contains(propertyName))) {
            return null;
        }

        if (valuesFound > 0) {
            sb.append(delimiter);
        }

        if (value != null) {
            sb.append(value);
        }

        valuesFound++;
    }

    if (sb.length() == 0 || valuesFound != propertyNames.size()) {
        return null;
    }

    return sb.toString().getBytes(Charset.forName("UTF-8"));
}

From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//from   w  ww  . j ava2s.co  m
        String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
        Object objRcpt = message.getObjectProperty(RECIPIENTS);
        List<String> recipients = null;

        if (objRcpt instanceof List<?>) {
            recipients = (List<String>) objRcpt;
        } else if (objRcpt instanceof String) {
            recipients = new LinkedList<String>();
            String[] rcpts = StringUtils.split((String) objRcpt, ',');
            for (String rcpt : rcpts) {
                recipients.add(rcpt);
            }
        }

        javax.jcr.Session adminSession = repository.loginAdministrative(null);
        ResourceResolver resolver = jcrResourceResolverFactory.getResourceResolver(adminSession);

        Node messageNode = resolver.getResource(nodePath).adaptTo(Node.class);

        if (objRcpt != null) {
            // validate the message
            if (messageNode != null) {
                if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)
                        && MessageConstants.BOX_OUTBOX.equals(
                                messageNode.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX).getString())) {
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                        // We're retrying this message, so clear the errors
                        messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null);
                    }
                    if (messageNode.hasProperty(MessageConstants.PROP_SAKAI_TO)
                            && messageNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
                        // make a commons-email message from the message
                        MultiPartEmail email;
                        try {
                            email = constructMessage(messageNode, recipients);

                            email.setSmtpPort(smtpPort);
                            email.setHostName(smtpServer);

                            email.send();
                        } catch (EmailException e) {
                            setError(messageNode, e.getMessage());
                            // Get the SMTP error code
                            // There has to be a better way to do this
                            if (e.getCause() != null && e.getCause().getMessage() != null) {
                                String smtpError = e.getCause().getMessage().trim();
                                try {
                                    int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                                    // All retry-able SMTP errors should have codes starting
                                    // with 4
                                    scheduleRetry(errorCode, messageNode);
                                } catch (NumberFormatException nfe) {
                                    // smtpError didn't start with an error code, let's dig for
                                    // it
                                    String searchFor = "response:";
                                    int rindex = smtpError.indexOf(searchFor);
                                    if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) {
                                        int errorCode = Integer.parseInt(smtpError.substring(searchFor.length(),
                                                searchFor.length() + 3));
                                        scheduleRetry(errorCode, messageNode);
                                    }
                                }
                            }
                        }
                    } else {
                        setError(messageNode, "Message must have a to and from set");
                    }
                } else {
                    setError(messageNode, "Not an outbox");
                }
                if (!messageNode.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                    messageNode.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT);
                }
            }
        } else {
            String retval = "null";
            if (objRcpt != null) {
                retval = objRcpt.getClass().toString();
            }
            setError(messageNode, "Expected recipients to be String or List<String>.  Found " + retval);
        }
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    }
}