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.axis2.transport.jms.JMSMessageSender.java

/**
 * Perform actual send of JMS message to the Destination selected
 *
 * @param message the JMS message//www.ja v  a  2s  .com
 * @param msgCtx the Axis2 MessageContext
 */
public void send(Message message, MessageContext msgCtx) {

    Boolean jtaCommit = getBooleanProperty(msgCtx, BaseConstants.JTA_COMMIT_AFTER_SEND);
    Boolean rollbackOnly = getBooleanProperty(msgCtx, BaseConstants.SET_ROLLBACK_ONLY);
    Boolean persistent = getBooleanProperty(msgCtx, JMSConstants.JMS_DELIVERY_MODE);
    Integer priority = getIntegerProperty(msgCtx, JMSConstants.JMS_PRIORITY);
    Integer timeToLive = getIntegerProperty(msgCtx, JMSConstants.JMS_TIME_TO_LIVE);

    // Do not commit, if message is marked for rollback
    if (rollbackOnly != null && rollbackOnly) {
        jtaCommit = Boolean.FALSE;
    }

    if (persistent != null) {
        try {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer for PERSISTENT delivery", e);
        }
    }
    if (priority != null) {
        try {
            producer.setPriority(priority);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer priority to : " + priority, e);
        }
    }
    if (timeToLive != null) {
        try {
            producer.setTimeToLive(timeToLive);
        } catch (JMSException e) {
            handleException("Error setting JMS Producer TTL to : " + timeToLive, e);
        }
    }

    boolean sendingSuccessful = false;
    // perform actual message sending
    try {
        if (jmsSpec11 || isQueue == null) {
            producer.send(message);

        } else {
            if (isQueue) {
                ((QueueSender) producer).send(message);

            } else {
                ((TopicPublisher) producer).publish(message);
            }
        }

        // set the actual MessageID to the message context for use by any others down the line
        String msgId = null;
        try {
            msgId = message.getJMSMessageID();
            if (msgId != null) {
                msgCtx.setProperty(JMSConstants.JMS_MESSAGE_ID, msgId);
            }
        } catch (JMSException ignore) {
        }

        sendingSuccessful = true;

        if (log.isDebugEnabled()) {
            log.debug("Sent Message Context ID : " + msgCtx.getMessageID() + " with JMS Message ID : " + msgId
                    + " to destination : " + producer.getDestination());
        }

    } catch (JMSException e) {
        log.error("Error sending message with MessageContext ID : " + msgCtx.getMessageID()
                + " to destination : " + destination, e);

    } finally {

        if (jtaCommit != null) {

            UserTransaction ut = (UserTransaction) msgCtx.getProperty(BaseConstants.USER_TRANSACTION);
            if (ut != null) {

                try {
                    if (sendingSuccessful && jtaCommit) {
                        ut.commit();
                    } else {
                        ut.rollback();
                    }
                    msgCtx.removeProperty(BaseConstants.USER_TRANSACTION);

                    if (log.isDebugEnabled()) {
                        log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " JTA Transaction");
                    }

                } catch (Exception e) {
                    handleException("Error committing/rolling back JTA transaction after "
                            + "sending of message with MessageContext ID : " + msgCtx.getMessageID()
                            + " to destination : " + destination, e);
                }
            }

        } else {
            try {
                if (session.getTransacted()) {
                    if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) {
                        session.commit();
                    } else {
                        session.rollback();
                    }
                }

                if (log.isDebugEnabled()) {
                    log.debug((sendingSuccessful ? "Committed" : "Rolled back")
                            + " local (JMS Session) Transaction");
                }

            } catch (JMSException e) {
                handleException("Error committing/rolling back local (i.e. session) "
                        + "transaction after sending of message with MessageContext ID : "
                        + msgCtx.getMessageID() + " to destination : " + destination, e);
            }
        }
    }
}

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();/*  w w  w .  j  a  v  a2 s.com*/

    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.falcon.messaging.MessageProducer.java

/**
 * @param entityInstanceMessage - Accepts a Message to be send to JMS topic, creates a new
 *                  Topic based on topic name if it does not exist or else
 *                  existing topic with the same name is used to send the message.
 * @throws JMSException//w ww  .  j ava  2s . com
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to: {} milli-seconds", DEFAULT_TTL);
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));
}

From source file:org.apache.ivory.messaging.MessageProducer.java

/**
 * //  www  . j  a  v a2 s  .  co  m
 * @param arguments
 *            - Accepts a Message to be send to JMS topic, creates a new
 *            Topic based on topic name if it does not exist or else
 *            existing topic with the same name is used to send the message.
 * @throws JMSException
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to:" + DEFAULT_TTL + " milli-seconds");
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));

}

From source file:org.apache.jmeter.protocol.jms.sampler.PublisherSampler.java

/**
 * The implementation will publish n messages within a for loop. Once n
 * messages are published, it sets the attributes of SampleResult.
 *
 * @return the populated sample result//from   ww w.j  a  va  2s.c o m
 */
