Example usage for javax.jms DeliveryMode PERSISTENT

List of usage examples for javax.jms DeliveryMode PERSISTENT

Introduction

In this page you can find the example usage for javax.jms DeliveryMode PERSISTENT.

Prototype

int PERSISTENT

To view the source code for javax.jms DeliveryMode PERSISTENT.

Click Source Link

Document

This delivery mode instructs the JMS provider to log the message to stable storage as part of the client's send operation.

Usage

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

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);/* w w  w. j av a 2 s.  c o m*/

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

From source file:org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest.java

protected void setUp() throws Exception {
    super.setUp();

    connectionFactory = createConnectionFactory();

    sendConnection = createSendConnection();
    sendConnection.start();//from  ww  w .j a  v a 2  s .com

    receiveConnection = createReceiveConnection();
    receiveConnection.start();

    LOG.info("Created sendConnection: " + sendConnection);
    LOG.info("Created receiveConnection: " + receiveConnection);

    session = createSendSession(sendConnection);
    receiveSession = createReceiveSession(receiveConnection);

    LOG.info("Created sendSession: " + session);
    LOG.info("Created receiveSession: " + receiveSession);

    producer = session.createProducer(null);
    producer.setDeliveryMode(deliveryMode);

    LOG.info("Created producer: " + producer + " delivery mode = "
            + (deliveryMode == DeliveryMode.PERSISTENT ? "PERSISTENT" : "NON_PERSISTENT"));

    if (topic) {
        consumerDestination = session.createTopic(getConsumerSubject());
        producerDestination = session.createTopic(getProducerSubject());
    } else {
        consumerDestination = session.createQueue(getConsumerSubject());
        producerDestination = session.createQueue(getProducerSubject());
    }

    LOG.info("Created  consumer destination: " + consumerDestination + " of type: "
            + consumerDestination.getClass());
    LOG.info("Created  producer destination: " + producerDestination + " of type: "
            + producerDestination.getClass());

    consumer = createConsumer(receiveSession, consumerDestination);
    consumer.setMessageListener(this);

    LOG.info("Started connections");
}

From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

protected Message createMessage(ProducerInfo producerInfo, ActiveMQDestination destination, int deliveryMode) {
    Message message = createMessage(producerInfo, destination);
    message.setPersistent(deliveryMode == DeliveryMode.PERSISTENT);
    return message;
}

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  ww.  jav  a  2s . c o m
    }
    connection.close();
}

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(// ww w  .  ja va 2  s . c o  m
            "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.ConcurrentProducerDurableConsumerTest.java

/**
 * @return max and ave send time//from   w ww .ja va 2 s  . c  om
 * @throws Exception
 */
private double[] produceMessages(Destination destination, final int toSend, final int numIterations,
        Session session, MessageProducer producer, Object addConsumerSignal) throws Exception {
    long start;
    long count = 0;
    double batchMax = 0, max = 0, sum = 0;
    for (int i = 0; i < numIterations; i++) {
        start = System.currentTimeMillis();
        for (int j = 0; j < toSend; j++) {
            long singleSendstart = System.currentTimeMillis();
            TextMessage msg = createTextMessage(session, "" + j);
            // rotate
            int priority = ((int) count % 10);
            producer.send(msg, DeliveryMode.PERSISTENT, priority, 0);
            max = Math.max(max, (System.currentTimeMillis() - singleSendstart));
            if (++count % 500 == 0) {
                if (addConsumerSignal != null) {
                    synchronized (addConsumerSignal) {
                        addConsumerSignal.notifyAll();
                        LOG.info("Signalled add consumer");
                    }
                }
            }
            ;
            if (count % 5000 == 0) {
                LOG.info("Sent " + count + ", singleSendMax:" + max);
            }

        }
        long duration = System.currentTimeMillis() - start;
        batchMax = Math.max(batchMax, duration);
        sum += duration;
        LOG.info("Iteration " + i + ", sent " + toSend + ", time: " + duration + ", batchMax:" + batchMax
                + ", singleSendMax:" + max);
    }

    LOG.info("Sent: " + toSend * numIterations + ", batchMax: " + batchMax + " singleSendMax: " + max);
    return new double[] { batchMax, sum / numIterations };
}

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

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridgeBrokers(SPOKE, HUB);//ww w .  j  ava  2s.  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);/*from   w w  w .  j a  v a  2 s .com*/
    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.axis2.transport.jms.JMSMessageReceiver.java

/**
 * Process a new message received//from   ww w .  j  a  v  a2 s .co m
 *
 * @param message the JMS message received
 * @param ut      UserTransaction which was used to receive the message
 * @return true if caller should commit
 */
public boolean onMessage(Message message, UserTransaction ut) {

    try {
        if (log.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();
            sb.append("Received new JMS message for service :").append(endpoint.getServiceName());
            sb.append("\nDestination    : ").append(message.getJMSDestination());
            sb.append("\nMessage ID     : ").append(message.getJMSMessageID());
            sb.append("\nCorrelation ID : ").append(message.getJMSCorrelationID());
            sb.append("\nReplyTo        : ").append(message.getJMSReplyTo());
            sb.append("\nRedelivery ?   : ").append(message.getJMSRedelivered());
            sb.append("\nPriority       : ").append(message.getJMSPriority());
            sb.append("\nExpiration     : ").append(message.getJMSExpiration());
            sb.append("\nTimestamp      : ").append(message.getJMSTimestamp());
            sb.append("\nMessage Type   : ").append(message.getJMSType());
            sb.append("\nPersistent ?   : ").append(DeliveryMode.PERSISTENT == message.getJMSDeliveryMode());

            log.debug(sb.toString());
            if (log.isTraceEnabled() && message instanceof TextMessage) {
                log.trace("\nMessage : " + ((TextMessage) message).getText());
            }
        }
    } catch (JMSException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error reading JMS message headers for debug logging", e);
        }
    }

    // update transport level metrics
    try {
        metrics.incrementBytesReceived(JMSUtils.getMessageSize(message));
    } catch (JMSException e) {
        log.warn("Error reading JMS message size to update transport metrics", e);
    }

    // has this message already expired? expiration time == 0 means never expires
    // TODO: explain why this is necessary; normally it is the responsibility of the provider to handle message expiration
    try {
        long expiryTime = message.getJMSExpiration();
        if (expiryTime > 0 && System.currentTimeMillis() > expiryTime) {
            if (log.isDebugEnabled()) {
                log.debug("Discard expired message with ID : " + message.getJMSMessageID());
            }
            return true;
        }
    } catch (JMSException ignore) {
    }

    boolean successful = false;
    try {
        successful = processThoughEngine(message, ut);

    } catch (JMSException e) {
        log.error("JMS Exception encountered while processing", e);
    } catch (AxisFault e) {
        log.error("Axis fault processing message", e);
    } catch (Exception e) {
        log.error("Unknown error processing message", e);

    } finally {
        if (successful) {
            metrics.incrementMessagesReceived();
        } else {
            metrics.incrementFaultsReceiving();
        }
    }

    return successful;
}