Example usage for javax.jms MessageProducer setDeliveryMode

List of usage examples for javax.jms MessageProducer setDeliveryMode

Introduction

In this page you can find the example usage for javax.jms MessageProducer setDeliveryMode.

Prototype


void setDeliveryMode(int deliveryMode) throws JMSException;

Source Link

Document

Sets the producer's default delivery mode.

Usage

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

public void x_testSendWithInactiveAndActiveConsumers() throws Exception {
    Destination destination = createDestination();
    ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final int toSend = 100;
    final int numIterations = 5;

    double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    startConsumers(factory, destination);
    LOG.info("Activated consumer");

    double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1]
            + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]));
    final int reasonableMultiplier = 15; // not so reasonable but improving
    assertTrue(/*from w  w w  . ja v a2 s .  com*/
            "max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: "
                    + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]),
            withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier);

    final int toReceive = toSend * numIterations * consumerCount * 2;
    Wait.waitFor(new Wait.Condition() {
        public boolean isSatisified() throws Exception {
            LOG.info("count: " + allMessagesList.getMessageCount());
            return toReceive == allMessagesList.getMessageCount();
        }
    }, 60 * 1000);

    assertEquals("got all messages", toReceive, allMessagesList.getMessageCount());
}

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

private MessageProducer createMessageProducer(Session session, Destination destination) throws JMSException {
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    return producer;
}

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

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridgeBrokers(SPOKE, HUB);/*from  ww w. j av  a 2  s  .c o m*/

    startAllBrokers();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getVmConnectorURI();
    URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName);
    remoteConsumer.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            try {
                TextMessage textMsg = (TextMessage) msg;
                receivedMsgs++;
                LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    // allow subscription information to flow back to Spoke
    sleep(1000);

    // Setup producer
    MessageProducer localProducer = sesHub.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        sleep(50);
        if (i == 50 || i == 150) {
            if (simulateStalledNetwork) {
                socketProxy.pause();
            } else {
                socketProxy.close();
            }
            networkDownTimeStart = System.currentTimeMillis();
        } else if (networkDownTimeStart > 0) {
            // restart after NETWORK_DOWN_TIME seconds
            sleep(NETWORK_DOWN_TIME);
            networkDownTimeStart = 0;
            if (simulateStalledNetwork) {
                socketProxy.goOn();
            } else {
                socketProxy.reopen();
            }
        } else {
            // slow message production to allow bridge to recover and limit message duplication
            sleep(500);
        }
        Message test = sesHub.createTextMessage("test-" + i);
        localProducer.send(test);
    }

    LOG.info("waiting for messages to flow");
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return receivedMsgs >= MESSAGE_COUNT;
        }
    });

    assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs,
            MESSAGE_COUNT <= receivedMsgs);
    brokers.get(HUB).broker.deleteAllMessages();
    brokers.get(SPOKE).broker.deleteAllMessages();
    conHub.close();
    conSpoke.close();
}

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

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridge(SPOKE, HUB);/*  ww  w. j ava 2 s  .co m*/
    startAllBrokers();

    verifyDuplexBridgeMbean();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName);
    sleep(1000);
    remoteConsumer.close();

    // Setup producer
    MessageProducer localProducer = sesSpoke.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final String payloadString = new String(new byte[10 * 1024]);
    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        Message test = sesSpoke.createTextMessage("test-" + i);
        test.setStringProperty("payload", payloadString);
        localProducer.send(test);
    }
    localProducer.close();

    final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false";
    for (int i = 0; i < 2; i++) {
        brokers.get(SPOKE).broker.stop();
        sleep(1000);
        createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options));
        bridge(SPOKE, HUB);
        brokers.get(SPOKE).broker.start();
        LOG.info("restarted spoke..:" + i);

        assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisified() throws Exception {
                return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2);
            }
        }));
    }
}

From source file:org.apache.falcon.messaging.JMSMessageConsumerTest.java

public void sendMessages(String topic, WorkflowExecutionContext.Type type, boolean isFalconWF)
        throws JMSException, FalconException, IOException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();//from w w  w.jav  a  2 s . c o m

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(topic);
    javax.jms.MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    for (int i = 0; i < 5; i++) {
        Message message = null;

        switch (type) {
        case POST_PROCESSING:
            message = getMockFalconMessage(i, session);
            break;
        case WORKFLOW_JOB:
            message = getMockOozieMessage(i, session, isFalconWF);
            break;
        case COORDINATOR_ACTION:
            message = getMockOozieCoordMessage(i, session, isFalconWF);
        default:
            break;
        }
        Log.debug("Sending:" + message);
        producer.send(message);
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void createProducer(final CreateProducerCommand command) {
    try {//from ww  w. j  a  va  2s . c o m
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            final Destination destination;
            if (command.isTopic()) {
                destination = session.createTopic(command.getDestinationName());
            } else {
                destination = session.createQueue(command.getDestinationName());
            }

            final MessageProducer jmsProducer = session.createProducer(destination);

            if (command.getPriority() != -1) {
                jmsProducer.setPriority(command.getPriority());
            }
            if (command.getTimeToLive() > 0) {
                jmsProducer.setTimeToLive(command.getTimeToLive());
            }

            if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT
                    || command.getDeliveryMode() == DeliveryMode.PERSISTENT) {
                jmsProducer.setDeliveryMode(command.getDeliveryMode());
            }

            addProducer(command.getParticipantName(), jmsProducer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new producer: " + command, jmse);
    }
}

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

/**
 * Send.//w w  w . ja va 2 s .  c  o 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.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * {@inheritDoc}//from  w w  w.  j a va 2s .  c  o m
 * 
 */
@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.mot.common.mq.ActiveMQFactory.java

/**
 * Create a new message producer onto a particular destination
 * /* w ww .j a  v  a2s .  c om*/
 * @param destination - destination queue/topic object
 * @return the message producer object
 */
public MessageProducer createMessageProducer(String channel, long ttl, boolean persistent) {
    Destination destination = createDestination(channel);
    MessageProducer msg = null;

    try {
        msg = session.createProducer(destination);

        msg.setTimeToLive(ttl);

        if (persistent) {
            msg.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            msg.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }

    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msg;
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public void send(Scenario scenario) throws Exception {
    Connection connection = null;
    try {/*w  w  w . j  a  v  a2 s . c  om*/
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createInputDestination(session, scenario);
            MessageProducer producer = null;
            try {
                producer = session.createProducer(destination);
                if (scenario.isPersistent()) {
                    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                }
                scenario.send(session, producer);
            } finally {
                if (producer != null) {
                    producer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}