Search in sources :

Example 1 with Session

use of jakarta.jms.Session in project spring-framework by spring-projects.

the class ConnectionFactoryUtils method doGetTransactionalSession.

/**
 * Obtain a JMS Session that is synchronized with the current transaction, if any.
 * @param connectionFactory the JMS ConnectionFactory to bind for
 * (used as TransactionSynchronizationManager key)
 * @param resourceFactory the ResourceFactory to use for extracting or creating
 * JMS resources
 * @param startConnection whether the underlying JMS Connection approach should be
 * started in order to allow for receiving messages. Note that a reused Connection
 * may already have been started before, even if this flag is {@code false}.
 * @return the transactional Session, or {@code null} if none found
 * @throws JMSException in case of JMS failure
 */
@Nullable
public static Session doGetTransactionalSession(ConnectionFactory connectionFactory, ResourceFactory resourceFactory, boolean startConnection) throws JMSException {
    Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
    Assert.notNull(resourceFactory, "ResourceFactory must not be null");
    JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(connectionFactory);
    if (resourceHolder != null) {
        Session session = resourceFactory.getSession(resourceHolder);
        if (session != null) {
            if (startConnection) {
                Connection con = resourceFactory.getConnection(resourceHolder);
                if (con != null) {
                    con.start();
                }
            }
            return session;
        }
        if (resourceHolder.isFrozen()) {
            return null;
        }
    }
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        return null;
    }
    JmsResourceHolder resourceHolderToUse = resourceHolder;
    if (resourceHolderToUse == null) {
        resourceHolderToUse = new JmsResourceHolder(connectionFactory);
    }
    Connection con = resourceFactory.getConnection(resourceHolderToUse);
    Session session = null;
    try {
        boolean isExistingCon = (con != null);
        if (!isExistingCon) {
            con = resourceFactory.createConnection();
            resourceHolderToUse.addConnection(con);
        }
        session = resourceFactory.createSession(con);
        resourceHolderToUse.addSession(session, con);
        if (startConnection) {
            con.start();
        }
    } catch (JMSException ex) {
        if (session != null) {
            try {
                session.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        throw ex;
    }
    if (resourceHolderToUse != resourceHolder) {
        TransactionSynchronizationManager.registerSynchronization(new JmsResourceSynchronization(resourceHolderToUse, connectionFactory, resourceFactory.isSynchedLocalTransactionAllowed()));
        resourceHolderToUse.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolderToUse);
    }
    return session;
}
Also used : QueueConnection(jakarta.jms.QueueConnection) TopicConnection(jakarta.jms.TopicConnection) Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) QueueSession(jakarta.jms.QueueSession) Session(jakarta.jms.Session) TopicSession(jakarta.jms.TopicSession) Nullable(org.springframework.lang.Nullable)

Example 2 with Session

use of jakarta.jms.Session in project spring-framework by spring-projects.

the class JmsTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        throw new InvalidIsolationLevelException("JMS does not support an isolation level concept");
    }
    ConnectionFactory connectionFactory = obtainConnectionFactory();
    JmsTransactionObject txObject = (JmsTransactionObject) transaction;
    Connection con = null;
    Session session = null;
    try {
        JmsResourceHolder resourceHolder;
        if (this.lazyResourceRetrieval) {
            resourceHolder = new LazyJmsResourceHolder(connectionFactory);
        } else {
            con = createConnection();
            session = createSession(con);
            if (logger.isDebugEnabled()) {
                logger.debug("Created JMS transaction on Session [" + session + "] from Connection [" + con + "]");
            }
            resourceHolder = new JmsResourceHolder(connectionFactory, con, session);
        }
        resourceHolder.setSynchronizedWithTransaction(true);
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            resourceHolder.setTimeoutInSeconds(timeout);
        }
        txObject.setResourceHolder(resourceHolder);
        TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolder);
    } catch (Throwable ex) {
        if (session != null) {
            try {
                session.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Throwable ex2) {
            // ignore
            }
        }
        throw new CannotCreateTransactionException("Could not create JMS transaction", ex);
    }
}
Also used : ConnectionFactory(jakarta.jms.ConnectionFactory) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) Connection(jakarta.jms.Connection) InvalidIsolationLevelException(org.springframework.transaction.InvalidIsolationLevelException) Session(jakarta.jms.Session)

Example 3 with Session

use of jakarta.jms.Session in project spring-framework by spring-projects.

