Search in sources :

Example 61 with Session

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

the class JmsResourceHolder method closeAll.

/**
 * Close all of this resource holder's Sessions and clear its state.
 * @see Session#close()
 */
public void closeAll() {
    for (Session session : this.sessions) {
        try {
            session.close();
        } catch (Throwable ex) {
            logger.debug("Could not close synchronized JMS Session after transaction", ex);
        }
    }
    for (Connection con : this.connections) {
        ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true);
    }
    this.connections.clear();
    this.sessions.clear();
    this.sessionsPerConnection.clear();
}
Also used : Connection(jakarta.jms.Connection) Session(jakarta.jms.Session)

Example 62 with Session

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

the class JmsTransactionManager method doCommit.

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

Example 63 with Session

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

the class AbstractPollingMessageListenerContainer method doReceiveAndExecute.

/**
 * Actually execute the listener for a message received from the given consumer,
 * fetching all requires resources and invoking the listener.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @param status the TransactionStatus (may be {@code null})
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doExecuteListener(jakarta.jms.Session, jakarta.jms.Message)
 */
protected boolean doReceiveAndExecute(Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer, @Nullable TransactionStatus status) throws JMSException {
    Connection conToClose = null;
    Session sessionToClose = null;
    MessageConsumer consumerToClose = null;
    try {
        Session sessionToUse = session;
        boolean transactional = false;
        if (sessionToUse == null) {
            sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(obtainConnectionFactory(), this.transactionalResourceFactory, true);
            transactional = (sessionToUse != null);
        }
        if (sessionToUse == null) {
            Connection conToUse;
            if (sharedConnectionEnabled()) {
                conToUse = getSharedConnection();
            } else {
                conToUse = createConnection();
                conToClose = conToUse;
                conToUse.start();
            }
            sessionToUse = createSession(conToUse);
            sessionToClose = sessionToUse;
        }
        MessageConsumer consumerToUse = consumer;
        if (consumerToUse == null) {
            consumerToUse = createListenerConsumer(sessionToUse);
            consumerToClose = consumerToUse;
        }
        Message message = receiveMessage(consumerToUse);
        if (message != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received message of type [" + message.getClass() + "] from consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" + sessionToUse + "]");
            }
            messageReceived(invoker, sessionToUse);
            boolean exposeResource = (!transactional && isExposeListenerSession() && !TransactionSynchronizationManager.hasResource(obtainConnectionFactory()));
            if (exposeResource) {
                TransactionSynchronizationManager.bindResource(obtainConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
            }
            try {
                doExecuteListener(sessionToUse, message);
            } catch (Throwable ex) {
                if (status != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
                    }
                    status.setRollbackOnly();
                }
                handleListenerException(ex);
                // that may have to trigger recovery...
                if (ex instanceof JMSException) {
                    throw (JMSException) ex;
                }
            } finally {
                if (exposeResource) {
                    TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
                }
            }
            // Indicate that a message has been received.
            return true;
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" + sessionToUse + "] did not receive a message");
            }
            noMessageReceived(invoker, sessionToUse);
            // Nevertheless call commit, in order to reset the transaction timeout (if any).
            if (shouldCommitAfterNoMessageReceived(sessionToUse)) {
                commitIfNecessary(sessionToUse, null);
            }
            // Indicate that no message has been received.
            return false;
        }
    } finally {
        JmsUtils.closeMessageConsumer(consumerToClose);
        JmsUtils.closeSession(sessionToClose);
        ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
    }
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) Message(jakarta.jms.Message) Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session)

Example 64 with Session

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

the class SimpleMessageListenerContainer method initializeConsumers.

/**
 * Initialize the JMS Sessions and MessageConsumers for this container.
 * @throws JMSException in case of setup failure
 */
protected void initializeConsumers() throws JMSException {
    // Register Sessions and MessageConsumers.
    synchronized (this.consumersMonitor) {
        if (this.consumers == null) {
            this.sessions = new HashSet<>(this.concurrentConsumers);
            this.consumers = new HashSet<>(this.concurrentConsumers);
            Connection con = getSharedConnection();
            for (int i = 0; i < this.concurrentConsumers; i++) {
                Session session = createSession(con);
                MessageConsumer consumer = createListenerConsumer(session);
                this.sessions.add(session);
                this.consumers.add(consumer);
            }
        }
    }
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) Connection(jakarta.jms.Connection) Session(jakarta.jms.Session)

Example 65 with Session

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

the class JmsTemplate method execute.

/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of {@code execute(SessionCallback)},
 * allowing the JMS Connection to be started on the fly.
 * <p>Use {@code execute(SessionCallback)} for the general case.
 * Starting the JMS Connection is just necessary for receiving messages,
 * which is preferably achieved through the {@code receive} methods.
 * @param action callback object that exposes the Session
 * @param startConnection whether to start the Connection
 * @return the result object from working with the Session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)
 * @see #receive
 */
@Nullable
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
    Assert.notNull(action, "Callback object must not be null");
    Connection conToClose = null;
    Session sessionToClose = null;
    try {
        Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(obtainConnectionFactory(), this.transactionalResourceFactory, startConnection);
        if (sessionToUse == null) {
            conToClose = createConnection();
            sessionToClose = createSession(conToClose);
            if (startConnection) {
                conToClose.start();
            }
            sessionToUse = sessionToClose;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing callback on JMS Session: " + sessionToUse);
        }
        return action.doInJms(sessionToUse);
    } catch (JMSException ex) {
        throw convertJmsAccessException(ex);
    } finally {
        JmsUtils.closeSession(sessionToClose);
        ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
    }
}
Also used : Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session) Nullable(org.springframework.lang.Nullable)

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