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:org.exist.messaging.JmsMessageSender.java

@Override
public NodeImpl send(JmsMessagingConfiguration config, MessagingMetadata metadata, Item content)
        throws XPathException {

    // JMS specific checks
    config.validateContent();/*from   w w  w  .j a  v  a2  s  .  c o m*/

    // Retrieve relevant values
    String initialContextFactory = config.getInitalContextProperty(Context.INITIAL_CONTEXT_FACTORY);
    String providerURL = config.getInitalContextProperty(Context.PROVIDER_URL);
    String connectionFactory = config.getConnectionFactory();
    String destination = config.getDestination();

    // TODO split up, use more exceptions, add better reporting
    try {
        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        props.setProperty(Context.PROVIDER_URL, providerURL);
        javax.naming.Context context = new InitialContext(props);

        // Setup connection
        ConnectionFactory cf = (ConnectionFactory) context.lookup(connectionFactory);
        Connection connection = cf.createConnection();

        // Lookup queue
        Destination dest = (Destination) context.lookup(destination);

        // Create session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create message producer
        MessageProducer producer = session.createProducer(dest);

        // Create message
        Message message = createMessage(session, content, metadata, xqcontext);

        // Write properties
        Map<String, String> kvs = metadata.getValueMap();
        for (String key : kvs.keySet()) {
            message.setStringProperty(key, kvs.get(key));
        }

        // Send message
        producer.send(message);

        // Close connection
        // TODO keep connection open for re-use, efficiency
        connection.close();

        return createReport(message, xqcontext);

    } catch (Throwable ex) {
        LOG.error(ex);
        throw new XPathException(ex);
    }
}

From source file:ProducerTool.java

protected void sendLoop(Session session, MessageProducer producer) throws Exception {

    for (int i = 0; i < messageCount || messageCount == 0; i++) {

        TextMessage message = session.createTextMessage(createMessageText(i));

        if (verbose) {
            String msg = message.getText();
            if (msg.length() > 50) {
                msg = msg.substring(0, 50) + "...";
            }//ww  w.j av  a2  s .  c om
            System.out.println("[" + this.getName() + "] Sending message: '" + msg + "'");
        }

        producer.send(message);

        if (transacted && (i % batch == 0)) {
            System.out.println("[" + this.getName() + "] Committing " + messageCount + " messages");
            session.commit();
        }
        Thread.sleep(sleepTime);
    }
}

From source file:org.openengsb.ports.jms.JMSPortTest.java

private String sendWithTempQueue(final String msg) {
    String resultString = jmsTemplate.execute(new SessionCallback<String>() {
        @Override/*from  w  w  w .  j  av a 2s . co m*/
        public String doInJms(Session session) throws JMSException {
            Queue queue = session.createQueue("receive");
            MessageProducer producer = session.createProducer(queue);
            TemporaryQueue tempQueue = session.createTemporaryQueue();
            MessageConsumer consumer = session.createConsumer(tempQueue);
            TextMessage message = session.createTextMessage(msg);
            message.setJMSReplyTo(tempQueue);
            producer.send(message);
            TextMessage response = (TextMessage) consumer.receive(10000);
            assertThat(
                    "server should set the value of the correltion ID to the value of the received message id",
                    response.getJMSCorrelationID(), is(message.getJMSMessageID()));
            JmsUtils.closeMessageProducer(producer);
            JmsUtils.closeMessageConsumer(consumer);
            return response != null ? response.getText() : null;
        }
    }, true);
    return resultString;
}

From source file:com.mirth.connect.connectors.jms.JmsReceiverTests.java

private void putMessagesInDestination(Destination destination, int numMessages) throws Exception {
    if (numMessages > 0) {
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        logger.debug("Putting " + numMessages + " messages into destination");

        for (int i = 0; i < numMessages; i++) {
            TextMessage message = session.createTextMessage(TEST_HL7_MESSAGE);
            message.setIntProperty("messageNumber", i);
            producer.send(message);
        }//from  w  w w  .j  ava 2 s .  com
    }
}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private void sendMessage(String queueName, int count, boolean transacted) throws JMSException {
    Connection con = connectionFactory.createConnection();
    try {//w  w  w.  ja v a2  s  . c o  m
        Session session = con.createSession(transacted,
                transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        try {
            Queue destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            try {
                for (int i = 0; i < count; i++) {
                    TextMessage message = session.createTextMessage();
                    message.setIntProperty("MessageId", messageCounter);
                    message.setText("Message-" + messageCounter++);
                    producer.send(message);
                }
                if (transacted) {
                    session.commit();
                }
            } finally {
                producer.close();
            }
        } finally {
            session.close();
        }
    } finally {
        con.close();
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/* w ww .  j a va2 s.  c om*/
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyDeliveringStats(defaultQueueName, 0, 0);

    MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
    Message msg = consumer.receive();
    verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
    msg.acknowledge();

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyDeliveringStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * Publish a tick history object//w  w  w  .  j  av  a  2s.co m
 * @param tick
 */
public void publishTickHistory(TickHistory tick, MessageProducer mp) {

    BytesMessage tickMessage;
    try {
        Session session = this.createSession();

        // Create a new ByteMessage
        tickMessage = session.createBytesMessage();

        // Serialize the tick content into the message
        tickMessage.writeBytes(tick.serialize());
        mp.send(tickMessage);
        this.closeSession(session);
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.springframework.jms.listener.adapter.MessageListenerAdapter.java

/**
 * Send the given response message to the given destination.
 * @param response the JMS message to send
 * @param destination the JMS destination to send to
 * @param session the JMS session to operate on
 * @throws JMSException if thrown by JMS API methods
 * @see #postProcessProducer//from   w w w  .  jav  a2  s.  co m
 * @see javax.jms.Session#createProducer
 * @see javax.jms.MessageProducer#send
 */
protected void sendResponse(Session session, Destination destination, Message response) throws JMSException {
    MessageProducer producer = session.createProducer(destination);
    try {
        postProcessProducer(producer, response);
        producer.send(response);
    } finally {
        JmsUtils.closeMessageProducer(producer);
    }
}

From source file:com.moss.veracity.core.cluster.jms.UpdateTransmitterJMSImpl.java

private void sendMessage(Object o) {

    Session session = null;/*w  w w . j  ava 2  s .c o m*/
    MessageProducer producer = null;
    try {
        StringWriter writer = new StringWriter();
        Marshaller m = jaxbContext.createMarshaller();
        m.marshal(o, writer);
        String text = writer.getBuffer().toString();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(UpdateTopic.NAME);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        TextMessage message = session.createTextMessage(text);
        producer.send(message);

        producer.close();
        session.close();
    } catch (Exception ex) {

        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close producer after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to close session after failure", e);
                } else {
                    ex.printStackTrace();
                }
            }
        }

        throw new RuntimeException("Message transmission failed: " + o, ex);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testScheduledStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/*w  w w  . j a v  a2 s .com*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.setDeliveryDelay(2000);
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyScheduledStats(defaultQueueName, 1, publishedMessageSize.get());

    consumeTestQueueMessages(1);

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyScheduledStats(defaultQueueName, 0, 0);

    connection.close();
}