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:eu.planets_project.tb.impl.system.batch.backends.ifwee.TestbedWEEBatchProcessor.java

public void submitTicketForPollingToQueue(String ticket, String queueName, String batchProcessorSystemID)
        throws Exception {
    Context ctx = null;/*from ww  w  . j a va  2s .c  o m*/
    QueueConnection cnn = null;
    QueueSession sess = null;
    Queue queue = null;
    QueueSender sender = null;
    try {
        ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup(QueueConnectionFactoryName);
        queue = (Queue) ctx.lookup(queueName);
        cnn = factory.createQueueConnection();
        sess = cnn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        //create the message to send to the MDB e.g. a TextMessage
        TextMessage message = sess.createTextMessage(ticket);
        message.setStringProperty(BatchProcessor.QUEUE_PROPERTY_NAME_FOR_SENDING, batchProcessorSystemID);

        //and finally send the message to the queue.
        sender = sess.createSender(queue);
        sender.send(message);
        log.debug("TestbedWEEBatchProcessor: sent message to queue, ID:" + message.getJMSMessageID());
    } finally {
        try {
            if (null != sender)
                sender.close();
        } catch (Exception ex) {
        }
        try {
            if (null != sess)
                sess.close();
        } catch (Exception ex) {
        }
        try {
            if (null != cnn)
                cnn.close();
        } catch (Exception ex) {
        }
        try {
            if (null != ctx)
                ctx.close();
        } catch (Exception ex) {
        }
    }
}

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

/**
 * {@inheritDoc}/*from  ww w. j a  va2 s  . c  o  m*/
 */
public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

    if (isDeactivated()) {
        return;
    }

    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))) {
            topicName = tenantDomain + "/" + getTopicName(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());

        Map<String, String> properties = message.getProperties();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            textMessage.setStringProperty(entry.getKey(), entry.getValue());
        }

        // 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:org.apache.stratos.messaging.broker.publish.TopicPublisher.java

private void doPublish(String message, Properties headers) throws Exception, JMSException {
    if (!initialized) {
        // Initialize a topic connection to the message broker
        connector.init(getName());//from   www.j a  v  a2  s. co  m
        initialized = true;
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher connector initialized: [topic] %s", getName()));
        }
    }

    try {
        // Create a new session
        topicSession = createSession(connector);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher session created: [topic] %s", getName()));
        }
        // Create a publisher from session
        topicPublisher = createPublisher(topicSession);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Topic publisher created: [topic] %s", getName()));
        }

        // Create text message
        TextMessage textMessage = topicSession.createTextMessage(message);

        if (headers != null) {
            // Add header properties
            @SuppressWarnings("rawtypes")
            Enumeration e = headers.propertyNames();

            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                textMessage.setStringProperty(key, headers.getProperty(key));
            }
        }

        topicPublisher.publish(textMessage);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Message published: [topic] %s [header] %s [body] %s", getName(),
                    (headers != null) ? headers.toString() : "null", message));
        }
    } finally {
        if (topicPublisher != null) {
            topicPublisher.close();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Topic publisher closed: [topic] %s", getName()));
            }
        }
        if (topicSession != null) {
            topicSession.close();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Topic publisher session closed: [topic] %s", getName()));
            }
        }
    }
}

From source file:ca.uhn.hunit.iface.AbstractJmsInterfaceImpl.java

