Example usage for javax.jms Message getStringProperty

List of usage examples for javax.jms Message getStringProperty

Introduction

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

Prototype


String getStringProperty(String name) throws JMSException;

Source Link

Document

Returns the value of the String property with the specified name.

Usage

From source file:org.perfcake.message.sender.JmsSenderTest.java

@Test
public void testProperties() throws Exception {

    final String payload = "Hello World with Properties!";

    final Properties props = new Properties();
    props.setProperty("messagetType", "STRING");
    props.setProperty("target", "queue/test");

    final JmsSender sender = (JmsSender) ObjectFactory.summonInstance(JmsSender.class.getName(), props);

    try {// w  w w .  ja  v  a  2s  . c o m
        sender.init();

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));

        // STRING Type
        final org.perfcake.message.Message message = new org.perfcake.message.Message();
        message.setPayload(payload);
        message.setProperty("kulek", "kulek nejmen");
        sender.preSend(message, null, null);
        sender.send(message, null);
        sender.postSend(message);

        final Message response = JmsHelper.readMessage(factory, 500, queue);
        Assert.assertTrue(response instanceof TextMessage);
        Assert.assertEquals(((TextMessage) response).getText(), payload);
        Assert.assertEquals(response.getStringProperty("kulek"), "kulek nejmen");

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));
    } finally {
        sender.close();
    }
}

From source file:org.perfcake.message.sender.JmsSenderTest.java

@Test
public void testAdditionalProperties() throws Exception {
    final String payload = "Hello World with  additional Properties!";

    final Properties props = new Properties();
    props.setProperty("messagetType", "STRING");
    props.setProperty("target", "queue/test");

    final JmsSender sender = (JmsSender) ObjectFactory.summonInstance(JmsSender.class.getName(), props);

    try {//from   w ww .j av a2 s  .c  o m
        sender.init();

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));

        // STRING Type
        final org.perfcake.message.Message message = new org.perfcake.message.Message();
        message.setPayload(payload);
        final Map<String, String> mapProps = new HashMap<>();
        mapProps.put("kulisek", "kulisek nejmensi");
        sender.preSend(message, mapProps, null);
        sender.send(message, null);
        sender.postSend(message);

        final Message response = JmsHelper.readMessage(factory, 500, queue);
        Assert.assertTrue(response instanceof TextMessage);
        Assert.assertEquals(((TextMessage) response).getText(), payload);
        Assert.assertEquals(response.getStringProperty("kulisek"), "kulisek nejmensi");

        // make sure the destination is empty
        Assert.assertNull(JmsHelper.readMessage(factory, 500, queue));
    } finally {
        sender.close();
    }
}

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

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//w  w  w.  j  a  v a 2  s.  c o  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);
    }
}

