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:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * {@inheritDoc}/*from  ww w  .  j  a  va2s.  c om*/
 * 
 */
@Override
public String[] executeInternal(final TaskExecutionEnv env, final SendType config,
        final Map<String, Properties> idPropertyMap)
        throws TaskExecutionException, BlackboardAccessException, RecordFilterNotFoundException {
    Connection connection = null;
    Session session = null;
    try {
        // get cached connection, if do not cache connections -> socket error when many records pushed
        connection = env.getServices().getBrokerConnections().getConnection(config, true);
        connection.start();
        session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        final Destination destination = session.createQueue(config.getQueue());
        final MessageProducer producer = session.createProducer(destination);
        if (config.isPersistentDelivery()) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

        final Iterator<Entry<String, Properties>> entries = idPropertyMap.entrySet().iterator();
        while (entries.hasNext()) {
            final Entry<String, Properties> entry = entries.next();
            // get message record, optionally a filtered copy.
            final Record record = createMessageRecord(entry.getKey(), config, env);
            // prepare queue message. messages are actually sent on session.commit() below.
            producer.send(createMessage(config, record, entry.getValue(), session));
        }

        // we must commit here so that the message consumer find the correct record version in storages.
        env.getBlackboard().commit();
        env.setCommitRequired(false);
        // finally send the messages.
        session.commit();

        return idPropertyMap.keySet().toArray(new String[idPropertyMap.size()]);
    } catch (final Throwable e) {
        _log.error(msg("Error"), e);
        rollbackQuietly(session);
        throw new TaskExecutionException(e);
    } finally {
        closeQuietly(session);
        closeQuietly(connection);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();/*w ww  . j  av a 2 s  . co  m*/

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

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

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

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();//from   w  w  w .j a  v  a2s  . c  o m
    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();
}

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();/*from  w w  w .  j  av a  2s.co m*/
    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.springframework.jms.core.JmsTemplate.java

/**
 * Create a JMS MessageProducer for the given Session and Destination.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to create a MessageProducer for
 * @param destination the JMS Destination to create a MessageProducer for
 * @return the new JMS MessageProducer//w ww .  jav a2s .co  m
 * @throws JMSException if thrown by JMS API methods
 */
protected MessageProducer createProducer(Session session, Destination destination) throws JMSException {
    return session.createProducer(destination);
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();/*from w  ww  .  j  a va2s  .  c om*/

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();

    List<Message> messages = new ArrayList<Message>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }

    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }

    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > 200);

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

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

@Test
public void testQueueLargeMessageSizeTX() throws Exception {

    ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf;
    acf.setMinLargeMessageSize(1000);/*from  ww w .  j a  v a  2 s . c om*/
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

    String testText = StringUtils.repeat("t", 2000);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText);
    for (int i = 0; i < 10; i++) {
        producer.send(message);
    }

    //not commited so should be 0
    verifyPendingStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);

    session.commit();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);

    connection.close();

    this.killServer();
    this.restartServer();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
}

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

@Test
public void testRollback() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/*from w w  w .j a va  2 s.  c om*/

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue holdKahaDb = session.createQueue("holdKahaDb");
    MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb);
    TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    Queue queue = session.createQueue("test");
    produce(connection, queue, 100, 512 * 1024);
    session.rollback();
    produce(connection, queue, 100, 512 * 1024);

    System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
            getQueueSize(holdKahaDb.getQueueName())));
    purgeQueue(queue.getQueueName());

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    // force gc
    broker.getPersistenceAdapter().checkpoint(true);

    connection.close();
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();
    broker.waitUntilStarted();

    // no sign of the test queue on recovery, rollback is the default for any inflight
    // this test serves as a sanity check on existing behaviour
    try {
        getQueueSize(holdKahaDb.getQueueName());
        fail("expect InstanceNotFoundException");
    } catch (UndeclaredThrowableException expected) {
        assertTrue(expected.getCause() instanceof InstanceNotFoundException);
    }
}

From source file:eu.domibus.submission.jms.BackendJMSImpl.java

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 *//*from  ww  w.  j a  va 2 s. c  o m*/
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

From source file:me.norman.maurer.james.queue.HornetQMailQueue.java

@Override
protected void produceMail(Session session, Map<String, Object> props, int msgPrio, Mail mail)
        throws JMSException, MessagingException, IOException {
    MessageProducer producer = null;/*from  w  w w . j  ava  2  s.  c  o  m*/
    try {
        BytesMessage message = session.createBytesMessage();
        Iterator<String> propIt = props.keySet().iterator();
        while (propIt.hasNext()) {
            String key = propIt.next();
            message.setObjectProperty(key, props.get(key));
        }
        // set the stream to read frome
        message.setObjectProperty("JMS_HQ_InputStream",
                new BufferedInputStream(new MimeMessageInputStream(mail.getMessage())));
        Queue q = session.createQueue(queuename);
        producer = session.createProducer(q);
        producer.send(message, Message.DEFAULT_DELIVERY_MODE, msgPrio, Message.DEFAULT_TIME_TO_LIVE);
    } finally {
        if (producer != null) {
            producer.close();
        }
    }
}