Example usage for javax.jms Session createTextMessage

List of usage examples for javax.jms Session createTextMessage

Introduction

In this page you can find the example usage for javax.jms Session createTextMessage.

Prototype


TextMessage createTextMessage() throws JMSException;

Source Link

Document

Creates a TextMessage object.

Usage

From source file:example.wildcard.Client.java

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

    try {
        Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName"));

        connection = connectionFactory.createConnection("admin", "password");

        Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = senderSession.createProducer(senderTopic);

        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);

        String policyType = System.getProperty("wildcard", ".*");
        String receiverTopicName = senderTopic.getTopicName() + policyType;
        Topic receiverTopic = receiverSession.createTopic(receiverTopicName);

        MessageConsumer receiver = receiverSession.createConsumer(receiverTopic);
        receiver.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        String text = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + text);
                    }
                } catch (JMSException e) {
                    System.out.println("Could not read the receiver's topic because of a JMSException");
                }
            }
        });

        connection.start();
        System.out.println("Listening on '" + receiverTopicName + "'");
        System.out.println("Enter a message to send: ");

        Scanner inputReader = new Scanner(System.in);

        while (true) {
            String line = inputReader.nextLine();
            if (line == null) {
                System.out.println("Done!");
                break;
            } else if (line.length() > 0) {
                try {
                    TextMessage message = senderSession.createTextMessage();
                    message.setText(line);
                    System.out.println("Sending a message: " + message.getText());
                    sender.send(message);
                } catch (JMSException e) {
                    System.out.println("Exception during publishing a message: ");
                }
            }
        }

        receiver.close();
        receiverSession.close();
        sender.close();
        senderSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("When trying to close connection: ");
            }
        }
    }

}

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

/**
 * @param args the destination name to send to and optionally, the number of
 *                messages to send// ww w . j av a  2s.  com
 */
public static void main(String... args) {
    Context jndiContext = null;
    ConnectionFactory connectionFactory = null;
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    MessageProducer producer = null;
    String destinationName = null;
    final int numMsgs;

    if ((args.length < 1) || (args.length > 2)) {
        LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");
        System.exit(1);
    }
    destinationName = args[0];
    LOG.info("Destination name is " + destinationName);
    if (args.length == 2) {
        numMsgs = (new Integer(args[1])).intValue();
    } else {
        numMsgs = 1;
    }

    /*
     * Create a JNDI API InitialContext object
     */
    try {
        jndiContext = new InitialContext();
    } catch (NamingException e) {
        LOG.info("Could not create JNDI API context: " + e.toString());
        System.exit(1);
    }

    /*
     * Look up connection factory and destination.
     */
    try {
        connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
        destination = (Destination) jndiContext.lookup(destinationName);
    } catch (NamingException e) {
        LOG.info("JNDI API lookup failed: " + e);
        System.exit(1);
    }

    /*
     * Create connection. Create session from connection; false means
     * session is not transacted. Create sender and text message. Send
     * messages, varying text slightly. Send end-of-messages message.
     * Finally, close connection.
     */
    try {
        connection = connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(destination);
        TextMessage message = session.createTextMessage();
        for (int i = 0; i < numMsgs; i++) {
            message.setText("This is message " + (i + 1));
            LOG.info("Sending message: " + message.getText());
            producer.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        producer.send(session.createMessage());
    } catch (JMSException e) {
        LOG.info("Exception occurred: " + e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}

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 a2  s  . com*/
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:example.transaction.Client.java

private static void acceptInputFromUser(Session senderSession, MessageProducer sender) throws JMSException {
    System.out.println("Type a message. Type COMMIT to send to receiver, type ROLLBACK to cancel");
    Scanner inputReader = new Scanner(System.in);

    while (true) {
        String line = inputReader.nextLine();
        if (line == null) {
            System.out.println("Done!");
            break;
        } else if (line.length() > 0) {
            if (line.trim().equals("ROLLBACK")) {
                System.out.println("Rolling back...");
                senderSession.rollback();
                System.out.println("Messages have been rolledback");
            } else if (line.trim().equals("COMMIT")) {
                System.out.println("Committing... ");
                senderSession.commit();// www  . j  a v a  2  s .c om
                System.out.println("Messages should have been sent");
            } else {
                TextMessage message = senderSession.createTextMessage();
                message.setText(line);
                System.out.println("Batching up:'" + message.getText() + "'");
                sender.send(message);
            }
        }
    }
}

From source file:com.appdynamicspilot.jms.CustomerMessageProducer.java

public void sendCustomerMesssage(final User user) {
    getJmsTemplate().send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            TextMessage msg = session.createTextMessage();
            StringBuilder builder = new StringBuilder();
            builder.append("user.id=");
            builder.append('\n');
            builder.append(user.getId());
            builder.append("user.email=");
            builder.append(user.getEmail());
            builder.append('\n');
            builder.append("user.password");
            builder.append(user.getPassword());
            msg.setText(builder.toString());
            return msg;
        }/*from w  ww.j a v  a  2s  .c  o m*/
    });
}

