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.leveldb.test.ReplicatedLevelDBBrokerTest.java

private void sendMessage(BrokerService brokerService, String body) throws Exception {
    TransportConnector connector = brokerService.getTransportConnectors().get(0);
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri());
    Connection connection = factory.createConnection();
    try {/*ww w .ja  v a 2s  . com*/
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue("FOO"));
        producer.send(session.createTextMessage(body));
    } finally {
        connection.close();
    }
}

From source file:org.ahp.core.messaging.AhpJmsProducer.java

public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes,
        AhpJmsDestinationNames pAhpJmsDestinationNames) {
    Connection lConnection = null;
    Session lSession = null;/*from w  w w . j  a  va2  s .c  o  m*/
    try {
        lConnection = this.mJmsConnectionFactory.createConnection();
        lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        Destination lDestination = null;
        if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue))
            lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString());
        else
            lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString());
        MessageProducer lMessageProducer = lSession.createProducer(lDestination);
        lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //lMessageProducer.setTimeToLive( timeToLive );
        Message lTextMessage = lSession.createTextMessage(pTextMessage);
        LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString()
                + " TextMessage :: \n" + pTextMessage);
        lMessageProducer.send(lTextMessage);
        lSession.commit();
    } catch (JMSException exJms) {
        LOGGER.error("", exJms);
    } finally {
        try {
            lConnection.close();
        } catch (JMSException exJms) {
            LOGGER.error("", exJms);
        }
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to non-null value and
 * check the correct routing key comes as a JMS property for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from ww  w.ja  v a2  s . c om
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void queueRoutingKeyPropertyTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1");
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY),
                "RoutingKeyPropertyQueue", "Invalid value received for " + "routing key property.");
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to non-null value and
 * check the correct routing key comes as a JMS property for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from  w  w w . ja  v  a2s  .c o m
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1");
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY),
                "RoutingKeyPropertyTopic", "Invalid value received for " + "routing key property.");

    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//  w  ww.  java2  s . c o  m
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void queueRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java

/**
 * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to null value and check
 * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException//from  w  w w  .j a  v  a2s  .  c o m
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "topic" })
public void topicRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY);
    long sendCount = 10;
    final List<Message> messages = new ArrayList<>();
    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            messages.add(message);
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    for (Message message : messages) {
        Assert.assertEquals(
                message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null,
                "Invalid value received for routing key property.");

    }
}

From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java

public void process(MessageExchange exchange) throws Exception {
    Context context = (Context) pendingMessages.remove(exchange.getExchangeId());
    Message message = (Message) context.getProperty(Message.class.getName());
    Message response = null;/*from   www.  j  av  a 2  s.  com*/
    Connection connection = null;
    try {
        if (exchange.getStatus() == ExchangeStatus.DONE) {
            return;
        } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
            if (endpoint.isRollbackOnError()) {
                TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent()
                        .getComponentContext().getTransactionManager();
                tm.setRollbackOnly();
                return;
            } else if (exchange instanceof InOnly) {
                LOG.info("Exchange in error: " + exchange, exchange.getError());
                return;
            } else {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Exception error = exchange.getError();
                if (error == null) {
                    error = new Exception("Exchange in error");
                }
                response = session.createObjectMessage(error);
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        } else {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            response = fromNMSResponse(exchange, context, session);
            if (response != null) {
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    }
}

From source file:org.audit4j.core.AsyncAuditEngine.java

/**
 * Send./*w  w w.jav a  2 s  .  co m*/
 * 
 * @param t
 *            the t
 */
public void send(final Serializable t) {
    try {
        final MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        final ObjectMessage objectMessage = session.createObjectMessage();
        objectMessage.setObject(t);

        // Tell the producer to send the message
        System.out.println("Sent message: " + t.hashCode());
        producer.send(objectMessage);

    } catch (final Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}

From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImpl.java

@Override
public void sendFeedback(String channel, BuildFeedback feedback) {
    if (session == null) {
        /* OK, this shouldn't happen. How did we get the update notification if JMS is not up? */
        log.info("JMS not started, not sending feedback\n");
        return;//from  w  w w .j  a  v a2s  .  c  om
    }

    try {
        Destination topic = session.createQueue(channel);
        MessageProducer producer = session.createProducer(topic);
        ObjectMessage msg = session.createObjectMessage(feedback);
        producer.send(msg);
        producer.close();
        log.info("Build feedback sent\n");
    } catch (JMSException e) {
        log.error("Error delivering feedback", e);
    }
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {/*  www  .ja  v a  2  s . co m*/
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }
}