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.apache.camel.component.jms.JmsBinding.java

public Object getObjectProperty(Message jmsMessage, String name) throws JMSException {
    // try a direct lookup first
    Object answer = jmsMessage.getObjectProperty(name);
    if (answer == null) {
        // then encode the key and do another lookup
        String key = jmsKeyFormatStrategy.encodeKey(name);
        answer = jmsMessage.getObjectProperty(key);
    }//w w w  . ja va 2s.c o  m
    return answer;
}

From source file:org.openadaptor.auxil.connector.jms.JMSReadConnector.java

/**
 * Copy any JMS Message Properties into the metadata.
 * //  w  w w .ja  va2s  .c  o  m
 * @param msg
 * @throws JMSException
 */
protected void readMetadataFromMessageProperties(Message msg) throws JMSException {
    Map addToMetadata = new HashMap();

    Enumeration names = msg.getPropertyNames();
    while (names.hasMoreElements()) {
        String nextName = (String) names.nextElement();
        addToMetadata.put(nextName, msg.getObjectProperty(nextName));
    }
    metadata.putAll(addToMetadata);
}

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 .  j a  va  2  s .c  o 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.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//from   w  w w .  jav  a2s.  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:com.fusesource.forge.jmstest.tests.AsyncConsumer.java

public void onMessage(Message msg) {
    if (receiveCount != null) {
        receiveCount.incrementAndGet();//from w  ww  .ja  va  2 s. c  o m
    }
    MessageProducer producer = null;
    try {
        Destination replyDest = msg.getJMSReplyTo();
        if (replyDest != null) {
            Message response = getSession().createTextMessage("Response");
            response.setStringProperty("ServedBy", getName());
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            for (Enumeration<?> en = msg.getPropertyNames(); en.hasMoreElements();) {
                String key = (String) en.nextElement();
                Object value = msg.getObjectProperty(key);
                if (key.equals("BrokerStamp")) {
                    value = value.toString() + " --";
                }
                response.setObjectProperty(key, value);
            }
            producer = getSession().createProducer(replyDest);
            producer.send(response);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.jwebsocket.jms.endpoint.JMSEndPointSender.java

/**
 *
 * @param aTargetId// w  ww  . j  ava 2s .  c  om
 * @param aCorrelationID
 * @param aText
 * @param aResponseListener
 * @param aTimeout
 */
public synchronized void sendText(String aTargetId, final String aCorrelationID, final String aText,
        IJMSResponseListener aResponseListener, long aTimeout) {
    Message lMsg;
    try {
        lMsg = mSession.createTextMessage(aText);
        if (null != aCorrelationID) {
            lMsg.setJMSCorrelationID(aCorrelationID);
        }
        lMsg.setStringProperty("targetId", aTargetId);
        lMsg.setStringProperty("sourceId", mEndPointId);

        if (mLog.isDebugEnabled()) {
            StringBuilder lPropStr = new StringBuilder();
            Enumeration lPropNames = lMsg.getPropertyNames();
            while (lPropNames.hasMoreElements()) {
                String lPropName = (String) lPropNames.nextElement();
                Object lValue = lMsg.getObjectProperty(lPropName);
                lPropStr.append(lPropName).append("=").append(lValue);
                if (lPropNames.hasMoreElements()) {
                    lPropStr.append(", ");
                }
            }
            mLog.debug("Sending text to '" + aTargetId + "': "
                    + (JMSLogging.isFullTextLogging() ? aText
                            : "[content suppressed, length: " + aText.length() + " bytes]")
                    + ", props: " + lPropStr + "...");
        }

        // processing callbacks
        if (null != aResponseListener) {
            Assert.notNull(aCorrelationID, "The 'correlationID' argument cannot be null!");
            Assert.isTrue(aTimeout > 0, "Invalid 'timeout' argument. Expecting 'timeout' > 0");
            // setting the expiration time
            lMsg.setJMSExpiration(aTimeout);

            // saving the callback 
            mResponseListeners.put(aCorrelationID, aResponseListener);

            // schedule the timer task
            Tools.getTimer().schedule(new JWSTimerTask() {
                @Override
                public void runTask() {
                    Thread lThread = new Thread() {
                        @Override
                        public void run() {
                            IJMSResponseListener lListener = mResponseListeners.remove(aCorrelationID);
                            if (null != lListener) {
                                lListener.onTimeout();
                            }
                        }
                    };
                    lThread.setName("JMSEndPointSender Timeout Thread");
                    Tools.getThreadPool().submit(lThread);
                }
            }, aTimeout);
        }

        mProducer.send(lMsg);

    } catch (JMSException lEx) {
        mLog.error(lEx.getClass().getSimpleName() + " sending message: " + lEx.getMessage() + " "
                + ExceptionUtils.getStackTrace(lEx));
    }
}

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

@SuppressWarnings("unchecked")
public void onMessage(Message message) {
    try {//from  w ww .j  av a2  s. c o  m
        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:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

private void process(String jobname, Message message) {
    try {/*from   w  w  w  .ja v  a2  s. co m*/
        Map<String, String> params = new HashMap<String, String>();
        params.put("CI_MESSAGE", getMessageBody(message));

        @SuppressWarnings("unchecked")
        Enumeration<String> e = message.getPropertyNames();
        while (e.hasMoreElements()) {
            String s = e.nextElement();
            if (message.getStringProperty(s) != null) {
                params.put(s, message.getObjectProperty(s).toString());
            }
        }
        super.trigger(jobname, formatMessage(message), params);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception processing message:\n" + formatMessage(message), e);
    }
}

From source file:org.mitre.mpf.markup.MarkupRequestConsumer.java

public void onMessage(Message message) {
    Stopwatch stopwatch = Stopwatch.createStarted();

    if (message == null) {
        log.warn("Received a null JMS message. No action will be taken.");
        return;/* w ww. ja v  a 2 s.co m*/
    }

    if (!(message instanceof BytesMessage)) {
        log.warn("Received a JMS message, but it was not of the correct type. No action will be taken.");
        return;
    }

    try {
        log.info("Received JMS message. Type = {}. JMS Message ID = {}. JMS Correlation ID = {}.",
                message.getClass().getName(), message.getJMSMessageID(), message.getJMSCorrelationID());

        final Map<String, Object> requestHeaders = new HashMap<String, Object>();
        Enumeration<String> properties = message.getPropertyNames();

        String propertyName = null;
        while (properties.hasMoreElements()) {
            propertyName = properties.nextElement();
            requestHeaders.put(propertyName, message.getObjectProperty(propertyName));
        }

        byte[] messageBytes = new byte[(int) (((BytesMessage) message).getBodyLength())];
        ((BytesMessage) message).readBytes(messageBytes);
        Markup.MarkupRequest markupRequest = Markup.MarkupRequest.parseFrom(messageBytes);
        Markup.MarkupResponse.Builder markupResponseBuilder = initializeResponse(markupRequest);
        markupResponseBuilder.setRequestTimestamp(message.getJMSTimestamp());

        log.debug("Processing markup request. Media Index = {}. Media ID = {} (type = {}). Request ID = {}.",
                markupRequest.getMediaIndex(), markupRequest.getMediaId(), markupRequest.getMediaType(),
                markupRequest.getRequestId());

        try {
            if (!new File(URI.create(markupRequest.getDestinationUri())).canWrite()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The target URI '%s' is not writable.", markupRequest.getDestinationUri()));
        }

        try {
            if (!new File(URI.create(markupRequest.getSourceUri())).canRead()) {
                throw new Exception();
            }
        } catch (Exception exception) {
            markupResponseBuilder.setHasError(true);
            markupResponseBuilder.setErrorMessage(
                    String.format("The source URI '%s' is not readable.", markupRequest.getSourceUri()));
        }

        if (!markupResponseBuilder.getHasError()) {
            if (markupRequest.getMapEntriesCount() == 0) {
                try {
                    FileUtils.copyFile(new File(URI.create(markupRequest.getSourceUri())),
                            new File(URI.create(markupRequest.getDestinationUri())));
                    markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                } catch (Exception exception) {
                    log.error("Failed to mark up the file '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else if (markupRequest.getMediaType() == Markup.MediaType.IMAGE) {
                try {
                    if (markupImage(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getSourceUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the image '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            } else {
                try {
                    if (markupVideo(markupRequest)) {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    } else {
                        markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri());
                    }
                } catch (Exception exception) {
                    log.error("Failed to mark up the video '{}' because of an exception.",
                            markupRequest.getSourceUri(), exception);
                    finishWithError(markupResponseBuilder, exception);
                }
            }
        }

        stopwatch.stop();
        markupResponseBuilder.setTimeProcessing(stopwatch.elapsed(TimeUnit.MILLISECONDS));
        final Markup.MarkupResponse markupResponse = markupResponseBuilder.build();

        log.info("Returning response for Media {}. Error: {}.", markupResponse.getMediaId(),
                markupResponse.getHasError());
        markupResponseTemplate.setSessionTransacted(true);
        markupResponseTemplate.setDefaultDestination(message.getJMSReplyTo());
        markupResponseTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(markupResponse.toByteArray());
                for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) {
                    bytesMessage.setObjectProperty(entry.getKey(), entry.getValue());
                }
                return bytesMessage;
            }
        });

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java

private String getQueueMessage(Session jSession, TibjmsAdmin admin, String queueName, int queueItem,
        LdapSender ldapSender) throws TibjmsAdminException, JMSException {
    QueueInfo qInfo = admin.getQueue(queueName);
    if (qInfo == null) {
        throw new JMSException(" queue [" + queueName + "] does not exist");
    }//from   ww  w .  j  a v a  2 s . c  om

    XmlBuilder qMessageXml = new XmlBuilder("qMessage");
    ServerInfo serverInfo = admin.getInfo();
    String url = serverInfo.getURL();
    qMessageXml.addAttribute("url", url);
    String resolvedUrl = getResolvedUrl(url);
    if (resolvedUrl != null) {
        qMessageXml.addAttribute("resolvedUrl", resolvedUrl);
    }
    qMessageXml.addAttribute("timestamp", DateUtils.getIsoTimeStamp());
    qMessageXml.addAttribute("startTime", DateUtils.format(serverInfo.getStartTime(), DateUtils.fullIsoFormat));
    XmlBuilder qNameXml = new XmlBuilder("qName");
    qNameXml.setCdataValue(queueName);

    Queue queue = jSession.createQueue(queueName);
    QueueBrowser queueBrowser = null;
    try {
        queueBrowser = jSession.createBrowser(queue);
        Enumeration enm = queueBrowser.getEnumeration();
        int count = 0;
        boolean found = false;
        String chompCharSizeString = AppConstants.getInstance().getString("browseQueue.chompCharSize", null);
        int chompCharSize = (int) Misc.toFileSize(chompCharSizeString, -1);

        while (enm.hasMoreElements() && !found) {
            count++;
            if (count == queueItem) {
                qNameXml.addAttribute("item", count);
                Object o = enm.nextElement();
                if (o instanceof Message) {
                    Message msg = (Message) o;
                    XmlBuilder qMessageId = new XmlBuilder("qMessageId");
                    qMessageId.setCdataValue(msg.getJMSMessageID());
                    qMessageXml.addSubElement(qMessageId);
                    XmlBuilder qTimestamp = new XmlBuilder("qTimestamp");
                    qTimestamp.setCdataValue(DateUtils.format(msg.getJMSTimestamp(), DateUtils.fullIsoFormat));
                    qMessageXml.addSubElement(qTimestamp);

                    StringBuffer sb = new StringBuffer("");
                    Enumeration propertyNames = msg.getPropertyNames();
                    while (propertyNames.hasMoreElements()) {
                        String propertyName = (String) propertyNames.nextElement();
                        Object object = msg.getObjectProperty(propertyName);
                        if (sb.length() > 0) {
                            sb.append("; ");
                        }
                        sb.append(propertyName);
                        sb.append("=");
                        sb.append(object);
                    }
                    XmlBuilder qPropsXml = new XmlBuilder("qProps");
                    qPropsXml.setCdataValue(sb.toString());

                    qMessageXml.addSubElement(qPropsXml);
                    XmlBuilder qTextXml = new XmlBuilder("qText");
                    String msgText;
                    try {
                        TextMessage textMessage = (TextMessage) msg;
                        msgText = textMessage.getText();
                    } catch (ClassCastException e) {
                        msgText = msg.toString();
                        qTextXml.addAttribute("text", false);
                    }
                    int msgSize = msgText.length();
                    if (isHideMessage()) {
                        qTextXml.setCdataValue("***HIDDEN***");
                    } else {
                        if (chompCharSize >= 0 && msgSize > chompCharSize) {
                            qTextXml.setCdataValue(msgText.substring(0, chompCharSize) + "...");
                            qTextXml.addAttribute("chomped", true);
                        } else {
                            qTextXml.setCdataValue(msgText);
                        }
                    }
                    qMessageXml.addSubElement(qTextXml);
                    XmlBuilder qTextSizeXml = new XmlBuilder("qTextSize");
                    qTextSizeXml.setValue(Misc.toFileSize(msgSize));
                    qMessageXml.addSubElement(qTextSizeXml);
                }
                found = true;
            } else {
                enm.nextElement();
            }
        }
    } finally {
        if (queueBrowser != null) {
            try {
                queueBrowser.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix(null) + "exception on closing queue browser", e);
            }
        }
    }

    qMessageXml.addSubElement(qNameXml);

    Map aclMap = getAclMap(admin, ldapSender);
    XmlBuilder aclXml = new XmlBuilder("acl");
    XmlBuilder qInfoXml = qInfoToXml(qInfo);
    aclXml.setValue((String) aclMap.get(qInfo.getName()));
    qInfoXml.addSubElement(aclXml);
    qMessageXml.addSubElement(qInfoXml);

    Map consumersMap = getConnectedConsumersMap(admin);
    XmlBuilder consumerXml = new XmlBuilder("connectedConsumers");
    if (consumersMap.containsKey(qInfo.getName())) {
        LinkedList<String> consumers = (LinkedList<String>) consumersMap.get(qInfo.getName());
        String consumersString = listToString(consumers);
        if (consumersString != null) {
            consumerXml.setCdataValue(consumersString);
        }
    }
    qInfoXml.addSubElement(consumerXml);

    return qMessageXml.toXML();
}