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.wso2.carbon.event.core.internal.delivery.jms.JMSMessageListener.java

public void onMessage(Message message) {
    try {//  w  w  w  .jav a  2  s.c om
        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;
            StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(
                    new ByteArrayInputStream(textMessage.getText().getBytes()));
            org.wso2.carbon.event.core.Message messageToSend = new org.wso2.carbon.event.core.Message();
            messageToSend.setMessage(stAXOMBuilder.getDocumentElement());
            // 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 (XMLStreamException e) {
        log.error("Can not build the xml string", e);
    } catch (EventBrokerException e) {
        log.error("Can not send the notification ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}

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

/**
 * Invoke the mediation logic for the passed message
 * *//* ww  w .j a v  a 2  s  .  co m*/
public boolean invoke(Object object, String name) throws SynapseException {

    Message msg = (Message) object;
    try {
        org.apache.synapse.MessageContext msgCtx = createMessageContext();
        msgCtx.setProperty("inbound.endpoint.name", name);
        InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name);
        CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName());
        String contentType = msg.getJMSType();

        if (contentType == null || contentType.trim().equals("")) {
            String contentTypeProperty = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE_PROPERTY);
            if (contentTypeProperty != null) {
                contentType = msg.getStringProperty(contentTypeProperty);
            }
        } else {
            msgCtx.setProperty(JMSConstants.JMS_MESSAGE_TYPE, contentType);
        }

        if (contentType == null || contentType.trim().equals("")) {
            contentType = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed JMS Message of Content-type : " + contentType);
        }
        MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        //setting transport headers
        axis2MsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
                JMSUtils.getTransportHeaders(msg, axis2MsgCtx));
        // set the JMS Message ID as the Message ID of the MessageContext
        try {
            msgCtx.setMessageID(msg.getJMSMessageID());
            String jmsCorrelationID = msg.getJMSCorrelationID();
            if (jmsCorrelationID != null && !jmsCorrelationID.isEmpty()) {
                msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID);
            } else {
                msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, msg.getJMSMessageID());
            }
        } catch (JMSException ignore) {
            log.warn("Error getting the COORELATION ID from the message.");
        }

        // Handle dual channel
        Destination replyTo = msg.getJMSReplyTo();
        if (replyTo != null) {
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            // Create the cachedJMSConnectionFactory with the existing
            // connection
            CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(
                    jmsProperties, connection);
            String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
            String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
            JMSReplySender jmsReplySender = new JMSReplySender(replyTo, cachedJMSConnectionFactory, strUserName,
                    strPassword);
            msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
        } else if (replyDestination != null) {
            msgCtx.setProperty(SynapseConstants.IS_INBOUND, true);
            // Create the cachedJMSConnectionFactory with the existing
            // connection
            CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory(
                    jmsProperties, connection);
            String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME);
            String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD);
            JMSReplySender jmsReplySender = new JMSReplySender(replyDestination, cachedJMSConnectionFactory,
                    strUserName, strPassword);
            msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender);
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }
        OMElement documentElement = null;
        // set the message payload to the message context
        try {
            if (msg instanceof TextMessage) {
                String message = ((TextMessage) msg).getText();
                InputStream in = new AutoCloseInputStream(new ByteArrayInputStream(message.getBytes()));
                documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
            } else if (msg instanceof BytesMessage) {
                if (builder instanceof DataSourceMessageBuilder) {
                    documentElement = ((DataSourceMessageBuilder) builder).processDocument(
                            new BytesMessageDataSource((BytesMessage) msg), contentType, axis2MsgCtx);
                } else {
                    documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) msg),
                            contentType, axis2MsgCtx);
                }
            } else if (msg instanceof MapMessage) {
                documentElement = convertJMSMapToXML((MapMessage) msg);
            }
        } catch (Exception ex) {
            // Handle message building error
            log.error("Error while building the message", ex);
            msgCtx.setProperty(SynapseConstants.ERROR_CODE, GenericConstants.INBOUND_BUILD_ERROR);
            msgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, ex.getMessage());
            SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint);
            faultSequence.mediate(msgCtx);

            if (isRollback(msgCtx)) {
                return false;
            }
            return true;
        }

        // Setting JMSXDeliveryCount header on the message context
        try {
            int deliveryCount = msg.getIntProperty("JMSXDeliveryCount");
            msgCtx.setProperty(JMSConstants.DELIVERY_COUNT, deliveryCount);
        } catch (NumberFormatException nfe) {
            if (log.isDebugEnabled()) {
                log.debug("JMSXDeliveryCount is not set in the received message");
            }
        }

        // Inject the message to the sequence.
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
        if (injectingSeq == null || injectingSeq.equals("")) {
            log.error("Sequence name not specified. Sequence : " + injectingSeq);
            return false;
        }
        SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration()
                .getSequence(injectingSeq);
        if (seq != null) {
            if (log.isDebugEnabled()) {
                log.debug("injecting message to sequence : " + injectingSeq);
            }
            if (!seq.isInitialized()) {
                seq.init(synapseEnvironment);
            }
            SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint);
            MediatorFaultHandler mediatorFaultHandler = new MediatorFaultHandler(faultSequence);
            msgCtx.pushFaultHandler(mediatorFaultHandler);

            if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) {
                return false;
            }
        } else {
            log.error("Sequence: " + injectingSeq + " not found");
        }

        if (isRollback(msgCtx)) {
            return false;
        }
    } catch (SynapseException se) {
        throw se;
    } catch (Exception e) {
        log.error("Error while processing the JMS Message", e);
        throw new SynapseException("Error while processing the JMS Message", e);
    }
    return true;
}

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

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

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

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

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

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

    return map;
}

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

public void onMessage(Message message) {
    try {//w ww  .  j av  a 2 s.  c  om
        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;
            StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(
                    new ByteArrayInputStream(textMessage.getText().getBytes()));
            org.wso2.carbon.registry.event.core.Message messageToSend = new org.wso2.carbon.registry.event.core.Message();
            messageToSend.setMessage(stAXOMBuilder.getDocumentElement());
            // 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 (XMLStreamException e) {
        log.error("Can not build the xml string", e);
    } catch (EventBrokerException e) {
        log.error("Can not send the notification ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to non-null value and
 * check the correct routing key comes as a JMS property for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//  ww  w .  jav  a 2  s  . c om
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void queueRoutingKeyPropertyTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1");
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY),
                "RoutingKeyPropertyQueue", "Invalid value received for " + "routing key property.");
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to non-null value and
 * check the correct routing key comes as a JMS property for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from w w  w  .  ja  v a2s . co  m
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1");
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY),
                "RoutingKeyPropertyTopic", "Invalid value received for " + "routing key property.");

    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException/*from  w w w . jav a2  s.c o  m*/
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void queueRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from  www . j  a  v a2  s  . c  o  m
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");

    }
}