Example usage for javax.jms TextMessage setStringProperty

List of usage examples for javax.jms TextMessage setStringProperty

Introduction

In this page you can find the example usage for javax.jms TextMessage setStringProperty.

Prototype


void setStringProperty(String name, String value) throws JMSException;

Source Link

Document

Sets a String property value with the specified name into the message.

Usage

From source file:org.apache.activemq.web.RestTest.java

@Test(timeout = 15 * 1000)
public void testCorrelation() throws Exception {
    int port = getPort();

    HttpClient httpClient = new HttpClient();
    httpClient.start();/*from   www . j  a  v  a 2 s .  c o  m*/

    for (int i = 0; i < 200; i++) {
        String correlId = "RESTY" + RandomStringUtils.randomNumeric(10);

        TextMessage message = session.createTextMessage(correlId);
        message.setStringProperty("correlationId", correlId);
        message.setJMSCorrelationID(correlId);

        LOG.info("Sending: " + correlId);
        producer.send(message);

        final StringBuffer buf = new StringBuffer();
        final CountDownLatch latch = asyncRequest(httpClient,
                "http://localhost:" + port + "/message/test?readTimeout=1000&type=queue&clientId=test", buf);

        latch.await();
        LOG.info("Received: " + buf.toString());
        // assertEquals(200, contentExchange.getResponseStatus());
        assertEquals(correlId, buf.toString());
    }
    httpClient.stop();
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

private Message getMockOozieMessage(int i, Session session, boolean isFalconWF)
        throws FalconException, JMSException {
    TextMessage message = session.createTextMessage();
    message.setStringProperty("appType", "WORKFLOW_JOB");
    if (isFalconWF) {
        message.setStringProperty("appName", "FALCON_PROCESS_DEFAULT_process1");
    } else {//from w  w w  .ja  v  a2  s. c o  m
        message.setStringProperty("appName", "OozieSampleShellWF");
    }
    message.setStringProperty("user", "falcon");
    switch (i % 4) {
    case 0:
        message.setText("{\"status\":\"RUNNING\",\"id\":\"0000042-130618221729631-oozie-oozi-W\""
                + ",\"startTime\":1342915200000}");
        break;
    case 1:
        message.setText("{\"status\":\"FAILED\",\"errorCode\":\"EL_ERROR\","
                + "\"errorMessage\":\"variable [dummyvalue] cannot be resolved\","
                + "\"id\":\"0000042-130618221729631-oozie-oozi-W\",\"startTime\":1342915200000,"
                + "\"endTime\":1366672183543}");
        break;
    case 2:
        message.setText("{\"status\":\"SUCCEEDED\",\"id\":\"0000039-130618221729631-oozie-oozi-W\""
                + ",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C@1\",\"endTime\":1366676224154}");
        break;
    case 3:
        message.setText("{\"status\":\"SUSPENDED\",\"id\":\"0000039-130618221729631-oozie-oozi-W\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C@1\"}");
        break;
    default:
    }
    return message;
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

private Message getMockOozieCoordMessage(int i, Session session, boolean isFalconWF)
        throws FalconException, JMSException {
    TextMessage message = session.createTextMessage();
    message.setStringProperty("appType", "COORDINATOR_ACTION");
    if (isFalconWF) {
        message.setStringProperty("appName", "FALCON_PROCESS_DEFAULT_process1");
    } else {//from w w  w. j a va2s .c  o  m
        message.setStringProperty("appName", "OozieSampleShellWF");
    }
    message.setStringProperty("user", "falcon");
    switch (i % 5) {
    case 0:
        message.setText("{\"status\":\"WAITING\",\"nominalTime\":1310342400000,\"missingDependency\""
                + ":\"hdfs://gsbl90107.blue.com:8020/user/john/dir1/file1\","
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\"}");
        message.setStringProperty("eventStatus", "WAITING");
        break;
    case 1:
        message.setText("{\"status\":\"RUNNING\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C\"}");
        message.setStringProperty("eventStatus", "STARTED");
        break;
    case 2:
        message.setText("{\"status\":\"SUCCEEDED\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\","
                + "\"startTime\":1342915200000,\"parentId\":\"0000025-130618221729631-oozie-oozi-C\","
                + "\"endTime\":1366677082799}");
        message.setStringProperty("eventStatus", "SUCCESS");
        break;
    case 3:
        message.setText("{\"status\":\"FAILED\",\"errorCode\":\"E0101\",\"errorMessage\":"
                + "\"dummyError\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\",\"endTime\":1366677140818}");
        message.setStringProperty("eventStatus", "FAILURE");
        break;
    case 4:
        message.setText("{\"status\":\"TIMEDOUT\",\"nominalTime\":1310342400000,"
                + "\"id\":\"0000025-130618221729631-oozie-oozi-C@1\",\"startTime\":1342915200000,"
                + "\"parentId\":\"0000025-130618221729631-oozie-oozi-C\",\"endTime\":1366677140818}");
        message.setStringProperty("eventStatus", "FAILURE");
    default:
    }
    return message;
}

From source file:com.oneops.controller.jms.InductorPublisher.java

/**
 * Publish message./* w  w w .j a  v a 2  s .c om*/
 *
 * @param waitTaskName the wait task name
 * @param woType       the wo type
 * @throws JMSException the jMS exception
 */
public void publishMessage(String processId, String execId, CmsWorkOrderSimpleBase wo, String waitTaskName,
        String woType) throws JMSException {
    SimpleDateFormat format = new SimpleDateFormat(CmsConstants.SEARCH_TS_PATTERN);
    wo.getSearchTags().put(CmsConstants.REQUEST_ENQUE_TS, format.format(new Date()));
    //guarantee non empty-value for searchMap
    if (version != null && StringUtils.isNotBlank(version.getGitVersion())) {
        wo.getSearchTags().put(CONTROLLLER_VERSION_SEARCH_TAG, version.getGitVersion());
    } else {
        wo.getSearchTags().put(CONTROLLLER_VERSION_SEARCH_TAG, DEFAULT_VERSION);
    }
    TextMessage message = session.createTextMessage(gson.toJson(wo));
    String corelationId = processId + "!" + execId + "!" + waitTaskName + "!" + getCtxtId(wo);
    message.setJMSCorrelationID(corelationId);
    message.setStringProperty("task_id", corelationId);
    message.setStringProperty("type", woType);

    String queueName = getQueue(wo);
    bindingQueusMap.computeIfAbsent(queueName, k -> {
        try {
            return newMessageProducer(k);
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }).send(message);

    if (logger.isDebugEnabled()) {
        logger.debug("Published: " + message.getText());
    }

    logger.info("Posted message with id " + corelationId + " to q: " + queueName);

}

From source file:com.oneops.inductor.MessagePublisher.java

@Override
protected boolean process(MessageHolder holder) {
    Map<String, String> event = holder.getMap();
    try {/*from ww  w .  j  av  a 2  s  .com*/
        TextMessage message = session.createTextMessage(event.get("body"));
        message.setJMSCorrelationID(event.get("correlationID"));

        for (Map.Entry<String, String> kv : event.entrySet()) {
            if (!kv.getKey().equals("body")) {
                message.setStringProperty(kv.getKey(), kv.getValue());
            }
        }

        MessageProducer producer = regularProducer;
        if ("high".equals(event.get("priority"))) {
            producer = priorityProducer;
            logger.debug("using priority producer to publish message");
        }

        producer.send(message);
        logger.debug("Published: " + message.toString());
        return true;
    } catch (NullPointerException npe) {
        // happens when amq session is null
        logger.warn("caught NullPointerException - reconnecting to broker");
        waitSome();
        init();
        return false;

    } catch (IllegalStateException e) {
        // this happens when connection is hosed - lets re-init
        logger.warn("caught IllegalStateException - reconnecting to broker");
        init();
        return false;

    } catch (JMSException e) {
        logger.error(e.getMessage());
        logger.debug(e.getMessage(), e);
        return false;
    }
}

From source file:SelectorChat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password, String selection) {

    // Create a connection.
    try {/*from w  w w. jav  a  2  s  . c  om*/
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics

    try {
        javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC);
        // NOTE: The subscriber's message selector will now be set:
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic,
                PROPERTY_NAME + " = \'" + selection + "\'", false);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
        System.exit(1);
    }

    try {
        // Read all standard input and send it as a message.

        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nSelectorChat application:\n" + "===========================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application will publish messages with " + PROPERTY_NAME + " set to " + selection
                + " to the " + APP_TOPIC + " topic .\n"
                + "The application also subscribes to that topic, selecting only messages where "
                + PROPERTY_NAME + " is " + selection + ".\n"
                + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                + ".\n");

        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = pubSession.createTextMessage();
                msg.setText(username + ": " + s);
                // NOTE: here we set a property on messages to be published:
                msg.setStringProperty(PROPERTY_NAME, selection);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

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

public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

    if (isDeactivated()) {
        return;//w ww.j  a  va 2 s  . c o  m
    }

    try {
        String userName = getLoggedInUserName();
        if ((userName == null) || (userName.equals(""))) {
            // use the system user name
            userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
        }

        TopicConnection topicConnection = getTopicConnection(userName);
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String tenantDomain = EventBrokerHolder.getInstance().getTenantDomain();
        if (tenantDomain != null
                && (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {
            if (!topicName.startsWith("/")) {
                topicName = getTopicName(tenantDomain + "/" + topicName);
            } else {
                topicName = getTopicName(tenantDomain + topicName);
            }
        } else {
            topicName = getTopicName(topicName);
        }

        Topic topic = topicSession.createTopic(topicName);
        //Some times we are not getting the proper topic with the required syntax, if it is not
        //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185
        if (!topic.toString().startsWith("topic://amq.topic")) {
            topic = topicSession.createTopic("BURL:" + topicName);
        }
        TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.setDeliveryMode(deliveryMode);
        TextMessage textMessage = topicSession.createTextMessage(message.getMessage().toString());

        Map<String, String> properties = message.getProperties();
        for (String key : properties.keySet()) {
            textMessage.setStringProperty(key, properties.get(key));
        }

        // saving the domain to be used send with the soap header
        if (CarbonContext.getThreadLocalCarbonContext().getTenantDomain() != null) {
            textMessage.setStringProperty(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME,
                    CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        }

        topicPublisher.publish(textMessage);
        topicPublisher.close();
        topicSession.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        throw new EventBrokerException("Can not publish to topic " + topicName + " " + e.getMessage(), e);
    }
}

From source file:SelectorTalk.java

/** Create JMS client for sending and receiving messages. */
private void talker(String broker, String username, String password, String rQueue, String sQueue,
        String selection) {/*from  ww  w . j a v a 2s .c  om*/
    // Create a connection.
    try {
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        receiveSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Sender and Receiver 'Talk' queues
    try {
        if (sQueue != null) {
            javax.jms.Queue sendQueue = sendSession.createQueue(sQueue);
            sender = sendSession.createProducer(sendQueue);
        }
        if (rQueue != null) {
            //NOTE: the Queue Receiver is set up with the Message Selector:
            javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue);
            javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue,
                    PROPERTY_NAME + " = \'" + selection + "\'");
            qReceiver.setMessageListener(this);
            connect.start();
        }
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
        exit();
    }

    try {
        if (rQueue != null)
            System.out.println("");
        else
            System.out.println("\nNo receiving queue specified.\n");

        // Read all standard input and send it as a message.
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        if (sQueue != null)
            System.out.println("SelectorTalk application:\n" + "=========================\n"
                    + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                    + ".\n" + "The application will send messages with " + PROPERTY_NAME + " set to "
                    + selection + " to the " + sQueue + " queue.\n"
                    + "The application creates a receiver on the " + rQueue
                    + " queue selecting only messages where " + PROPERTY_NAME + " is " + selection + ".\n\n"

                    + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                    + ".\n");
        else
            System.out.println("\nPress CTRL-C to exit.\n");

        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0 && sQueue != null) {
                javax.jms.TextMessage msg = sendSession.createTextMessage();
                msg.setText(username + ": " + s);
                // NOTE: here we set the property for each sent message.
                msg.setStringProperty(PROPERTY_NAME, selection);
                sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY,
                        MESSAGE_LIFESPAN);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
    // Close the connection.
    exit();
}

From source file:tools.ProducerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;// w  ww. java  2s  . c  o  m
    try {
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        MessageProducer producer = session.createProducer(destination);
        if (durable) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        int numMessagesToSend = useFinalControlMessage ? numMessages - 1 : numMessages;

        for (int i = 0; i < numMessagesToSend; i++) {
            String messageText = "Message " + i + " at " + new Date();
            if (bytesLength > -1) {
                byte[] messageTextBytes = messageText.getBytes(StandardCharsets.UTF_8);
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.writeBytes(messageTextBytes);
                if (messageTextBytes.length < bytesLength) {
                    byte[] paddingBytes = new byte[bytesLength - messageTextBytes.length];
                    bytesMessage.writeBytes(paddingBytes);
                }
                if (messageGroupId != null) {
                    bytesMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending bytes message");
                producer.send(bytesMessage);
            } else {
                TextMessage textMessage = session.createTextMessage(messageText);
                if (messageGroupId != null) {
                    textMessage.setStringProperty("JMSXGroupID", messageGroupId);
                }
                LOGGER.info("Sending text message: " + messageText);
                producer.send(textMessage);
            }

            if (perMessageSleepMS > 0) {
                Thread.sleep(perMessageSleepMS);
            }
            if (transacted) {
                if ((i + 1) % batchSize == 0) {
                    session.commit();
                }
            }
        }
        if (useFinalControlMessage) {
            Message message = session.createMessage();
            if (messageGroupId != null) {
                message.setStringProperty("JMSXGroupID", messageGroupId);
            }
            LOGGER.info("Sending message");
            producer.send(message);
            if (transacted) {
                session.commit();
            }
        }
        producer.close();
    } catch (Exception ex) {
        LOGGER.error("ProducerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.esb.client.impl.CtmsCaaersMessageConsumer.java

/**
 * This method sends the response out. It uses a producer which is connected to "ctms-caaers.outputQueue"
 * @param responseXml//from ww  w. ja va2  s  . c  o m
 * @param jmsCorelationID
 * @param messageType
 */
private void sendResponse(String responseXml, String jmsCorelationID, String messageType) {
    try {
        TextMessage message = session.createTextMessage();
        message.setJMSCorrelationID(jmsCorelationID);
        message.setStringProperty("MESSAGE_TYPE", messageType);
        message.setText(responseXml);
        producer.send(message);
    } catch (JMSException e) {
        logger.error("caught sendResponse", e);
    }
}