Search in sources :

Example 6 with Connection

use of jakarta.jms.Connection 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 7 with Connection

use of jakarta.jms.Connection 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)

Example 8 with Connection

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

the class DefaultMessageListenerContainer method refreshConnectionUntilSuccessful.

/**
 * Refresh the underlying Connection, not returning before an attempt has been
 * successful. Called in case of a shared Connection as well as without shared
 * Connection, so either needs to operate on the shared Connection or on a
 * temporary Connection that just gets established for validation purposes.
 * <p>The default implementation retries until it successfully established a
 * Connection, for as long as this message listener container is running.
 * Applies the specified recovery interval between retries.
 * @see #setRecoveryInterval
 * @see #start()
 * @see #stop()
 */
protected void refreshConnectionUntilSuccessful() {
    BackOffExecution execution = this.backOff.start();
    while (isRunning()) {
        try {
            if (sharedConnectionEnabled()) {
                refreshSharedConnection();
            } else {
                Connection con = createConnection();
                JmsUtils.closeConnection(con);
            }
            logger.debug("Successfully refreshed JMS Connection");
            break;
        } catch (Exception ex) {
            if (ex instanceof JMSException) {
                invokeExceptionListener((JMSException) ex);
            }
            StringBuilder msg = new StringBuilder();
            msg.append("Could not refresh JMS Connection for destination '");
            msg.append(getDestinationDescription()).append("' - retrying using ");
            msg.append(execution).append(". Cause: ");
            msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage());
            if (logger.isDebugEnabled()) {
                logger.error(msg, ex);
            } else {
                logger.error(msg);
            }
        }
        if (!applyBackOffTime(execution)) {
            logger.error("Stopping container for destination '" + getDestinationDescription() + "': back-off policy does not allow for further attempts.");
            stop();
        }
    }
}
Also used : BackOffExecution(org.springframework.util.backoff.BackOffExecution) Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) JmsException(org.springframework.jms.JmsException) JMSException(jakarta.jms.JMSException)

Example 9 with Connection

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

the class JmsTemplateTests method testSessionCallbackWithinSynchronizedTransaction.

@Test
void testSessionCallbackWithinSynchronizedTransaction() throws Exception {
    SingleConnectionFactory scf = new SingleConnectionFactory(this.connectionFactory);
    JmsTemplate template = createTemplate();
    template.setConnectionFactory(scf);
    TransactionSynchronizationManager.initSynchronization();
    try {
        template.execute((SessionCallback<Void>) session -> {
            session.getTransacted();
            return null;
        });
        template.execute((SessionCallback<Void>) session -> {
            session.getTransacted();
            return null;
        });
        assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, null, false)).isSameAs(this.session);
        assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)).isSameAs(this.session);
        TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf);
        Connection tac = tacf.createConnection();
        Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE);
        tas.getTransacted();
        tas.close();
        tac.close();
        List<TransactionSynchronization> synchs = TransactionSynchronizationManager.getSynchronizations();
        assertThat(synchs.size()).isEqualTo(1);
        TransactionSynchronization synch = synchs.get(0);
        synch.beforeCommit(false);
        synch.beforeCompletion();
        synch.afterCommit();
        synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
    } finally {
        TransactionSynchronizationManager.clearSynchronization();
        scf.destroy();
    }
    assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
    verify(this.connection).start();
    if (useTransactedTemplate()) {
        verify(this.session).commit();
    }
    verify(this.session).close();
    verify(this.connection).stop();
    verify(this.connection).close();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) MessageNotReadableException(org.springframework.jms.MessageNotReadableException) SimpleMessageConverter(org.springframework.jms.support.converter.SimpleMessageConverter) MessageProducer(jakarta.jms.MessageProducer) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) UncategorizedJmsException(org.springframework.jms.UncategorizedJmsException) JMSException(jakarta.jms.JMSException) TemporaryQueue(jakarta.jms.TemporaryQueue) Queue(jakarta.jms.Queue) Session(jakarta.jms.Session) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) InvalidDestinationException(org.springframework.jms.InvalidDestinationException) ResourceAllocationException(org.springframework.jms.ResourceAllocationException) SingleConnectionFactory(org.springframework.jms.connection.SingleConnectionFactory) MessageConsumer(jakarta.jms.MessageConsumer) BDDMockito.given(org.mockito.BDDMockito.given) Destination(jakarta.jms.Destination) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) MessageFormatException(org.springframework.jms.MessageFormatException) Context(javax.naming.Context) ConnectionFactory(jakarta.jms.ConnectionFactory) MessageEOFException(org.springframework.jms.MessageEOFException) Connection(jakarta.jms.Connection) QosSettings(org.springframework.jms.support.QosSettings) InvalidClientIDException(org.springframework.jms.InvalidClientIDException) TransactionAwareConnectionFactoryProxy(org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy) PrintWriter(java.io.PrintWriter) Message(jakarta.jms.Message) JmsException(org.springframework.jms.JmsException) BDDMockito.willThrow(org.mockito.BDDMockito.willThrow) StringWriter(java.io.StringWriter) JndiDestinationResolver(org.springframework.jms.support.destination.JndiDestinationResolver) JndiTemplate(org.springframework.jndi.JndiTemplate) TransactionInProgressException(org.springframework.jms.TransactionInProgressException) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) MessageNotWriteableException(org.springframework.jms.MessageNotWriteableException) TransactionSynchronization(org.springframework.transaction.support.TransactionSynchronization) JmsUtils(org.springframework.jms.support.JmsUtils) TextMessage(jakarta.jms.TextMessage) ConnectionFactoryUtils(org.springframework.jms.connection.ConnectionFactoryUtils) DeliveryMode(jakarta.jms.DeliveryMode) TransactionRolledBackException(org.springframework.jms.TransactionRolledBackException) JmsSecurityException(org.springframework.jms.JmsSecurityException) Mockito.reset(org.mockito.Mockito.reset) InvalidSelectorException(org.springframework.jms.InvalidSelectorException) Mockito.mock(org.mockito.Mockito.mock) TransactionSynchronization(org.springframework.transaction.support.TransactionSynchronization) SingleConnectionFactory(org.springframework.jms.connection.SingleConnectionFactory) Connection(jakarta.jms.Connection) TransactionAwareConnectionFactoryProxy(org.springframework.jms.connection.TransactionAwareConnectionFactoryProxy) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Example 10 with Connection

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

