Example usage for javax.jms Session SESSION_TRANSACTED

List of usage examples for javax.jms Session SESSION_TRANSACTED

Introduction

In this page you can find the example usage for javax.jms Session SESSION_TRANSACTED.

Prototype

int SESSION_TRANSACTED

To view the source code for javax.jms Session SESSION_TRANSACTED.

Click Source Link

Document

This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

Usage

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;/*from w w w  .  j  a  v  a2 s  .c o  m*/
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

From source file:org.apache.camel.component.jms.JmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for request/response using a request timeout value
 *//* w  w w .  j  a v a  2  s  . c o m*/
public JmsOperations createInOutTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination,
        long requestTimeout) {
    JmsOperations answer = createInOnlyTemplate(endpoint, pubSubDomain, destination);
    if (answer instanceof JmsTemplate && requestTimeout > 0) {
        JmsTemplate jmsTemplate = (JmsTemplate) answer;
        jmsTemplate.setExplicitQosEnabled(true);
        if (timeToLive < 0) {
            // If TTL not specified, then default to
            jmsTemplate.setTimeToLive(requestTimeout);
        }
        jmsTemplate.setSessionTransacted(isTransactedInOut());
        if (isTransactedInOut()) {
            jmsTemplate.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
        } else {
            if (acknowledgementMode >= 0) {
                jmsTemplate.setSessionAcknowledgeMode(acknowledgementMode);
            } else if (acknowledgementModeName != null) {
                jmsTemplate.setSessionAcknowledgeModeName(acknowledgementModeName);
            } else {
                // default to AUTO
                jmsTemplate.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
            }
        }
    }
    return answer;
}

From source file:org.apache.camel.component.jms.JmsConfiguration.java

/**
 * Creates a {@link JmsOperations} object used for one way messaging
 *///from w  w w  . j  a  va  2  s.c o m
public JmsOperations createInOnlyTemplate(JmsEndpoint endpoint, boolean pubSubDomain, String destination) {
    if (jmsOperations != null) {
        return jmsOperations;
    }

    ConnectionFactory factory = getTemplateConnectionFactory();
    JmsTemplate template = new CamelJmsTemplate(this, factory);

    template.setPubSubDomain(pubSubDomain);
    if (destinationResolver != null) {
        template.setDestinationResolver(destinationResolver);
        if (endpoint instanceof DestinationEndpoint) {
            LOG.debug(
                    "You are overloading the destinationResolver property on a DestinationEndpoint; are you sure you want to do that?");
        }
    } else if (endpoint instanceof DestinationEndpoint) {
        DestinationEndpoint destinationEndpoint = (DestinationEndpoint) endpoint;
        template.setDestinationResolver(createDestinationResolver(destinationEndpoint));
    }
    template.setDefaultDestinationName(destination);

    template.setExplicitQosEnabled(isExplicitQosEnabled());
    template.setDeliveryPersistent(deliveryPersistent);
    if (messageConverter != null) {
        template.setMessageConverter(messageConverter);
    }
    template.setMessageIdEnabled(messageIdEnabled);
    template.setMessageTimestampEnabled(messageTimestampEnabled);
    if (priority >= 0) {
        template.setPriority(priority);
    }
    template.setPubSubNoLocal(pubSubNoLocal);
    if (receiveTimeout >= 0) {
        template.setReceiveTimeout(receiveTimeout);
    }
    if (timeToLive >= 0) {
        template.setTimeToLive(timeToLive);
    }

    template.setSessionTransacted(transacted);
    if (transacted) {
        template.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
    } else {
        // This is here for completeness, but the template should not get
        // used for receiving messages.
        if (acknowledgementMode >= 0) {
            template.setSessionAcknowledgeMode(acknowledgementMode);
        } else if (acknowledgementModeName != null) {
            template.setSessionAcknowledgeModeName(acknowledgementModeName);
        }
    }
    return template;
}

