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:org.apache.jmeter.protocol.jms.sampler.SubscriberSampler.java

private void extractContent(StringBuilder buffer, StringBuilder propBuffer, Message msg, boolean isLast) {
    if (msg != null) {
        try {/*  w  w w .ja va 2s .  c  o m*/
            if (msg instanceof TextMessage) {
                buffer.append(((TextMessage) msg).getText());
            } else if (msg instanceof ObjectMessage) {
                ObjectMessage objectMessage = (ObjectMessage) msg;
                if (objectMessage.getObject() != null) {
                    buffer.append(objectMessage.getObject().getClass());
                } else {
                    buffer.append("object is null");
                }
            } else if (msg instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) msg;
                buffer.append(bytesMessage.getBodyLength() + " bytes received in BytesMessage");
            } else if (msg instanceof MapMessage) {
                MapMessage mapm = (MapMessage) msg;
                @SuppressWarnings("unchecked") // MapNames are Strings
                Enumeration<String> enumb = mapm.getMapNames();
                while (enumb.hasMoreElements()) {
                    String name = enumb.nextElement();
                    Object obj = mapm.getObject(name);
                    buffer.append(name);
                    buffer.append(",");
                    buffer.append(obj.getClass().getCanonicalName());
                    buffer.append(",");
                    buffer.append(obj);
                    buffer.append("\n");
                }
            }
            Utils.messageProperties(propBuffer, msg);
            if (!isLast && !StringUtils.isEmpty(separator)) {
                propBuffer.append(separator);
                buffer.append(separator);
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }
    }
}

From source file:org.gss_project.gss.server.ejb.indexer.IndexerMDBean.java

/**
 * Decides to add or drop an item from the index depending on the message
 * received//from  www .  j ava 2  s.  co  m
 *
 * It currently uses the patched solr API for rich documents. This API does not
 * allow indexing time field boosting. For this reason we have to use the dismax search API (instead of the
 * standard) that allows for search time field boosting
 *
 * @param msg
 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
 */
@Override
public void onMessage(Message msg) {
    Long id = null;
    try {
        MapMessage map = (MapMessage) msg;
        id = (Long) map.getObject("id");
        boolean delete = map.getBoolean("delete");
        if (delete) {
            CommonsHttpSolrServer solr = new CommonsHttpSolrServer(getConfiguration().getString("solr.url"));
            sendDelete(solr, id);
            solr.commit();
        } else {
            service.postFileToSolr(id);
        }
    } catch (JMSException e) {
        throw new EJBException("Error processing file ID " + id, e);
    } catch (IOException e) {
        throw new EJBException("Error processing file ID " + id, e);
    } catch (SolrServerException e) {
        throw new EJBException(e);
    } catch (ObjectNotFoundException e) {
        throw new EJBException(e);
    }
}

From source file:org.mule.transport.jms.JmsMessageUtils.java

public static Object toObject(Message source, String jmsSpec, String encoding)
        throws JMSException, IOException {
    if (source instanceof ObjectMessage) {
        return ((ObjectMessage) source).getObject();
    } else if (source instanceof MapMessage) {
        Map<String, Object> map = new HashMap<String, Object>();
        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);/*from   w ww . j a  v  a2s . co  m*/
        }

        return map;
    } else if (source instanceof TextMessage) {
        return ((TextMessage) source).getText();
    } else if (source instanceof BytesMessage) {
        return toByteArray(source, jmsSpec, encoding);
    } else if (source instanceof StreamMessage) {
        List<Object> result = new ArrayList<Object>();
        try {
            StreamMessage sMsg = (StreamMessage) source;
            Object obj;
            while ((obj = sMsg.readObject()) != null) {
                result.add(obj);
            }
        } catch (MessageEOFException eof) {
            // ignored
        } catch (Exception e) {
            throw new JMSException("Failed to extract information from JMS Stream Message: " + e);
        }
        return result;
    }

    // what else is there to do?
    return source;
}