the class JmsTransactionManagerTests method testLazyTransactionalSession.

@Test
public void testLazyTransactionalSession() throws JMSException {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    final Session session = mock(Session.class);
    JmsTransactionManager tm = new JmsTransactionManager(cf);
    tm.setLazyResourceRetrieval(true);
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
    given(cf.createConnection()).willReturn(con);
    given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
    JmsTemplate jt = new JmsTemplate(cf);
    jt.execute((SessionCallback<Void>) sess -> {
        assertThat(session).isSameAs(sess);
        return null;
    });
    tm.commit(ts);
    verify(session).commit();
    verify(session).close();
    verify(con).close();
}
Also used : MessageProducer(jakarta.jms.MessageProducer) TransactionDefinition(org.springframework.transaction.TransactionDefinition) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session) TransactionSynchronizationManager(org.springframework.transaction.support.TransactionSynchronizationManager) BDDMockito.given(org.mockito.BDDMockito.given) Destination(jakarta.jms.Destination) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) JmsTemplate(org.springframework.jms.core.JmsTemplate) ConnectionFactory(jakarta.jms.ConnectionFactory) Connection(jakarta.jms.Connection) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Message(jakarta.jms.Message) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) StubQueue(org.springframework.jms.StubQueue) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) Mockito.times(org.mockito.Mockito.times) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) SessionCallback(org.springframework.jms.core.SessionCallback) Mockito.mock(org.mockito.Mockito.mock) ConnectionFactory(jakarta.jms.ConnectionFactory) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Connection(jakarta.jms.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) JmsTemplate(org.springframework.jms.core.JmsTemplate) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Aggregations

Connection (jakarta.jms.Connection)52 Test (org.junit.jupiter.api.Test)40 ConnectionFactory (jakarta.jms.ConnectionFactory)31 Session (jakarta.jms.Session)29 JMSException (jakarta.jms.JMSException)22 QueueConnection (jakarta.jms.QueueConnection)21 TopicConnection (jakarta.jms.TopicConnection)21 Message (jakarta.jms.Message)16 QueueConnectionFactory (jakarta.jms.QueueConnectionFactory)11 TopicConnectionFactory (jakarta.jms.TopicConnectionFactory)11 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)10 BDDMockito.given (org.mockito.BDDMockito.given)10 Mockito.mock (org.mockito.Mockito.mock)10 Mockito.verify (org.mockito.Mockito.verify)10 StubQueue (org.springframework.jms.StubQueue)10 Destination (jakarta.jms.Destination)9 MessageProducer (jakarta.jms.MessageProducer)9 MessageConsumer (jakarta.jms.MessageConsumer)8 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)8 JmsTemplate (org.springframework.jms.core.JmsTemplate)8