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.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private String requestParse(final Long documentId, final String content) {
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;//from w ww . j a va2s . com

    // set up JMS connection, session, consumer, producer
    try {
        connection = this.connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.requestQueue);

        logger.info("Sending parse request, document ID: " + documentId);
        final TextMessage textMessage = session.createTextMessage(content);
        textMessage.setJMSReplyTo(this.responseQueue);
        textMessage.setLongProperty(DOCUMENT_ID, documentId);

        producer.send(textMessage);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (producer != null) {
                producer.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    return content;
}

From source file:org.sofun.core.messaging.SofunMessagingServiceImpl.java

@Override
public void sendMessage(Serializable message, String destination) {

    Connection connection = null;
    Session session = null;
    MessageProducer sender = null;/* w  w w . j  a va  2 s.c o m*/
    Queue q = getQueueFor(destination);
    if (q == null) {
        log.error("Cannot find associated queue for destination=" + destination);
    }
    try {
        connection = connFactory.createConnection(SofunMessagingCredentials.USERNAME,
                SofunMessagingCredentials.PASSWORD);
        session = connection.createSession(true, 0);
        sender = session.createProducer(q);
        ObjectMessage msg = session.createObjectMessage(message);
        sender.send(msg);
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        try {
            if (sender != null) {
                sender.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }

    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

protected Message messageSend(SubmitContext submitContext, Request request, Session session, Hermes hermes,
        Queue queueSend, Destination replyToDestination) throws JMSException {
    MessageProducer messageProducer = session.createProducer(queueSend);
    Message messageSend = createMessage(submitContext, request, session);
    return send(submitContext, request, hermes, messageProducer, messageSend, replyToDestination);
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

protected Message messagePublish(SubmitContext submitContext, Request request, Session topicSession,
        Hermes hermes, Topic topicPublish, Destination replyToDestination) throws JMSException {
    MessageProducer topicPublisher = topicSession.createProducer(topicPublish);
    Message messagePublish = createMessage(submitContext, request, topicSession);
    return send(submitContext, request, hermes, topicPublisher, messagePublish, replyToDestination);
}

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. j av  a 2s. c  om
        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:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;/*from  w  w  w .j a va 2 s. c  o  m*/
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

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

@Test(timeout = 300000)
public void testDurableWithNoMessageAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);//from w ww  . j a va 2 s.  c  om

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all messages
    for (int i = 0; i < messageCount.get(); i++) {
        durable.receive();
    }

    durable.close();

    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Should have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

    assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length);

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

    assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length);

    assertNull(durable2.receive(500));
}

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

@Test(timeout = 300000)
public void testDurableWithOnePendingAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);//from   w ww.  j a v  a  2  s. c o m

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all but 1 message
    for (int i = 0; i < messageCount.get() - 1; i++) {
        durable.receive();
    }

    durable.close();

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertFalse("Should not have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }, 5000, 500));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

    assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length);

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

    assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length);

    assertNotNull(durable2.receive(5000));
}

From source file:org.codehaus.stomp.jms.StompSession.java

public StompSession(InitialContext initialContext, ProtocolConverter protocolConverter, Session session,
        Connection connection) throws JMSException {
    this.initialContext = initialContext;
    this.protocolConverter = protocolConverter;
    this.session = session;
    this.connection = connection;
    this.producer = session.createProducer(null);
}

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

private void sendMessage(Object o) {

    Session session = null;
    MessageProducer producer = null;/*from  w  w  w .  ja v a2s . c  o m*/
    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);
    }
}