@Override
public SampleResult sample() {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());
    result.setSuccessful(false); // Assume it will fail
    result.setResponseCode("000"); // ditto $NON-NLS-1$
    if (publisher == null) {
        try {
            initClient();
        } catch (JMSException e) {
            result.setResponseMessage(e.toString());
            return result;
        } catch (NamingException e) {
            result.setResponseMessage(e.toString());
            return result;
        }
    }
    StringBuilder buffer = new StringBuilder();
    StringBuilder propBuffer = new StringBuilder();
    int loop = getIterationCount();
    result.sampleStart();
    String type = getMessageChoice();

    try {
        Map<String, Object> msgProperties = getJMSProperties().getJmsPropertysAsMap();
        int deliveryMode = getUseNonPersistentDelivery() ? DeliveryMode.NON_PERSISTENT
                : DeliveryMode.PERSISTENT;
        int priority = Integer.parseInt(getPriority());
        long expiration = Long.parseLong(getExpiration());

        for (int idx = 0; idx < loop; idx++) {
            if (JMSPublisherGui.TEXT_MSG_RSC.equals(type)) {
                String tmsg = getMessageContent();
                Message msg = publisher.publish(tmsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                buffer.append(tmsg);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.MAP_MSG_RSC.equals(type)) {
                Map<String, Object> m = getMapContent();
                Message msg = publisher.publish(m, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.OBJECT_MSG_RSC.equals(type)) {
                Serializable omsg = getObjectContent();
                Message msg = publisher.publish(omsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else if (JMSPublisherGui.BYTES_MSG_RSC.equals(type)) {
                byte[] bmsg = getBytesContent();
                Message msg = publisher.publish(bmsg, getDestination(), msgProperties, deliveryMode, priority,
                        expiration);
                Utils.messageProperties(propBuffer, msg);
            } else {
                throw new JMSException(type + " is not recognised");
            }
        }
        result.setResponseCodeOK();
        result.setResponseMessage(loop + " messages published");
        result.setSuccessful(true);
        result.setSamplerData(buffer.toString());
        result.setSampleCount(loop);
        result.setRequestHeaders(propBuffer.toString());
    } catch (Exception e) {
        result.setResponseMessage(e.toString());
    } finally {
        result.sampleEnd();
    }
    return result;
}

From source file:org.apache.ode.extension.jmseventlistener.JmsBpelEventListener.java

public void startup(Properties configProperties) {
    if (configProperties == null) {
        logger.info("No configuration properties given. Initialization aborted.");
        return;/*from   w  w  w  . j  ava2  s . co  m*/
    }
    topicName = configProperties.getProperty(TOPIC_NAME_KEY, "org.apache.ode.events");
    url = configProperties.getProperty(MQ_URL_KEY, "tcp://localhost:61616");

    try {
        factory = new ActiveMQConnectionFactory(url);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        publisher = session.createProducer(topic);
        publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
        initialized = true;
    } catch (JMSException e) {
        logger.error("Initialization failed.", e);
    }
    logger.info("JMS BPEL event has been started.");
}

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

public void createProducer(final CreateProducerCommand command) {
    try {/*from  ww w .  j a  v  a2  s  .  c  om*/
        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.codehaus.stomp.jms.StompSession.java

protected int getDeliveryMode(Map headers) throws JMSException {
    Object o = headers.remove(Stomp.Headers.Send.PERSISTENT);
    if (o != null) {
        return "true".equals(o) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
    } else {/*from w w w .  ja  v a2  s  .  c o  m*/
        return producer.getDeliveryMode();
    }
}

From source file:org.codehaus.stomp.StompTest.java

public void testSendMessageWithStandardHeaders() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);/*w w w. j  a  v a  2  s  . co m*/

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame = "SEND\n" + "correlation-id:c123\n" + "priority:3\n" + "type:t345\n" + "JMSXGroupID:abc\n"
            + "foo:abc\n" + "bar:123\n" + "destination:/queue/" + getQueueName() + "\n\n" + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    Assert.assertEquals("JMSCorrelationID", "c123", message.getJMSCorrelationID());
    Assert.assertEquals("getJMSType", "t345", message.getJMSType());
    Assert.assertEquals("getJMSPriority", 3, message.getJMSPriority());
    Assert.assertEquals(DeliveryMode.PERSISTENT, message.getJMSDeliveryMode());
    Assert.assertEquals("foo", "abc", message.getStringProperty("foo"));
    Assert.assertEquals("bar", "123", message.getStringProperty("bar"));

    Assert.assertEquals("JMSXGroupID", "abc", message.getStringProperty("JMSXGroupID"));
    ActiveMQTextMessage amqMessage = (ActiveMQTextMessage) message;
    Assert.assertEquals("GroupID", "abc", amqMessage.getGroupID());
}

From source file:org.dhatim.routing.jms.JMSRouter.java

/**
 * Sets the following MessageProducer properties:
 * <lu>/*from  w  w  w .ja  v a 2s  . c  o  m*/
 *    <li>TimeToLive
 *    <li>Priority
 *    <li>DeliveryMode
 * </lu>
 * <p>
 * Subclasses may override this behaviour.
 */
protected void setMessageProducerProperties() throws SmooksConfigurationException {
    try {
        msgProducer.setTimeToLive(jmsProperties.getTimeToLive());
        msgProducer.setPriority(jmsProperties.getPriority());

        final int deliveryModeInt = "non-persistent".equals(jmsProperties.getDeliveryMode())
                ? DeliveryMode.NON_PERSISTENT
                : DeliveryMode.PERSISTENT;
        msgProducer.setDeliveryMode(deliveryModeInt);
    } catch (JMSException e) {
        final String errorMsg = "JMSException while trying to set JMS Header Fields";
        throw new SmooksConfigurationException(errorMsg, e);
    }
}