From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//  w  w  w.  j  a v  a2 s  . c om
        LOGGER.debug("Started handling email jms message.");

        String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
        String contentPath = message.getStringProperty(CONTENT_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);
            }
        }

        if (contentPath != null && contentPath.length() > 0) {
            javax.jcr.Session adminSession = repository.loginAdministrative(null);
            org.sakaiproject.nakamura.api.lite.Session sparseSession = StorageClientUtils
                    .adaptToSession(adminSession);

            try {
                ContentManager contentManager = sparseSession.getContentManager();
                Content messageContent = contentManager.get(contentPath);

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

                                    setOptions(email);
                                    if (LOGGER.isDebugEnabled()) {
                                        // build wrapped meesage in order to log it
                                        email.buildMimeMessage();
                                        logEmail(email);
                                    }
                                    email.send();
                                } catch (EmailException e) {
                                    String exMessage = e.getMessage();
                                    Throwable cause = e.getCause();

                                    setError(messageContent, exMessage);
                                    LOGGER.warn("Unable to send email: " + exMessage);

                                    // Get the SMTP error code
                                    // There has to be a better way to do this
                                    boolean rescheduled = false;
                                    if (cause != null && cause.getMessage() != null) {
                                        String smtpError = cause.getMessage().trim();
                                        try {
                                            int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                                            // All retry-able SMTP errors should have codes starting
                                            // with 4
                                            scheduleRetry(errorCode, messageContent);
                                            rescheduled = true;
                                        } 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, messageContent);
                                                rescheduled = true;
                                            } else if (!rescheduled
                                                    && cause.toString().contains("java.net.ConnectException")) {
                                                scheduleRetry(messageContent);
                                                rescheduled = true;
                                            }
                                        }
                                    }

                                    if (rescheduled) {
                                        LOGGER.info("Email {} rescheduled for redelivery. ", nodePath);
                                    } else {
                                        LOGGER.error(
                                                "Unable to reschedule email for delivery: " + e.getMessage(),
                                                e);
                                    }
                                }
                            } else {
                                setError(messageContent, "Message must have a to and from set");
                            }
                        } else {
                            setError(messageContent, "Not an outbox");
                        }
                        if (!messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                            messageContent.setProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX,
                                    MessageConstants.BOX_SENT);
                        }
                    }
                } else {
                    String retval = "null";
                    setError(messageContent,
                            "Expected recipients to be String or List<String>.  Found " + retval);
                }
            } finally {
                if (adminSession != null) {
                    adminSession.logout();
                }
            }
        }
    } catch (PathNotFoundException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (EmailDeliveryException e) {
        LOGGER.error(e.getMessage());
    } catch (ClientPoolException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (StorageClientException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

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

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {/*w w w  .j ava 2  s.c  o m*/
        LOGGER.debug("Started handling email jms message.");

        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);
        Map<String, Object> authInfo = new HashMap<String, Object>();
        authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, adminSession);
        ResourceResolver resolver = resourceResolverFactory.getResourceResolver(authInfo);

        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 = null;
                        try {
                            email = constructMessage(messageNode, recipients);

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

                            email.send();
                        } catch (EmailException e) {
                            String exMessage = e.getMessage();
                            Throwable cause = e.getCause();

                            setError(messageNode, exMessage);
                            LOGGER.warn("Unable to send email: " + exMessage);

                            // Get the SMTP error code
                            // There has to be a better way to do this
                            boolean rescheduled = false;
                            if (cause != null && cause.getMessage() != null) {
                                String smtpError = cause.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);
                                    rescheduled = true;
                                } 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);
                                        rescheduled = true;
                                    }
                                }
                            }
                            if (rescheduled) {
                                LOGGER.info("Email {} rescheduled for redelivery. ", nodePath);
                            } else {
                                LOGGER.error("Unable to reschedule email for delivery: " + e.getMessage(), e);
                            }
                        }
                    } 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";
            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);
    } catch (LoginException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (EmailDeliveryException e) {
        LOGGER.error(e.getMessage());
    }
}

From source file:org.sakaiproject.nakamura.grouper.event.SyncJMSMessageConsumer.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    log.debug("Receiving a message on {} : {}", SyncJMSMessageProducer.QUEUE_NAME, message);
    try {//from  w w  w.  ja  v a  2  s .co m

        String topic = message.getJMSType();
        String groupId = (String) message.getStringProperty("path");

        String operation = "UNKNOWN";

        // A group was DELETED
        if ("org/sakaiproject/nakamura/lite/authorizables/DELETE".equals(topic) && config.getDeletesEnabled()) {
            Map<String, Object> attributes = (Map<String, Object>) message
                    .getObjectProperty(StoreListener.BEFORE_EVENT_PROPERTY);
            grouperManager.deleteGroup(groupId, attributes);
            operation = "DELETED";
        }

        // A new group was ADDED or an existing group was UPDATED
        if ("org/sakaiproject/nakamura/lite/authorizables/ADDED".equals(topic)
                || "org/sakaiproject/nakamura/lite/authorizables/UPDATED".equals(topic)) {
            // These events should be under org/sakaiproject/nakamura/lite/authorizables/UPDATED
            // http://jira.sakaiproject.org/browse/KERN-1795
            String membersAdded = (String) message.getStringProperty(GrouperEventUtils.MEMBERS_ADDED_PROP);
            if (membersAdded != null) {
                // membership adds can be attached to the same event for the group add.
                grouperManager.createGroup(groupId, config.getGroupTypes());
                grouperManager.addMemberships(groupId, Arrays.asList(StringUtils.split(membersAdded, ",")));
                operation = "ADD_MEMBERS";
            }

            String membersRemoved = (String) message.getStringProperty(GrouperEventUtils.MEMBERS_REMOVED_PROP);
            if (membersRemoved != null) {
                grouperManager.removeMemberships(groupId,
                        Arrays.asList(StringUtils.split(membersRemoved, ",")));
                operation = "REMOVE_MEMBERS";
            }

            if (membersAdded == null && membersRemoved == null) {
                org.sakaiproject.nakamura.api.lite.Session repositorySession = repository.loginAdministrative();
                AuthorizableManager am = repositorySession.getAuthorizableManager();
                Group group = (Group) am.findAuthorizable(groupId);
                repositorySession.logout();

                if (groupId.startsWith(ContactsGrouperNameProviderImpl.CONTACTS_GROUPID_PREFIX)) {
                    // TODO Why are we not getting added and removed properties on the Message
                    grouperManager.createGroup(groupId, null);
                    grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers()));
                    operation = "UPDATE CONTACTS";
                } else {
                    grouperManager.createGroup(groupId, config.getGroupTypes());
                    grouperManager.addMemberships(groupId, Arrays.asList(group.getMembers()));
                    operation = "CREATE";
                }
            }
        }

        // The message was processed successfully. No exceptions were thrown.
        // We acknowledge the message and its removed from the queue
        message.acknowledge();

        // We got a message that we didn't know what to do with.
        if (operation.equals("UNKNOWN")) {
            log.error("I don't know what to do with this topic: {}. Turn on debug logs to see the message.",
                    topic);
            log.debug(message.toString());
        } else {
            log.info("Successfully processed and acknowledged. {}, {}", operation, groupId);
            log.debug(message.toString());
        }

    } catch (JMSException jmse) {
        log.error("JMSException while processing message.", jmse);
    } catch (Exception e) {
        log.error("Exception while processing message.", e);
    }
}