the class JmsTransactionManager method doRollback.

@Override
protected void doRollback(DefaultTransactionStatus status) {
    JmsTransactionObject txObject = (JmsTransactionObject) status.getTransaction();
    Session session = txObject.getResourceHolder().getOriginalSession();
    if (session != null) {
        try {
            if (status.isDebug()) {
                logger.debug("Rolling back JMS transaction on Session [" + session + "]");
            }
            session.rollback();
        } catch (JMSException ex) {
            throw new TransactionSystemException("Could not roll back JMS transaction", ex);
        }
    }
}
Also used : JMSException(jakarta.jms.JMSException) TransactionSystemException(org.springframework.transaction.TransactionSystemException) Session(jakarta.jms.Session)

Example 4 with Session

use of jakarta.jms.Session in project spring-framework by spring-projects.

the class JmsTemplate method executeLocal.

/**
 * A variant of {@link #execute(SessionCallback, boolean)} that explicitly
 * creates a non-transactional {@link Session}. The given {@link SessionCallback}
 * does not participate in an existing transaction.
 */
@Nullable
private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException {
    Assert.notNull(action, "Callback object must not be null");
    Connection con = null;
    Session session = null;
    try {
        con = createConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        if (startConnection) {
            con.start();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing callback on JMS Session: " + session);
        }
        return action.doInJms(session);
    } catch (JMSException ex) {
        throw convertJmsAccessException(ex);
    } finally {
        JmsUtils.closeSession(session);
        ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection);
    }
}
Also used : Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session) Nullable(org.springframework.lang.Nullable)

Example 5 with Session

use of jakarta.jms.Session in project spring-framework by spring-projects.

the class AbstractMessageListenerContainer method doInvokeListener.

/**
 * Invoke the specified listener as Spring SessionAwareMessageListener,
 * exposing a new JMS Session (potentially with its own transaction)
 * to the listener if demanded.
 * @param listener the Spring SessionAwareMessageListener to invoke
 * @param session the JMS Session to operate on
 * @param message the received JMS Message
 * @throws JMSException if thrown by JMS API methods
 * @see SessionAwareMessageListener
 * @see #setExposeListenerSession
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void doInvokeListener(SessionAwareMessageListener listener, Session session, Message message) throws JMSException {
    Connection conToClose = null;
    Session sessionToClose = null;
    try {
        Session sessionToUse = session;
        if (!isExposeListenerSession()) {
            // We need to expose a separate Session.
            conToClose = createConnection();
            sessionToClose = createSession(conToClose);
            sessionToUse = sessionToClose;
        }
        // Actually invoke the message listener...
        listener.onMessage(message, sessionToUse);
        // Clean up specially exposed Session, if any.
        if (sessionToUse != session) {
            if (sessionToUse.getTransacted() && isSessionLocallyTransacted(sessionToUse)) {
                // Transacted session created by this container -> commit.
                JmsUtils.commitIfNecessary(sessionToUse);
            }
        }
    } finally {
        JmsUtils.closeSession(sessionToClose);
        JmsUtils.closeConnection(conToClose);
    }
}
Also used : Connection(jakarta.jms.Connection) Session(jakarta.jms.Session)

Aggregations

Session (jakarta.jms.Session)84 Test (org.junit.jupiter.api.Test)71 Connection (jakarta.jms.Connection)30 Message (jakarta.jms.Message)27 TextMessage (jakarta.jms.TextMessage)26 StubTextMessage (org.springframework.jms.StubTextMessage)22 ConnectionFactory (jakarta.jms.ConnectionFactory)21 JMSException (jakarta.jms.JMSException)20 MessageProducer (jakarta.jms.MessageProducer)19 Destination (jakarta.jms.Destination)18 MessagingMessageListenerAdapter (org.springframework.jms.listener.adapter.MessagingMessageListenerAdapter)16 Queue (jakarta.jms.Queue)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)12 BDDMockito.given (org.mockito.BDDMockito.given)12 Mockito.mock (org.mockito.Mockito.mock)12 Mockito.verify (org.mockito.Mockito.verify)12 StubQueue (org.springframework.jms.StubQueue)12 ObjectMessage (jakarta.jms.ObjectMessage)11 QueueSession (jakarta.jms.QueueSession)11 SimpleMessageConverter (org.springframework.jms.support.converter.SimpleMessageConverter)11