@Override
protected TestMessage<T> internalSendMessage(final TestMessage<T> theMessage) throws TestFailureException {
    LogFactory.INSTANCE.get(this).info("Sending message (" + theMessage.getRawMessage().length() + " bytes)");

    try {/*from w  ww  .  j  a  v  a  2s  . c o  m*/
        MessageCreator mc = new MessageCreator() {
            @Override
            public javax.jms.Message createMessage(Session theSession) throws JMSException {
                TextMessage textMessage = theSession.createTextMessage(theMessage.getRawMessage());

                for (int i = 0; i < myMessagePropertyTableModel.getRowCount(); i++) {
                    if (java.lang.String.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setStringProperty(myMessagePropertyTableModel.getName(i),
                                (String) myMessagePropertyTableModel.getArg(i));
                    } else if (java.lang.Integer.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setIntProperty(myMessagePropertyTableModel.getName(i),
                                (Integer) myMessagePropertyTableModel.getArg(i));
                    } else if (int.class.equals(myMessagePropertyTableModel.getArgType(i))) {
                        textMessage.setIntProperty(myMessagePropertyTableModel.getName(i),
                                (Integer) myMessagePropertyTableModel.getArg(i));
                    }
                }

                return textMessage;
            }
        };

        myJmsTemplate.send(myQueueName, mc);
        LogFactory.INSTANCE.get(this).info("Sent message");

    } catch (JmsException e) {
        throw new InterfaceWontSendException(this, e.getMessage(), e);
    }

    return null;
}

From source file:org.apache.activemq.cli.test.ArtemisTest.java

public void testSimpleRun(String folderName) throws Exception {
    File instanceFolder = temporaryFolder.newFolder(folderName);

    setupAuth(instanceFolder);/*from ww  w . j  ava 2s .  com*/
    String queues = "q1,q2";
    String addresses = "a1,a2";

    // This is usually set when run from the command line via artemis.profile
    Run.setEmbedded(true);
    Artemis.main("create", instanceFolder.getAbsolutePath(), "--force", "--silent", "--no-web", "--queues",
            queues, "--addresses", addresses, "--no-autotune", "--require-login");
    System.setProperty("artemis.instance", instanceFolder.getAbsolutePath());

    // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol
    Artemis.internalExecute("run");

    try {
        try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616");
                ClientSessionFactory factory = locator.createSessionFactory();
                ClientSession coreSession = factory.createSession("admin", "admin", false, true, true, false,
                        0)) {
            for (String str : queues.split(",")) {
                ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find queue " + str, queryResult.isExists());
            }
            for (String str : addresses.split(",")) {
                ClientSession.AddressQuery queryResult = coreSession
                        .addressQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find address " + str, queryResult.isExists());
            }
        }

        try {
            Artemis.internalExecute("data", "print");
            Assert.fail("Exception expected");
        } catch (CLIException expected) {
        }
        Artemis.internalExecute("data", "print", "--f");

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("producer", "--message-count", "100",
                "--verbose", "--user", "admin", "--password", "admin"));
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--verbose", "--break-on-null",
                "--receive-timeout", "100", "--user", "admin", "--password", "admin"));

        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = cf.createConnection("admin", "admin");
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(
                ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE));

        TextMessage message = session.createTextMessage("Banana");
        message.setStringProperty("fruit", "banana");
        producer.send(message);

        for (int i = 0; i < 100; i++) {
            message = session.createTextMessage("orange");
            message.setStringProperty("fruit", "orange");
            producer.send(message);
        }
        session.commit();

        connection.close();
        cf.close();

        assertEquals(Integer.valueOf(1), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='banana'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='orange'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(101), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--user", "admin", "--password", "admin"));

        // should only receive 10 messages on browse as I'm setting messageCount=10
        assertEquals(Integer.valueOf(10), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--message-count", "10", "--user", "admin", "--password", "admin"));

        // Nothing was consumed until here as it was only browsing, check it's receiving again
        assertEquals(Integer.valueOf(1),
                Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null",
                        "--receive-timeout", "100", "--filter", "fruit='banana'", "--user", "admin",
                        "--password", "admin"));

        // Checking it was acked before
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose",
                "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin"));
    } finally {
        stopServer();
    }
}

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

