Example usage for javax.jms Session createProducer

List of usage examples for javax.jms Session createProducer

Introduction

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

Prototype


MessageProducer createProducer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageProducer to send messages to the specified destination.

Usage

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();//from   w w  w  .ja  va 2  s.c  om

    // 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:org.wildfly.camel.test.jms.TransactedJMSIntegrationTest.java

private void sendMessage(Connection connection, String jndiName, String message) throws Exception {
    InitialContext initialctx = new InitialContext();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = (Destination) initialctx.lookup(jndiName);
    MessageProducer producer = session.createProducer(destination);
    TextMessage msg = session.createTextMessage(message);
    producer.send(msg);/*from   w w w.  j  a  va2  s .c  o m*/
    connection.start();
}

From source file:org.jbpm.ejb.impl.CommandListenerBean.java

private void sendResult(Serializable result, Destination destination, String correlationId)
        throws JMSException {
    log.debug("sending result " + result + " to " + destination);
    Session jmsSession = createSession();
    try {// ww w .  j a v a2s . com
        Message resultMessage = jmsSession.createObjectMessage(result);
        resultMessage.setJMSCorrelationID(correlationId);
        jmsSession.createProducer(destination).send(resultMessage);
    } finally {
        jmsSession.close();
    }
}

From source file:org.apache.juddi.subscription.notify.AMQPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {
    Connection connection = null;
    Context context = null;/* ww  w. j a va  2 s.  co m*/
    boolean success = false;
    String err = null;
    try {
        if (destination != null && exchangeType != null && exchangeName != null) {
            log.info("Sending notification AMQP to " + destination);
            Properties properties = new Properties();

            properties.put("java.naming.factory.initial",
                    "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
            properties.put("connectionfactory.qpidConnectionfactory", destination);
            properties.put("destination." + exchangeName, exchangeType);

            context = new InitialContext(properties);

            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory");
            connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destinationLocal = (Destination) context.lookup(exchangeName);

            MessageProducer messageProducer = session.createProducer(destinationLocal);

            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            TextMessage message = session.createTextMessage(subscriptionResultXML);
            messageProducer.send(message);
            success = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Error deliverying AMQP subscription " + e.getMessage());
        log.debug("Error deliverying AMQP subscription " + e.getMessage(), e);
        err = e.getMessage();

    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException ex) {
            log.error(null, ex);
        }
        try {
            if (context != null) {
                context.close();
            }
        } catch (NamingException ex) {
            log.error(null, ex);
        }
    }
    if (!success) {
        throw new DispositionReportFaultMessage(err, null);
    }
    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}

From source file:com.fusesource.forge.jmstest.benchmark.command.transport.JMSCommandTransport.java

public void sendCommand(BenchmarkCommand command) {
    log.debug("Sending command message: " + command.toString());
    if (getConnection() != null) {
        try {//from  w w w.jav a  2 s  .  c om
            Session session = getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination dest = getJmsDestinationProvider().getDestination(session, getDestinationName());
            MessageProducer producer = session.createProducer(dest);
            producer.send(session.createObjectMessage((Serializable) command));
            session.close();
        } catch (Exception je) {
            log().error("Could not send Command " + command.toString() + ".", je);
        }
    } else {
        log.warn("Command not sent as JMS connection is not established.");
    }
}

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 ww .j  a  va 2 s  .  co  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:org.jbpm.ejb.CommandListenerBean.java

private void sendResult(Serializable result, Destination destination, String correlationId)
        throws JMSException {
    if (log.isDebugEnabled())
        log.debug("sending " + result + " to " + destination);

    Connection jmsConnection = jmsConnectionFactory.createConnection();
    try {//from  ww  w . j  ava2  s .  co  m
        /*
         * if the connection supports xa, the session will be transacted, else the session will
         * auto acknowledge; in either case no explicit transaction control must be performed -
         * see ejb 2.1 - 17.3.5
         */
        Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Message resultMessage = jmsSession.createObjectMessage(result);
        resultMessage.setJMSCorrelationID(correlationId);
        MessageProducer producer = jmsSession.createProducer(destination);
        producer.send(resultMessage);
    } finally {
        // there is no need to close the sessions and producers of a closed connection
        // http://download.oracle.com/javaee/1.4/api/javax/jms/Connection.html#close()
        try {
            jmsConnection.close();
        } catch (JMSException e) {
            log.warn("failed to close jms connection", e);
        }
    }
}

From source file:ubic.gemma.job.grid.util.JMSBrokerMonitorImpl.java

private MapMessage sendTaskSubmissionQueueDiagnosticMessage() throws JMSException {
    MapMessage reply = jmsTemplate.execute(new SessionCallback<MapMessage>() {
        @Override//w  w  w  .  j  a  va 2  s.c  om
        public MapMessage doInJms(Session session) throws JMSException {
            Queue replyTo = session.createTemporaryQueue();
            Message message = session.createMessage();
            message.setJMSReplyTo(replyTo);
            Queue queryQueue = session.createQueue("ActiveMQ.Statistics.Destination.tasks.submit");
            MessageProducer producer = session.createProducer(queryQueue);
            MessageConsumer consumer = session.createConsumer(replyTo);
            producer.send(message);
            return (MapMessage) consumer.receive(5000);
        }
    }, true);
    return reply;
}

From source file:io.fabric8.mq.controller.coordination.BrokerJMXPropertiesTest.java

@Test
public void testNumberOfTopicProducers() throws Exception {
    String uriString = brokerService.getDefaultSocketURIString();
    ConnectionFactory factory = new ActiveMQConnectionFactory(uriString);
    Connection connection = factory.createConnection();
    connection.start();//from ww  w  . j  av a2s.  c  om
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    int numberOfProducers = 10;
    List<MessageProducer> producers = new ArrayList<>();
    Topic topic = session.createTopic("topic.test");
    for (int i = 0; i < numberOfProducers; i++) {

        MessageProducer producer = session.createProducer(topic);
        producers.add(producer);

    }
    ObjectName root = BrokerJmxUtils.getRoot(client);
    Assert.assertNotNull(root);
    List<ObjectName> list = BrokerJmxUtils.getDestinations(client, root, "Topic");
    Assert.assertNotNull(list);
    Assert.assertFalse(list.isEmpty());
    ObjectName result = null;
    for (ObjectName objectName : list) {
        if (objectName.getKeyProperty("destinationName").equals("topic.test")) {
            result = objectName;
        }
    }
    Assert.assertNotNull(result);
    Object producerCount = BrokerJmxUtils.getAttribute(client, result, "ProducerCount");
    Assert.assertNotNull(producerCount);
    int pc = Integer.parseInt(producerCount.toString());
    Assert.assertEquals(pc, numberOfProducers);
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void sendMessages(Destination destination, int count) throws Exception {
    Connection connection = cf.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    for (int i = 0; i < count; ++i) {
        TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination);
        producer.send(message);//from   w  w w .  j a  va2  s  .  co m
    }
    connection.close();
}