Example usage for javax.jms MapMessage getObject

List of usage examples for javax.jms MapMessage getObject

Introduction

In this page you can find the example usage for javax.jms MapMessage getObject.

Prototype


Object getObject(String name) throws JMSException;

Source Link

Document

Returns the value of the object with the specified name.

Usage

From source file:com.espertech.esperio.regression.adapter.SupportJMSReceiver.java

public static void print(Message msg) throws JMSException {
    log.info(".print received message: " + msg.getJMSMessageID());
    if (msg instanceof ObjectMessage) {
        ObjectMessage objMsg = (ObjectMessage) msg;
        log.info(".print object: " + objMsg.getObject().toString());
    } else {//from w w w.j  a  va  2s.c o m
        MapMessage mapMsg = (MapMessage) msg;
        HashMap map = new HashMap();
        Enumeration en = mapMsg.getMapNames();
        while (en.hasMoreElements()) {
            String property = (String) en.nextElement();
            Object mapObject = mapMsg.getObject(property);
            map.put(property, mapObject);
        }
        log.info(".print map: " + map);
    }
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

public static Object getObjectForMessage(Message source) throws JMSException {
    Object result = null;/*from  ww  w.j a  v a 2 s.c  o m*/
    try {
        if (source instanceof ObjectMessage) {
            result = ((ObjectMessage) source).getObject();
        } else if (source instanceof MapMessage) {
            Hashtable map = new Hashtable();
            MapMessage m = (MapMessage) source;

            for (Enumeration e = m.getMapNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Object obj = m.getObject(name);
                map.put(name, obj);
            }

            result = map;
        } else if (source instanceof javax.jms.BytesMessage) {

            javax.jms.BytesMessage bm = (javax.jms.BytesMessage) source;
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

            byte[] buffer = new byte[1024 * 4];
            int len = 0;
            bm.reset();
            while ((len = bm.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            result = baos.toByteArray();
            baos.close();
            if (result != null) {
                if (logger.isDebugEnabled())
                    logger.debug("JMSToObject: extracted " + ((byte[]) result).length
                            + " bytes from JMS BytesMessage");
            }
        } else if (source instanceof TextMessage) {
            result = ((TextMessage) source).getText();

        } else if (source instanceof BytesMessage) {
            byte[] bytes = getBytesFromMessage(source);
            return CompressionHelper.uncompressByteArray(bytes);
        } else if (source instanceof StreamMessage) {

            StreamMessage sm = (javax.jms.StreamMessage) source;

            result = new java.util.Vector();
            try {
                Object obj = null;
                while ((obj = sm.readObject()) != null) {
                    ((java.util.Vector) result).addElement(obj);
                }
            } catch (MessageEOFException eof) {
            } catch (Exception e) {
                throw new JMSException("Failed to extract information from JMS Stream Message: " + e);
            }
        } else {
            result = source;
        }
    } catch (Exception e) {
        throw new JMSException("Failed to transform message: " + e.getMessage());
    }
    return result;
}

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

public static String getMessageBody(Message message) {
    try {/*from  ww w  . j a v a 2 s  .  c  om*/
        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.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class));
            }
            return mapper.writer().writeValueAsString(root);
        } else if (message instanceof TextMessage) {
            TextMessage tm = (TextMessage) message;
            return tm.getText();
        } else if (message instanceof BytesMessage) {
            BytesMessage bm = (BytesMessage) message;
            byte[] bytes = new byte[(int) bm.getBodyLength()];
            if (bm.readBytes(bytes) == bm.getBodyLength()) {
                return new String(bytes);
            }
        } else {
            log.log(Level.SEVERE, "Unsupported message type:\n" + formatMessage(message));
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception retrieving message body:\n" + formatMessage(message), e);
    }

    return "";
}

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

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

    try {/*w  ww .  j a v  a 2  s .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:com.espertech.esperio.jms.JMSDefaultAnyMessageUnmarshaller.java

public EventBean unmarshal(EventAdapterService eventAdapterService, Message message) throws EPException {
    try {//from   w w  w.ja v  a 2  s  . c  om
        if (message instanceof ObjectMessage) {
            ObjectMessage objmsg = (ObjectMessage) message;
            Serializable obj = objmsg.getObject();
            return eventAdapterService.adapterForBean(obj);
        } else if (message instanceof MapMessage) {
            Map<String, Object> properties = new HashMap<String, Object>();
            MapMessage mapMsg = (MapMessage) message;
            Enumeration en = mapMsg.getMapNames();
            while (en.hasMoreElements()) {
                String property = (String) en.nextElement();
                Object mapObject = mapMsg.getObject(property);
                properties.put(property, mapObject);
            }

            // Get event type property
            Object typeProperty = properties.get(InputAdapter.ESPERIO_MAP_EVENT_TYPE);
            if (typeProperty == null) {
                log.warn(".unmarshal Failed to unmarshal map message, expected type property not found: '"
                        + InputAdapter.ESPERIO_MAP_EVENT_TYPE + "'");
                return null;
            }

            // Get event type
            String name = typeProperty.toString();
            EventType eventType = eventAdapterService.getExistsTypeByName(name);
            if (eventType == null) {
                log.warn(".unmarshal Failed to unmarshal map message, event type name '" + name
                        + "' is not a known type");
                return null;
            }

            return eventAdapterService.adapterForTypedMap(properties, eventType);
        } else {
            String error = ".unmarshal Failed to unmarshal message of JMS type: " + message.getJMSType();
            log.error(error);
            throw new EPException(error);
        }
    } catch (JMSException ex) {
        throw new EPException("Error unmarshalling message", ex);
    }
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityJMSMessageParser.java

/**
 * Parse JMS {@link MapMessage} activity info into activity data map.
 *
 * @param mapMessage/* w  ww  . j ava 2  s .  co  m*/
 *            JMS map message
 * @param dataMap
 *            activity data map collected from JMS {@link MapMessage}
 * @throws JMSException
 *             if JMS exception occurs while getting map entries from message.
 */
@SuppressWarnings("unchecked")
protected void parseMapMessage(MapMessage mapMessage, Map<String, Object> dataMap) throws JMSException {
    Enumeration<String> en = (Enumeration<String>) mapMessage.getMapNames();
    while (en.hasMoreElements()) {
        String key = en.nextElement();
        dataMap.put(key, mapMessage.getObject(key));
    }
}

From source file:hermes.ext.imq.ImqAdmin.java

@Override
public void onMessage(Message msg) {

    try {/*from  w  w w.  ja va 2s .  c  o m*/

        MapMessage mapMsg = (MapMessage) msg;
        String type = mapMsg.getStringProperty("type");

        LOG.debug("Got admin message from broker of type: " + type);

        if (type.equals(DEST_LIST_TOPIC_NAME)) {
            List<DestinationConfig> result = new ArrayList<DestinationConfig>();

            for (@SuppressWarnings("unchecked")
            Enumeration e = mapMsg.getMapNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();

                @SuppressWarnings("unchecked")
                Map<String, String> object = (Map<String, String>) mapMsg.getObject(name);

                DestinationConfig dest = HermesBrowser.getConfigDAO().createDestinationConfig();
                dest.setName(object.get("name"));
                dest.setShortName(object.get("name"));
                dest.setDomain("queue".equals(object.get("type")) ? Domain.QUEUE.getId()
                        : ("topic".equals(object.get("type")) ? Domain.TOPIC.getId() : Domain.UNKNOWN.getId()));

                result.add(dest);
            }

            Collections.sort(result, new Comparator<DestinationConfig>() {
                @Override
                public int compare(DestinationConfig o1, DestinationConfig o2) {
                    return o1.getShortName().compareTo(o2.getShortName());
                }
            });

            destinations = result;

            synchronized (destListGuard) {
                destListGuard.notifyAll();
            }

        } else if (type.startsWith(QUEUE_METRICS_TOPIC_PREFIX)) {
            LOG.debug("Got queue metrics: " + type);

            String queueName = type.substring(QUEUE_METRICS_TOPIC_PREFIX.length());
            messageCounts.put(queueName, mapMsg.getLong("numMsgs"));
            HashMap<String, Long> map = new HashMap<String, Long>();

            @SuppressWarnings("unchecked")
            Enumeration<String> e = mapMsg.getMapNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                map.put(name, mapMsg.getLong(name));
            }
            stats.put(queueName, map);
            LOG.debug("Stored stats for: " + queueName);

            synchronized (destMetricGuard) {
                destMetricGuard.notifyAll();
            }

        } else if (type.startsWith(TOPIC_METRICS_TOPIC_PREFIX)) {
            LOG.debug("Got topic metrics: " + type);

            String topicName = type.substring(TOPIC_METRICS_TOPIC_PREFIX.length());
            messageCounts.put(topicName, mapMsg.getLong("numMsgs"));

            HashMap<String, Long> map = new HashMap<String, Long>();

            @SuppressWarnings("unchecked")
            Enumeration<String> e = mapMsg.getMapNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                map.put(name, mapMsg.getLong(name));
            }
            stats.put(topicName, map);
            LOG.debug("Stored stats for: " + topicName);

            synchronized (destMetricGuard) {
                destMetricGuard.notifyAll();
            }
        }

    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {//from  w w  w.  j  av  a 2 s.c o  m
        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:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

private boolean verify(Message message, MsgCheck check) {
    String sVal = "";

    if (check.getField().equals(MESSAGECONTENTFIELD)) {
        try {/*w ww. j a v a 2 s. c o  m*/
            if (message instanceof TextMessage) {
                sVal = ((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.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class));
                }
                sVal = 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()) {
                    sVal = new String(bytes);
                }
            }
        } catch (JMSException e) {
            return false;
        } catch (JsonProcessingException e) {
            return false;
        }
    } else {
        Enumeration<String> propNames = null;
        try {
            propNames = message.getPropertyNames();
            while (propNames.hasMoreElements()) {
                String propertyName = propNames.nextElement();
                if (propertyName.equals(check.getField())) {
                    if (message.getObjectProperty(propertyName) != null) {
                        sVal = message.getObjectProperty(propertyName).toString();
                        break;
                    }
                }
            }
        } catch (JMSException e) {
            return false;
        }
    }

    String eVal = "";
    if (check.getExpectedValue() != null) {
        eVal = check.getExpectedValue();
    }
    if (Pattern.compile(eVal).matcher(sVal).find()) {
        return true;
    }
    return false;
}

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

/**
 * Extracts a {@link Map} from a {@link MapMessage}
 *///from  w  w w . ja  v  a 2s. c  o m
public Map<String, Object> createMapFromMapMessage(MapMessage message) throws JMSException {
    Map<String, Object> answer = new HashMap<String, Object>();
    Enumeration names = message.getMapNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement().toString();
        Object value = message.getObject(name);
        answer.put(name, value);
    }
    return answer;
}