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:example.queue.selector.Producer.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from w w  w .  j ava2 s.  c  o  m
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageProducer producer = session.createProducer(destination);

        for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {
            TextMessage message = session.createTextMessage("Message #" + i);
            System.out.println("Sending message #" + i);
            if (i % 2 == 0) {
                System.out.println("Sending to me");
                message.setStringProperty("intended", "me");
            } else {
                System.out.println("Sending to you");
                message.setStringProperty("intended", "you");
            }
            producer.send(message);
            Thread.sleep(DELAY);
        }

        producer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *///from  w ww  .ja v a  2s  .c  om
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:io.datalayer.activemq.producer.SpringProducer.java

public void start() throws JMSException {
    for (int i = 0; i < messageCount; i++) {
        final String text = "Text for message: " + i;
        template.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                LOG.info("Sending message: " + text);
                TextMessage message = session.createTextMessage(text);
                message.setStringProperty("next", "foo");
                return message;
            }//from w w w .  j  ava 2  s .com
        });
    }
}

From source file:org.apache.stratos.autoscaler.integration.TopicPublisher.java

private void publish(Object message, String eventClassName) throws NamingException, JMSException, IOException {
    // Send message
    if (message instanceof String) {
        TextMessage textMessage = topicSession.createTextMessage((String) message);
        textMessage.setStringProperty(Constants.EVENT_CLASS_NAME, eventClassName);
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.publish(textMessage);
        log.info("Text message sent: " + (String) message);
    } else if (message instanceof Serializable) {
        ObjectMessage objectMessage = topicSession.createObjectMessage((Serializable) message);
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.publish(objectMessage);
        log.info("Object message sent: " + ((Serializable) message).toString());
    } else {//from   www . j  a  v a 2  s . co  m
        throw new RuntimeException("Unknown message type");
    }
}

From source file:org.btc4j.jms.BtcDaemonCaller.java

public void send(String destination, final String payload) {
    jmsTemplate.convertAndSend(destination, new MessageCreator() {
        @Override//from www  . ja v  a  2  s  .  c  o m
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage();
            message.setText(payload);
            message.setStringProperty("btcapi:account", account);
            message.setStringProperty("btcapi:password", password);
            return message;
        }
    });
}

From source file:org.apache.activemq.JmsTopicSendSameMessageTest.java

public void testSendReceive() throws Exception {
    messages.clear();// w w w  .ja  va  2 s .com

    TextMessage message = session.createTextMessage();

    for (int i = 0; i < data.length; i++) {
        message.setText(data[i]);
        message.setStringProperty("stringProperty", data[i]);
        message.setIntProperty("intProperty", i);

        if (verbose) {
            LOG.info("About to send a message: " + message + " with text: " + data[i]);
        }

        producer.send(producerDestination, message);
    }

    assertMessagesAreReceived();
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void lockPhone(int accountId) throws IOException {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;//from w ww . j a v a2  s.  c o  m
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:com.mdmserver.managers.ControllerFacade.java

public void uninstallApp(int accountId, String appPackageName) {
    Account account = databaseManager.getAccountByAccountId(accountId);
    Context ctx;//from   w w w  .jav a2s .  co m
    try {
        ctx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/mdmQueue");
        MessageProducer messageProducer;
        System.out.println("Naming success");
        try {

            javax.jms.Connection connection = connectionFactory.createConnection();
            javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(queue);
            TextMessage message = session.createTextMessage();
            message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId());
            ControlClient cClient = new ControlClient();
            cClient.setCommandType(ControlClient.UNINSTALL_APP_CONTROL);
            cClient.setJsonCommandDetails(appPackageName);
            Gson gson = new Gson();
            message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient));
            System.out.println("It come from Servlet:" + message.getText());
            messageProducer.send(message);
            System.out.println("JMS success");
        } catch (JMSException ex) {
            //                  Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("JMS exception");
        }

    } catch (NamingException ex) {
        //                Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Naming exception");
    }
}

From source file:de.taimos.dvalin.interconnect.core.spring.DaemonMessageSender.java

private void sendIVO(final String correlationID, final Destination replyTo, final InterconnectObject ico,
        final boolean secure) throws Exception {
    final String json = InterconnectMapper.toJson(ico);
    this.logger.debug("TextMessage send: " + json);
    this.template.send(replyTo, new MessageCreator() {

        @Override//from ww w  . ja v  a  2  s.c  o  m
        public Message createMessage(final Session session) throws JMSException {
            final TextMessage textMessage = session.createTextMessage();
            textMessage.setStringProperty(InterconnectConnector.HEADER_ICO_CLASS, ico.getClass().getName());
            textMessage.setJMSCorrelationID(correlationID);
            textMessage.setText(json);
            if (secure) {
                try {
                    MessageConnector.secureMessage(textMessage);
                } catch (CryptoException e) {
                    throw new JMSException(e.getMessage());
                }
            }
            return textMessage;
        }
    });
}

From source file:org.ala.jms.JmsMessageProducer.java

@Test
public void generateInvalidMethod() throws JMSException {
    template.send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            String json = getJson("" + myGuid);
            TextMessage message = session.createTextMessage(json);

            message.setStringProperty(JmsMessageListener.MESSAGE_METHOD, "");

            logger.debug("B Sending message: " + message.getStringProperty(JmsMessageListener.MESSAGE_METHOD)
                    + " == " + json);

            return message;
        }//from  w  w w .j av a2 s.  c o m
    });
}