From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java

@Test
public void testMapMessageWithNullValue() throws Exception {
    String[] keys = new String[] { "key", "null" };
    Iterator<String> keyIterator = IteratorUtils.arrayIterator(keys);
    Enumeration<String> keyEnumeration = new IteratorEnumeration(keyIterator);

    MapMessage mockMessage1 = mock(MapMessage.class);
    when(mockMessage1.getMapNames()).thenReturn(keyEnumeration);
    when(mockMessage1.getObject("key")).thenReturn("value");
    when(mockMessage1.getObject("null")).thenReturn(null);

    Object result = JmsMessageUtils.toObject(mockMessage1, JmsConstants.JMS_SPECIFICATION_11, ENCODING);
    assertNotNull(result);// www  .  j  a va  2s .  co m
    assertTrue(result instanceof Map);
    Map map = (Map) result;
    assertEquals("value", map.get("key"));
    assertNull(map.get("null"));
}

From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java

/**
 * Tests that is able to convert a Map which only contains simple values into a
 * MapMessage.//from   ww w . j av a 2  s  .  c o m
 */
@Test
public void testConvertsValidMapWithSimpleValuesToMapMessage() throws JMSException {
    Session session = mock(Session.class);
    when(session.createMapMessage()).thenReturn(new ActiveMQMapMessage());

    // Creates a test Map with data
    Map data = new HashMap();
    data.put("value1", new Float(4));
    data.put("value2", new byte[] { 1, 2, 3 });
    data.put("value3", "value3");
    data.put("value4", new Double(67.9));
    data.put("value5", true);
    data.put("value6", null);

    Message message = JmsMessageUtils.toMessage(data, session);
    assertTrue(message instanceof MapMessage);

    MapMessage mapMessage = (MapMessage) message;
    assertEquals(new Float(4), mapMessage.getFloat("value1"), 0);
    assertTrue(Arrays.equals(new byte[] { 1, 2, 3 }, mapMessage.getBytes("value2")));
    assertEquals("value3", mapMessage.getString("value3"));
    assertEquals(new Double(67.9), mapMessage.getDouble("value4"), 0);
    assertTrue(mapMessage.getBoolean("value5"));
    assertNull(mapMessage.getObject("value6"));
}

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

/**
 * Gets the message content as a string, after verifying its type
 *
 * @param message - JMS Message/*  ww  w . ja  v  a2 s  . c  o m*/
 * @return a string array of message content; a summary and the whole message
 * @throws JMSException
 */