From source file:org.wso2.carbon.andes.core.internal.util.Utils.java

/**
 * Gets properties of a JMS message/* w  ww.  j a v a2s .c  o m*/
 *
 * @param message message object
 * @return String value of all the properties of the message
 * @throws JMSException
 */
public static String getMsgProperties(Message message) throws JMSException {

    Enumeration propertiesEnu = message.getPropertyNames();
    StringBuilder sb = new StringBuilder("");
    if (propertiesEnu != null) {
        while (propertiesEnu.hasMoreElements()) {
            String propName = (String) propertiesEnu.nextElement();
            sb.append(propName).append(" = ").append(message.getStringProperty(propName));
            sb.append(", ");
        }
    }

    return sb.toString();
}

From source file:org.wso2.carbon.andes.event.core.internal.delivery.jms.JMSMessageListener.java

/**
 * Fire when message receive and send notification to carbon notification manager
 *
 * @param message message/*w  w  w . j  av  a  2s.c  om*/
 */
public void onMessage(Message message) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(this.subscription.getTenantId());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.subscription.getOwner());
        PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            org.wso2.carbon.andes.event.core.Message messageToSend = new org.wso2.carbon.andes.event.core.Message();
            messageToSend.setMessage(textMessage.getText());
            // set the properties
            Enumeration propertyNames = message.getPropertyNames();
            String key = null;
            while (propertyNames.hasMoreElements()) {
                key = (String) propertyNames.nextElement();
                messageToSend.addProperty(key, message.getStringProperty(key));
            }

            this.notificationManager.sendNotification(messageToSend, this.subscription);
        } else {
            log.warn("Non text message received");
        }
    } catch (JMSException e) {
        log.error("Can not read the text message ", e);
    } catch (EventBrokerException e) {
        log.error("Can not send the notification ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}

From source file:org.wso2.carbon.andes.ui.client.QueueBrowserClient.java

/**
 * Get message details of the input javax.jms.Message object.
 * @param queueMessage javax.jms.Message (ideally fetched through the Queue Browser Enumeration)
 * @return String representation of the message
 * @throws JMSException// ww w.j a v  a  2s  .c o m
 */
public String getMsgProperties(Message queueMessage) throws JMSException {

    Enumeration propertiesEnu = queueMessage.getPropertyNames();
    StringBuilder sb = new StringBuilder("");
    if (propertiesEnu != null) {
        while (propertiesEnu.hasMoreElements()) {
            String propName = (String) propertiesEnu.nextElement();
            sb.append(propName).append(" = ").append(queueMessage.getStringProperty(propName));
            sb.append(", ");
        }
    }

    return sb.toString();
}

From source file:org.wso2.carbon.bpmn.extensions.jms.JMSUtils.java

/**
 *
 * @param message/*ww w . j a va 2  s. c  o m*/
 * @param property
 * @return
 */
public static String getMessageProperty(Message message, String property) {
    try {
        return message.getStringProperty(property);
    } catch (JMSException e) {
        return null;
    }
}