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.apache.activemq.store.jdbc.JDBCCleanupLimitedPoolTest.java

@Test
public void testNoDeadlockOnXaPoolExhaustion() throws Exception {
    final CountDownLatch done = new CountDownLatch(1);
    final CountDownLatch doneCommit = new CountDownLatch(1000);

    final ActiveMQXAConnectionFactory factory = new ActiveMQXAConnectionFactory(
            broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());

    ExecutorService executorService = Executors.newCachedThreadPool();
    // some contention over pool of 2
    for (int i = 0; i < 3; i++) {
        executorService.execute(new Runnable() {
            @Override//from www. j av a 2 s.  c  o m
            public void run() {
                try {
                    ActiveMQXAConnection conn = (ActiveMQXAConnection) factory.createXAConnection();
                    conn.start();
                    XASession sess = conn.createXASession();
                    while (done.getCount() > 0 && doneCommit.getCount() > 0) {
                        Xid xid = createXid();
                        sess.getXAResource().start(xid, XAResource.TMNOFLAGS);
                        MessageProducer producer = sess.createProducer(sess.createQueue("test"));
                        producer.send(sess.createTextMessage("test"));
                        sess.getXAResource().end(xid, XAResource.TMSUCCESS);
                        sess.getXAResource().prepare(xid);
                        sess.getXAResource().commit(xid, false);
                        doneCommit.countDown();
                    }

                    conn.close();

                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        });
    }

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            try {
                while (!done.await(10, TimeUnit.MILLISECONDS) && doneCommit.getCount() > 0) {
                    jdbcPersistenceAdapter.cleanup();
                }
            } catch (Exception ignored) {
            }

        }
    });

    executorService.shutdown();
    boolean allComplete = executorService.awaitTermination(40, TimeUnit.SECONDS);
    done.countDown();
    assertTrue("all complete", allComplete);
    executorService.shutdownNow();

    assertTrue("xa tx done", doneCommit.await(10, TimeUnit.SECONDS));
}

From source file:org.apache.storm.jms.spout.JmsSpoutTest.java

public Message sendMessage(ConnectionFactory connectionFactory, Destination destination) throws JMSException {
    Session mySess = connectionFactory.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = mySess.createProducer(destination);
    TextMessage msg = mySess.createTextMessage();
    msg.setText("Hello World");
    log.debug("Sending Message: " + msg.getText());
    producer.send(msg);
    return msg;//ww  w .  ja v a2  s .co  m
}

From source file:org.apache.servicemix.wsn.jms.JmsPublisher.java

@Override
public void notify(NotificationMessageHolderType messageHolder, String mes) {
    Session session = null;/* w w  w .  j  a  v  a2  s.  c o m*/
    try {
        Topic topic = topicConverter.toActiveMQTopic(messageHolder.getTopic());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(topic);
        Message message = session.createTextMessage(mes);
        producer.send(message);
    } catch (JMSException e) {
        log.warn("Error dispatching message", e);
    } catch (InvalidTopicException e) {
        log.warn("Error dispatching message", e);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.debug("Error closing session", e);
            }
        }
    }
}

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

/**
 * Tests if the consumer receives the messages that were sent before the
 * connection was started./*www .j  a v  a 2  s .  c  o  m*/
 *
 * @throws JMSException
 */
public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException {
    Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Setup the consumers.
    Topic topic = startedSession.createTopic("test");
    MessageConsumer startedConsumer = startedSession.createConsumer(topic);
    MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic);

    // Send the message.
    MessageProducer producer = startedSession.createProducer(topic);
    TextMessage message = startedSession.createTextMessage("Hello");
    producer.send(message);

    // Test the assertions.
    Message m = startedConsumer.receive(1000);
    assertNotNull(m);

    m = stoppedConsumer.receive(1000);
    assertNull(m);

    stoppedConnection.start();
    m = stoppedConsumer.receive(5000);
    assertNotNull(m);

    startedSession.close();
    stoppedSession.close();
}

From source file:org.dawnsci.commandserver.core.producer.Broadcaster.java

/**
 * /*from   ww w . j av a 2 s. c o  m*/
 * @param bean
 * @throws Exception 
 */
private void updateQueue(StatusBean bean) throws Exception {

    QueueConnection qCon = null;

    try {

        QueueBrowser qb = qSes.createBrowser(queue);

        @SuppressWarnings("rawtypes")
        Enumeration e = qb.getEnumeration();

        ObjectMapper mapper = new ObjectMapper();
        String jMSMessageID = null;
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                @SuppressWarnings("unchecked")
                final StatusBean qbean = mapper.readValue(t.getText(), bean.getClass());
                if (qbean == null)
                    continue;
                if (qbean.getUniqueId() == null)
                    continue; // Definitely not our bean
                if (qbean.getUniqueId().equals(bean.getUniqueId())) {
                    jMSMessageID = t.getJMSMessageID();
                    break;
                }
            }
        }

        qb.close();

        if (jMSMessageID != null) {
            MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
            Message m = consumer.receive(1000);
            if (m != null && m instanceof TextMessage) {
                MessageProducer producer = qSes.createProducer(queue);
                producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:org.sakaiproject.kernel.messaging.JmsEmailMessageHandler.java

/**
 * {@inheritDoc}/*from   ww w. j  ava  2s.co m*/
 *
 * @see org.sakaiproject.kernel.api.messaging.MessageHandler#handle(java.lang.String,
 *      java.lang.String, java.lang.String, javax.jcr.Node)
 */
public void handle(String userID, String filePath, String fileName, Node node) {
    try {
        InputStream inputStream = nodeFactory.getInputStream(filePath);
        String content = IOUtils.readFully(inputStream, "UTF-8");
        Connection conn = connFactory.createConnection();
        conn.setClientID("sakai.emailmessagehandler");
        Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination emailTopic = clientSession.createTopic(emailQueueName);
        MessageProducer client = clientSession.createProducer(emailTopic);
        ObjectMessage mesg = clientSession.createObjectMessage(content);
        mesg.setJMSType(emailJmsType);
        client.send(mesg);
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } catch (JCRNodeFactoryServiceException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private void sendRandomMessage(TopicSession session, MessageProducer producer) throws JMSException {
    TextMessage textMessage = session.createTextMessage();
    textMessage.setText(RandomStringUtils.random(500, "abcdefghijklmnopqrstuvwxyz"));
    producer.send(textMessage);
}

From source file:com.datatorrent.lib.io.jms.JMSTestBase.java

public void produceMsg(String text) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();/*ww  w .  j a v  a2  s .c o m*/

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

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    TextMessage message = session.createTextMessage(text);
    producer.send(message);

    // Clean up
    session.close();
    connection.close();
}

From source file:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception//from w ww . ja  v  a 2 s. c o m
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}

From source file:org.soitoolkit.commons.studio.components.logger.impl.DefaultLogEventSender.java

protected void sendOneTextMessage(Session session, String queueName, String message) {

    MessageProducer publisher = null;

    try {/*from   w ww .  jav  a  2  s .com*/
        publisher = session.createProducer(session.createQueue(queueName));
        TextMessage textMessage = session.createTextMessage(message);
        publisher.send(textMessage);

    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (publisher != null)
                publisher.close();
        } catch (JMSException e) {
        }
    }
}