public static String[] getMessageContentAsString(Message message) throws JMSException {

    String messageContent[] = new String[2];
    String summaryMsg = "";
    String wholeMsg = "";

    StringBuilder sb = new StringBuilder();
    if (message != null) {
        if (message instanceof TextMessage) {
            String textMessage = ((TextMessage) message).getText();
            if (StringUtils.isNotEmpty(textMessage)) {
                wholeMsg = StringEscapeUtils.escapeHtml(textMessage).trim();
                if (wholeMsg.length() >= CHARACTERS_TO_SHOW) {
                    summaryMsg = wholeMsg.substring(0, CHARACTERS_TO_SHOW);
                } else {
                    summaryMsg = wholeMsg;
                }
                if (wholeMsg.length() > MESSAGE_DISPLAY_LENGTH_MAX) {
                    wholeMsg = wholeMsg.substring(0, MESSAGE_DISPLAY_LENGTH_MAX - 3) + DISPLAY_CONTINUATION
                            + DISPLAY_LENGTH_EXCEEDED;
                }
            }
        } else if (message instanceof ObjectMessage) {
            wholeMsg = "This Operation is Not Supported!";
            summaryMsg = "Not Supported";

        } else if (message instanceof MapMessage) {
            MapMessage mapMessage = ((MapMessage) message);
            Enumeration mapEnu = mapMessage.getMapNames();
            while (mapEnu.hasMoreElements()) {
                String mapName = (String) mapEnu.nextElement();
                String mapVal = mapMessage.getObject(mapName).toString();
                wholeMsg = StringEscapeUtils
                        .escapeHtml(sb.append(mapName).append(": ").append(mapVal).append(", ").toString())
                        .trim();

            }
            if (wholeMsg.length() >= CHARACTERS_TO_SHOW) {
                summaryMsg = wholeMsg.substring(0, CHARACTERS_TO_SHOW);
            } else {
                summaryMsg = wholeMsg;
            }

        } else if (message instanceof StreamMessage) {
            ((StreamMessage) message).reset();
            wholeMsg = getContentFromStreamMessage((StreamMessage) message, sb).trim();
            if (wholeMsg.length() >= CHARACTERS_TO_SHOW) {
                summaryMsg = wholeMsg.substring(0, CHARACTERS_TO_SHOW);
            } else {
                summaryMsg = wholeMsg;
            }

        } else if (message instanceof BytesMessage) {
            ((BytesMessage) message).reset();
            long messageLength = ((BytesMessage) message).getBodyLength();
            byte[] byteMsgArr = new byte[(int) messageLength];

            int index = ((BytesMessage) message).readBytes(byteMsgArr);
            for (int i = 0; i < index; i++) {
                wholeMsg = sb.append(byteMsgArr[i]).append(" ").toString().trim();
            }

            if (wholeMsg.length() >= CHARACTERS_TO_SHOW) {
                summaryMsg = wholeMsg.substring(0, CHARACTERS_TO_SHOW);
            } else {
                summaryMsg = wholeMsg;
            }
        }
    }
    messageContent[0] = summaryMsg;
    messageContent[1] = wholeMsg;
    return messageContent;
}

From source file:org.wso2.carbon.apimgt.jms.listener.utils.JMSMessageListener.java

public void onMessage(Message message) {
    try {/*from w  w w. ja va 2s  .  c  om*/
        if (message != null) {
            if (log.isDebugEnabled()) {
                log.debug("Event received in JMS Event Receiver - " + message);
            }

            if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                Map<String, Object> map = new HashMap<String, Object>();
                Enumeration enumeration = mapMessage.getMapNames();
                while (enumeration.hasMoreElements()) {
                    String key = (String) enumeration.nextElement();
                    map.put(key, mapMessage.getObject(key));
                }

                if (map.get(APIConstants.THROTTLE_KEY) != null) {
                    /**
                     * This message contains throttle data in map which contains Keys
                     * throttleKey - Key of particular throttling level
                     * isThrottled - Whether message has throttled or not
                     * expiryTimeStamp - When the throttling time window will expires
                     */
                    handleThrottleUpdateMessage(map);
                } else if (map.get(APIConstants.BLOCKING_CONDITION_KEY) != null) {
                    /**
                     * This message contains blocking condition data
                     * blockingCondition - Blocking condition type
                     * conditionValue - blocking condition value
                     * state - State whether blocking condition is enabled or not
                     */
                    handleBlockingMessage(map);
                } else if (map.get(APIConstants.POLICY_TEMPLATE_KEY) != null) {
                    /**
                     * This message contains key template data
                     * keyTemplateValue - Value of key template
                     * keyTemplateState - whether key template active or not
                     */
                    handleKeyTemplateMessage(map);
                }

            } else {
                log.warn("Event dropped due to unsupported message type " + message.getClass());
            }
        } else {
            log.warn("Dropping the empty/null event received through jms receiver");
        }
    } catch (JMSException e) {
        log.error("JMSException occurred when processing the received message ", e);
    }
}

From source file:org.wso2.carbon.event.input.adapter.jms.internal.util.JMSMessageListener.java