From source file:org.apache.camel.component.jms.JmsConfiguration.java

protected void configureMessageListenerContainer(AbstractMessageListenerContainer container,
        JmsEndpoint endpoint) throws Exception {
    container.setConnectionFactory(getListenerConnectionFactory());
    if (endpoint instanceof DestinationEndpoint) {
        container.setDestinationResolver(createDestinationResolver((DestinationEndpoint) endpoint));
    } else if (destinationResolver != null) {
        container.setDestinationResolver(destinationResolver);
    }/* ww w  .java2s  .c  o m*/
    container.setAutoStartup(autoStartup);

    if (durableSubscriptionName != null) {
        container.setDurableSubscriptionName(durableSubscriptionName);
        container.setSubscriptionDurable(true);
    }
    if (durableSubscriptionName != null && clientId == null) {
        throw new IllegalArgumentException(
                "ClientId must be configured when subscription is durable for " + endpoint);
    }
    if (clientId != null) {
        container.setClientId(clientId);
    }

    if (exceptionListener != null) {
        container.setExceptionListener(exceptionListener);
    }

    container.setAcceptMessagesWhileStopping(acceptMessagesWhileStopping);
    container.setExposeListenerSession(exposeListenerSession);
    container.setSessionTransacted(transacted);
    if (transacted) {
        container.setSessionAcknowledgeMode(Session.SESSION_TRANSACTED);
    } else {
        if (acknowledgementMode >= 0) {
            container.setSessionAcknowledgeMode(acknowledgementMode);
        } else if (acknowledgementModeName != null) {
            container.setSessionAcknowledgeModeName(acknowledgementModeName);
        }
    }

    if (endpoint.getSelector() != null && endpoint.getSelector().length() != 0) {
        container.setMessageSelector(endpoint.getSelector());
    }

    if (container instanceof DefaultMessageListenerContainer) {
        // this includes DefaultMessageListenerContainer102
        DefaultMessageListenerContainer listenerContainer = (DefaultMessageListenerContainer) container;
        if (concurrentConsumers >= 0) {
            listenerContainer.setConcurrentConsumers(concurrentConsumers);
        }

        if (cacheLevel >= 0) {
            listenerContainer.setCacheLevel(cacheLevel);
        } else if (cacheLevelName != null) {
            listenerContainer.setCacheLevelName(cacheLevelName);
        } else {
            listenerContainer.setCacheLevel(defaultCacheLevel(endpoint));
        }

        if (idleTaskExecutionLimit >= 0) {
            listenerContainer.setIdleTaskExecutionLimit(idleTaskExecutionLimit);
        }
        if (maxConcurrentConsumers > 0) {
            if (maxConcurrentConsumers < concurrentConsumers) {
                throw new IllegalArgumentException("Property maxConcurrentConsumers: " + maxConcurrentConsumers
                        + " must be higher than concurrentConsumers: " + concurrentConsumers);
            }
            listenerContainer.setMaxConcurrentConsumers(maxConcurrentConsumers);
        }
        if (maxMessagesPerTask >= 0) {
            listenerContainer.setMaxMessagesPerTask(maxMessagesPerTask);
        }
        listenerContainer.setPubSubNoLocal(pubSubNoLocal);
        if (receiveTimeout >= 0) {
            listenerContainer.setReceiveTimeout(receiveTimeout);
        }
        if (recoveryInterval >= 0) {
            listenerContainer.setRecoveryInterval(recoveryInterval);
        }
        if (taskExecutor != null) {
            listenerContainer.setTaskExecutor(taskExecutor);
        }
        PlatformTransactionManager tm = getTransactionManager();
        if (tm != null && transacted) {
            listenerContainer.setTransactionManager(tm);
        } else if (transacted) {
            throw new IllegalArgumentException(
                    "Property transacted is enabled but a transactionManager was not injected!");
        }
        if (transactionName != null) {
            listenerContainer.setTransactionName(transactionName);
        }
        if (transactionTimeout >= 0) {
            listenerContainer.setTransactionTimeout(transactionTimeout);
        }
        if (taskExecutor != null) {
            listenerContainer.setTaskExecutor(taskExecutor);
        } else if (taskExecutorSpring2 != null) {
            // use reflection to invoke to support spring 2 when JAR is compiled with Spring 3.0
            IntrospectionSupport.setProperty(listenerContainer, "taskExecutor",
                    endpoint.getTaskExecutorSpring2());
        }
    } else if (container instanceof SimpleMessageListenerContainer) {
        // this includes SimpleMessageListenerContainer102
        SimpleMessageListenerContainer listenerContainer = (SimpleMessageListenerContainer) container;
        if (concurrentConsumers >= 0) {
            listenerContainer.setConcurrentConsumers(concurrentConsumers);
        }
        listenerContainer.setPubSubNoLocal(pubSubNoLocal);
        if (taskExecutor != null) {
            listenerContainer.setTaskExecutor(taskExecutor);
        } else if (taskExecutorSpring2 != null) {
            // use reflection to invoke to support spring 2 when JAR is compiled with Spring 3.0
            IntrospectionSupport.setProperty(listenerContainer, "taskExecutor",
                    endpoint.getTaskExecutorSpring2());
        }
    }
}

