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);
}
}
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);
}
}
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();
}
}
}
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();
}
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();
}
Aggregations