public void onMessage(Message message) {
    try {//from ww  w . java  2s.c  o m
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        if (message != null) {

            if (log.isDebugEnabled()) {
                log.debug("Event received in JMS Event Adaptor - " + message);
            }

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                // Send the text of the message. Conversion to any type (XML,JSON) should
                // not happen here since this message will be built later.
                try {
                    String msgText = textMessage.getText();
                    eventAdaptorListener.onEvent(msgText);
                } catch (JMSException e) {
                    if (log.isErrorEnabled()) {
                        log.error("Failed to get text from " + textMessage, e);
                    }
                } catch (InputEventAdapterRuntimeException e) {
                    if (log.isErrorEnabled()) {
                        log.error(e);
                    }
                }
            } else if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                Map event = new HashMap();
                try {
                    Enumeration names = mapMessage.getMapNames();
                    Object name;
                    while (names.hasMoreElements()) {
                        name = names.nextElement();
                        event.put(name, mapMessage.getObject((String) name));
                    }
                    eventAdaptorListener.onEvent(event);

                } catch (JMSException e) {
                    log.error("Can not read the map message ", e);
                } catch (InputEventAdapterRuntimeException e) {
                    log.error("Can not send the message to broker ", e);
                }
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes;
                bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                eventAdaptorListener.onEvent(new String(bytes, "UTF-8"));
            } else {
                log.warn("Event dropped due to unsupported message type");
            }
        } else {
            log.warn("Dropping the empty/null event received through jms adaptor");
        }
    } catch (JMSException e) {
        log.error(e);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (Throwable t) {
        log.error(t);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.wso2.carbon.event.input.adaptor.jms.internal.util.JMSMessageListener.java

public void onMessage(Message message) {
    try {/*from   w w  w  .  j av a  2s.  c  o  m*/
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        if (message != null) {

            if (log.isDebugEnabled()) {
                log.debug(message);
            }

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                // Send the text of the message. Conversion to any type (XML,JSON) should
                // not happen here since this message will be built later.
                try {
                    String msgText = textMessage.getText();
                    eventAdaptorListener.onEventCall(msgText);
                } catch (JMSException e) {
                    if (log.isErrorEnabled()) {
                        log.error("Failed to get text from " + textMessage, e);
                    }
                } catch (InputEventAdaptorEventProcessingException e) {
                    if (log.isErrorEnabled()) {
                        log.error(e);
                    }
                }
            } else if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                Map event = new HashMap();
                try {
                    Enumeration names = mapMessage.getMapNames();
                    Object name;
                    while (names.hasMoreElements()) {
                        name = names.nextElement();
                        event.put(name, mapMessage.getObject((String) name));
                    }
                    eventAdaptorListener.onEventCall(event);

                } catch (JMSException e) {
                    log.error("Can not read the map message ", e);
                } catch (InputEventAdaptorEventProcessingException e) {
                    log.error("Can not send the message to broker ", e);
                }
            } else if (message instanceof BytesMessage) {
                BytesMessage bytesMessage = (BytesMessage) message;
                byte[] bytes;
                bytes = new byte[(int) bytesMessage.getBodyLength()];
                bytesMessage.readBytes(bytes);
                eventAdaptorListener.onEventCall(new String(bytes, "UTF-8"));
            } else {
                log.warn("Event dropped due to unsupported message type");
            }
        } else {
            log.warn("Dropping the empty/null event received through jms adaptor");
        }
    } catch (JMSException e) {
        log.error(e);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSConsumerClient.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {// w w  w .j a  v  a2 s. co  m
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {

        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                messageCount++;
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    preservedEventList.add(map);
                    log.info("Received Map Message : \n" + map + "\n");
                } else if (message instanceof TextMessage) {
                    String textMessage = ((TextMessage) message).getText();
                    preservedEventList.add(textMessage);
                    log.info("Received Text Message : \n" + textMessage + "\n");
                } else {
                    preservedEventList.add(message.toString());
                    log.info("Received message : \n" + message.toString() + "\n");
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}