From source file:org.apache.camel.component.sjms.SjmsConsumer.java

/**
 * Creates a {@link MessageConsumerResources} with a dedicated
 * {@link Session} required for transacted and InOut consumers.
 *//*from  www  .  ja  v  a 2 s.  co m*/
private MessageConsumerResources createConsumer() throws Exception {
    MessageConsumerResources answer;
    Connection conn = getConnectionResource().borrowConnection();
    try {
        Session session = conn.createSession(isTransacted(),
                isTransacted() ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        Destination destination = getEndpoint().getDestinationCreationStrategy().createDestination(session,
                getDestinationName(), isTopic());
        MessageConsumer messageConsumer = JmsObjectFactory.createMessageConsumer(session, destination,
                getMessageSelector(), isTopic(), getDurableSubscriptionId());
        MessageListener handler = createMessageHandler(session);
        messageConsumer.setMessageListener(handler);

        answer = new MessageConsumerResources(session, messageConsumer);
    } catch (Exception e) {
        log.error("Unable to create the MessageConsumer", e);
        throw e;
    } finally {
        getConnectionResource().returnConnection(conn);
    }
    return answer;
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * <p>/*from  w w  w .  ja v  a 2s  . c o  m*/
 * Dequeues a mail when it is ready to process. As JMS does not support delay scheduling out-of-the box,
 * we use a messageselector to check if a mail is ready. For this a
 * {@link MessageConsumer#receive(long)} is used with a timeout of 10
 * seconds.
 * </p>
 * <p>
 * Many JMS implementations support better solutions for this, so this
 * should get overridden by these implementations
 * </p>
 */
@Override
public MailQueueItem deQueue() throws MailQueueException {
    Session session = null;
    MessageConsumer consumer = null;

    while (true) {
        TimeMetric timeMetric = metricFactory.timer(DEQUEUED_TIMER_METRIC_NAME_PREFIX + queueName);
        try {
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue queue = session.createQueue(queueName);
            consumer = session.createConsumer(queue, getMessageSelector());

            Message message = consumer.receive(10000);

            if (message != null) {
                dequeuedMailsMetric.increment();
                return createMailQueueItem(session, consumer, message);
            } else {
                session.commit();
                closeConsumer(consumer);
                closeSession(session);
            }

        } catch (Exception e) {
            rollback(session);
            closeConsumer(consumer);
            closeSession(session);
            throw new MailQueueException("Unable to dequeue next message", e);
        } finally {
            timeMetric.stopAndPublish();
        }
    }
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

@Override
public long flush() throws MailQueueException {
    boolean first = true;
    long count = 0;
    try (Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) {
        Queue queue = session.createQueue(queueName);
        try (MessageConsumer consumer = session.createConsumer(queue)) {
            try (MessageProducer producer = session.createProducer(queue)) {

                Message message = null;/* w w  w  . ja v  a2  s.c  o m*/
                while (first || message != null) {
                    if (first) {
                        // give the consumer 2000 ms to receive messages
                        message = consumer.receive(2000);
                    } else {
                        message = consumer.receiveNoWait();
                    }
                    first = false;

                    if (message != null) {
                        Message m = copy(session, message);
                        m.setBooleanProperty(FORCE_DELIVERY, true);
                        producer.send(m, message.getJMSDeliveryMode(), message.getJMSPriority(),
                                message.getJMSExpiration());
                        count++;
                    }
                }
                session.commit();
                return count;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to flush mail", e);
        throw new MailQueueException("Unable to get size of queue " + queueName, e);
    }
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * Remove messages with the given selector
 *
 * @param selector//from  w  w w .  j a v a2s . c  o  m
 * @return messages
 */
public List<Message> removeWithSelector(String selector) throws MailQueueException {
    boolean first = true;
    List<Message> messages = new ArrayList<>();

    try {
        try (Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) {
            Queue queue = session.createQueue(queueName);
            try (MessageConsumer consumer = session.createConsumer(queue, selector)) {
                Message message = null;
                while (first || message != null) {
                    if (first) {
                        // give the consumer 2000 ms to receive messages
                        message = consumer.receive(2000);
                    } else {
                        message = consumer.receiveNoWait();
                    }
                    first = false;
                    if (message != null) {
                        messages.add(message);
                    }
                }
            }
            session.commit();
        }
        return messages;
    } catch (Exception e) {
        throw new MailQueueException("Unable to remove mails", e);
    }
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

private void missingClientCertWhileNeedingOrWantingTestImpl(boolean needClientCerts, boolean wantClientCerts,
        boolean shouldSucceed) throws Exception {
    if (shouldPerformTest()) {
        clearSslStoreSystemProperties();

        //Start the broker
        configureJavaBrokerIfNecessary(true, true, needClientCerts, wantClientCerts);
        super.setUp();

        String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s"
                + "?ssl='true'&trust_store='%s'&trust_store_password='%s''";

        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT, TRUSTSTORE, TRUSTSTORE_PASSWORD);
        try {//from  w w  w .jav  a  2s. c o m
            Connection con = getConnection(new AMQConnectionURL(url));
            if (!shouldSucceed) {
                fail("Connection succeeded, expected exception was not thrown");
            } else {
                //Use the connection to verify it works
                con.createSession(true, Session.SESSION_TRANSACTED);
            }
        } catch (JMSException e) {
            if (shouldSucceed) {
                _logger.error("Caught unexpected exception", e);
                fail("Connection failed, unexpected exception thrown");
            } else {
                //expected
                verifyExceptionCausesContains(e, "Caused by: javax.net.ssl.SSLException:");
            }
        }
    }
}

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

public void createSession(final CreateSessionCommand command) {
    try {//from w ww  . jav  a 2 s. c  o  m
        final Connection connection = _testConnections.get(command.getConnectionName());
        if (connection == null) {
            throw new DistributedTestException(
                    "No test connection found called: " + command.getConnectionName(), command);
        }
        final boolean transacted = command.getAcknowledgeMode() == Session.SESSION_TRANSACTED;

        final Session newSession = connection.createSession(transacted, command.getAcknowledgeMode());
        LOGGER.debug("Created session " + command.getSessionName() + " with transacted = "
                + newSession.getTransacted() + " and acknowledgeMode = " + newSession.getAcknowledgeMode());

        addSession(command.getSessionName(), newSession);
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new session: " + command, jmse);
    }
}