Example usage for javax.jms MessageProducer send

List of usage examples for javax.jms MessageProducer send

Introduction

In this page you can find the example usage for javax.jms MessageProducer send.

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live.

Usage

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/*from   w w  w .  j av a2 s . c  om*/
 */
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]
 */// w  w w . j a v a  2  s . 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:org.xerela.zap.jms.EventElf.java

/**
 * @param queueName//from   w  w w.  jav  a 2 s  .  c o m
 * @param message
 * @throws Exception
 */
public static void sendMessage(String queueName, Message message) throws Exception {
    MessageProducer producer = (MessageProducer) producerPool.borrowObject(queueName);
    try {
        producer.send(message);
    } finally {
        producerPool.returnObject(queueName, producer);
    }
}

From source file:org.wso2.carbon.sample.jmsclient.JMSClientUtil.java

/**
 * Each message will be divided into groups and create the map message
 *
 * @param producer     Used for sending messages to a destination
 * @param session      Used to produce the messages to be sent
 * @param messagesList List of messages to be sent
 *///from   w w w  . j  av  a2 s .  c  om
public static void publishTextMessage(MessageProducer producer, Session session, List<String> messagesList)
        throws JMSException {
    for (String message : messagesList) {
        TextMessage jmsMessage = session.createTextMessage();
        jmsMessage.setText(message);
        producer.send(jmsMessage);
    }
}

From source file:service.emailer.Emailer.java

/**
 * Send email with parameters to emailQueue
 * @param area//w ww.  j  ava 2s .  c  o  m
 * @param email
 */
public static void sendEmail(String area, List<String> email) {
    try {
        //JMS QUEUE SEND
        final ConnectionFactory connectionFactory = lookup(ConnectionFactory.class, JNDI_CONNECTION_FACTORY);
        final Queue queue = lookup(Queue.class, JNDI_QUEUE);

        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        MapMessage message = session.createMapMessage();
        message.setString("type", "warnFile");
        message.setString("area", area);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(email);
        message.setString("emailReceivers", json);
        producer.send(message);
    } catch (JMSException ex) {
        Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JsonProcessingException ex) {
        Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.activemq.bugs.AMQ7118Test.java

protected static boolean produce(Session session, Topic topic, int messageCount, int messageSize)
        throws JMSException {
    MessageProducer producer = session.createProducer(topic);

    for (int i = 0; i < messageCount; i++) {
        TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize));

        try {// www .  j  av a2 s .c  o m
            producer.send(helloMessage);
        } catch (ResourceAllocationException e) {
            return false;
        }
    }

    return true;
}

From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * Each message will be divided into groups and create the map message
 *
 * @param producer     Used for sending messages to a destination
 * @param session      Used to produce the messages to be sent
 * @param messagesList List of messages to be sent
 *
 *///from   w  ww. j  a v  a  2s .c om
public static void publishTextMessage(MessageProducer producer, Session session, List<String> messagesList)
        throws JMSException {
    for (String message : messagesList) {
        TextMessage jmsTextMessage = session.createTextMessage();
        jmsTextMessage.setText(message);
        producer.send(jmsTextMessage);
    }
}

From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java

public static void publishMapMessage(MessageProducer producer, Session session,
        List<Map<String, Object>> messagesList) throws IOException, JMSException {
    for (Map<String, Object> message : messagesList) {
        MapMessage mapMessage = session.createMapMessage();
        message.put("time", System.currentTimeMillis());
        for (Map.Entry<String, Object> entry : message.entrySet()) {
            mapMessage.setObject(entry.getKey(), entry.getValue());
        }/*from   w w w.j a  va 2s.  c o  m*/
        producer.send(mapMessage);
    }
    log.info("messages sent (per-thread):" + messagesList.size());
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

protected static void produce(Connection connection, Queue queue, int messageCount, int messageSize)
        throws JMSException, IOException, XAException {
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    MessageProducer producer = session.createProducer(queue);

    for (int i = 0; i < messageCount; i++) {
        TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize));
        producer.send(helloMessage);
        session.commit();/*from  www.j  av  a 2 s.  c  o  m*/

    }
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static void deliverMessageToTopic(String host, String topicName, String xml) {
    log.debug("IntegrationMod.deliverMessageToQueue queueName = " + topicName + " and doc = " + xml);

    char test = topicName.charAt(0);

    if (test == '/')
        topicName = topicName.substring(1);

    try {//w w  w .  ja v  a2  s .c o m

        InitialContext context = JNDIUtil.getInitialContext(host);

        Connection connection = null;
        Session session = null;
        MessageProducer publisher = null;
        ConnectionFactory tcf = (ConnectionFactory) context.lookup("ConnectionFactory");

        Topic topic = (Topic) context.lookup(topicName);

        connection = tcf.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        publisher = session.createProducer(topic);

        TextMessage message = session.createTextMessage();

        log.debug("message value is -> " + xml);

        message.setText(xml);

        publisher.send(message);

    } catch (Exception e) {
        log.error("unable to send message on topic", e);
    } finally {

    }
}