From source file:org.acruxsource.sandbox.spring.jmstows.jms.JmsMessageSender.java

public void sendMessage(String destination, final String message) {
    jmsTemplate.send(destination, new MessageCreator() {

        @Override/*w  w w. java  2s  .c  o  m*/
        public Message createMessage(Session session) throws JMSException {
            TextMessage textMessage = session.createTextMessage();
            textMessage.setText(message);
            return textMessage;
        }
    });
}

From source file:com.consol.citrus.samples.incident.service.FieldForceJmsClient.java

/**
 * Sends new order request via JMS./*w ww.ja  va 2 s .c  om*/
 * @param order
 */
public void send(final OrderRequest order) {
    jmsTemplate.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage textMessage = session.createTextMessage();

            StringResult payload = new StringResult();
            try {
                marshaller.marshal(order, payload);
            } catch (IOException e) {
                throw new ServiceException("Failed to create field force order request message", e);
            }

            textMessage.setText(payload.toString());
            return textMessage;
        }
    });
}

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

public void send(String destination, final String payload) {
    jmsTemplate.convertAndSend(destination, new MessageCreator() {
        @Override/*w w  w . j a  v a  2s.co 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:fi.vm.sade.log.client.LoggerJms.java

@Override
public void log(final Tapahtuma tapahtuma) {

    log.debug("log({})", tapahtuma);

    if (jmsTemplate == null) {
        throw new IllegalStateException("LoggerJms - invalid configuration 'jsmTemplate' not available!");
    }/*w  w w  .j a  va2 s  .  co  m*/

    final LogEvent event = new LogEvent(tapahtuma);

    // Convert message to TextMessage with LogEvent as XML in payload
    jmsTemplate.send(new MessageCreator() {
        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage();
            message.setText(encode(event));
            log.debug("  sending log message - text={}", message.getText());
            return message;
        }
    });

}

From source file:org.addsimplicity.anicetus.io.jms.JsonMessageConverter.java

/**
 * Translate the telemetry to a JMS message. A JMS text message is used to
 * contain the translated payload./*from  www. j ava 2 s  .  com*/
 * 
 * @param obj
 *          The telemetry artifact.
 * @param jsmSess
 *          The JMS session.
 * @return a text message containing the translated payload.
 * 
 * @see org.springframework.jms.support.converter.MessageConverter#toMessage(java.lang.Object,
 *      javax.jms.Session)
 */
public Message toMessage(Object obj, Session jmsSess) throws JMSException, MessageConversionException {
    TextMessage m = jmsSess.createTextMessage();

    GlobalInfo telemetry = (GlobalInfo) obj;
    m.setJMSCorrelationID(telemetry.getEntityId().toString());
    m.setStringProperty(GlobalInfoFields.ReportingNode.name(), telemetry.getReportingNode());

    if (telemetry.containsKey(ExecInfoFields.OperationName.name())) {
        m.setStringProperty(ExecInfoFields.OperationName.name(),
                (String) telemetry.get(ExecInfoFields.OperationName.name()));
    }

    if (telemetry.containsKey(ExecInfoFields.Status.name())) {
        m.setStringProperty(ExecInfoFields.Status.name(),
                telemetry.get(ExecInfoFields.Status.name()).toString());
    }

    char[] body = m_translator.encode(telemetry);

    m.setText(new String(body));

    return m;
}