@Override
public boolean sendMessage(Run<?, ?> build, TaskListener listener, MessageUtils.MESSAGE_TYPE type, String props,
        String content) {//  w w  w .  j  a  v a2  s .  co m
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;

    try {
        String ltopic = getTopic();
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);

            TextMessage message;
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);

            message.setStringProperty("CI_NAME", build.getParent().getName());
            message.setStringProperty("CI_TYPE", type.getMessage());
            if (!build.isBuilding()) {
                message.setStringProperty("CI_STATUS",
                        (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            }

            StrSubstitutor sub = new StrSubstitutor(build.getEnvironment(listener));

            if (props != null && !props.trim().equals("")) {
                Properties p = new Properties();
                p.load(new StringReader(props));
                @SuppressWarnings("unchecked")
                Enumeration<String> e = (Enumeration<String>) p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    message.setStringProperty(key, sub.replace(p.getProperty(key)));
                }
            }

            message.setText(sub.replace(content));

            publisher.send(message);
            log.info("Sent " + type.toString() + " message for job '" + build.getParent().getName()
                    + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return false;
        }

    } catch (Exception e) {
        log.log(Level.SEVERE, "Unhandled exception in perform.", e);
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return true;
}

From source file:org.codehaus.stomp.StompTest.java

public void sendMessage(String msg, String propertyName, String propertyValue) throws JMSException {
    MessageProducer producer = session.createProducer(queue);
    TextMessage message = session.createTextMessage(msg);
    message.setStringProperty(propertyName, propertyValue);
    producer.send(message);//  w w  w  .  j a  v  a2s.  c o m
}

From source file:org.codehaus.stomp.StompTest.java

public void testSubscribeWithMessageSentWithProperties() throws Exception {

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);//w w w .j a  v  a2  s .  c  o m

    frame = receiveFrame(100000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SUBSCRIBE\n" + "destination:/queue/" + getQueueName() + "\n" + "ack:auto\n\n" + Stomp.NULL;
    sendFrame(frame);

    MessageProducer producer = session.createProducer(queue);
    TextMessage message = session.createTextMessage("Hello World");
    message.setStringProperty("s", "value");
    message.setBooleanProperty("n", false);
    message.setByteProperty("byte", (byte) 9);
    message.setDoubleProperty("d", 2.0);
    message.setFloatProperty("f", (float) 6.0);
    message.setIntProperty("i", 10);
    message.setLongProperty("l", 121);
    message.setShortProperty("s", (short) 12);
    producer.send(message);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("MESSAGE"));

    //        System.out.println("out: "+frame);

    frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);
}

From source file:org.openanzo.combus.realtime.RealtimeUpdatePublisher.java

/**
 * Reset cache the cache of acls//from w  w  w.  j  a  v  a2 s .  c  om
 * 
 * @param session
 *            session
 * @throws AnzoException
 */
public void reset(Session session) throws AnzoException {
    synchronized (datasetTrackers) {
        datasetTrackers.clear();
    }
    userRolesCache.clear();
    graphRolesCache.clear();
    registeredSysadmins.clear();
    trackers.clear();
    namedGraphTrackers.clear();
    try {
        // Now send a transaction complete to all users
        TextMessage endMessage = session.createTextMessage();
        endMessage.setStringProperty(SerializationConstants.operation, SerializationConstants.reset);
        endMessage.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION);
        for (Map.Entry<URI, Collection<Destination>> entry : userDestinations.entrySet()) {
            Collection<Destination> destinations = entry.getValue();
            for (Destination destination : destinations) {
                try {
                    getProducer().send(destination, endMessage);
                } catch (JMSException jmex) {
                    log.debug(LogUtils.COMBUS_MARKER, "Error sending reset message", jmex);
                    cleanupDestination(entry.getKey(), destination);
                }
            }
        }
    } catch (JMSException jmse) {
        throw new AnzoException(ExceptionConstants.COMBUS.PROCESS_UPDATE_FAILED, jmse);
    }
    //currentServerId = serviceContainer.getInstanceURI().toString();
}