use of jakarta.jms.MessageConsumer in project spring-framework by spring-projects.
the class JmsTemplateTests method doTestSendAndReceive.
private void doTestSendAndReceive(boolean explicitDestination, boolean useDefaultDestination, long timeout) throws Exception {
JmsTemplate template = createTemplate();
template.setConnectionFactory(this.connectionFactory);
String destinationName = "testDestination";
if (useDefaultDestination) {
if (explicitDestination) {
template.setDefaultDestination(this.queue);
} else {
template.setDefaultDestinationName(destinationName);
}
}
template.setReceiveTimeout(timeout);
Session localSession = getLocalSession();
TemporaryQueue replyDestination = mock(TemporaryQueue.class);
MessageProducer messageProducer = mock(MessageProducer.class);
given(localSession.createProducer(this.queue)).willReturn(messageProducer);
given(localSession.createTemporaryQueue()).willReturn(replyDestination);
MessageConsumer messageConsumer = mock(MessageConsumer.class);
given(localSession.createConsumer(replyDestination)).willReturn(messageConsumer);
TextMessage request = mock(TextMessage.class);
MessageCreator messageCreator = mock(MessageCreator.class);
given(messageCreator.createMessage(localSession)).willReturn(request);
TextMessage reply = mock(TextMessage.class);
if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) {
given(messageConsumer.receiveNoWait()).willReturn(reply);
} else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) {
given(messageConsumer.receive()).willReturn(reply);
} else {
given(messageConsumer.receive(timeout)).willReturn(reply);
}
Message message = null;
if (useDefaultDestination) {
message = template.sendAndReceive(messageCreator);
} else if (explicitDestination) {
message = template.sendAndReceive(this.queue, messageCreator);
} else {
message = template.sendAndReceive(destinationName, messageCreator);
}
// replyTO set on the request
verify(request).setJMSReplyTo(replyDestination);
assertThat(message).as("Reply message not received").isSameAs(reply);
verify(this.connection).start();
verify(this.connection).close();
verify(localSession).close();
verify(messageConsumer).close();
verify(messageProducer).close();
}
use of jakarta.jms.MessageConsumer in project spring-framework by spring-projects.
the class SimpleMessageListenerContainerTests method testContextRefreshedEventStartsTheConnectionByDefault.
@Test
public void testContextRefreshedEventStartsTheConnectionByDefault() throws Exception {
MessageConsumer messageConsumer = mock(MessageConsumer.class);
Session session = mock(Session.class);
// Queue gets created in order to create MessageConsumer for that Destination...
given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
// no MessageSelector...
given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);
Connection connection = mock(Connection.class);
// session gets created in order to register MessageListener...
given(connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode())).willReturn(session);
// and the connection is start()ed after the listener is registered...
ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
given(connectionFactory.createConnection()).willReturn(connection);
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener(new TestMessageListener());
this.container.afterPropertiesSet();
GenericApplicationContext context = new GenericApplicationContext();
context.getBeanFactory().registerSingleton("messageListenerContainer", this.container);
context.refresh();
context.close();
verify(connection).setExceptionListener(this.container);
verify(connection).start();
}
use of jakarta.jms.MessageConsumer in project spring-framework by spring-projects.
the class SimpleMessageListenerContainerTests method testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillDo_NOT_Propagate.
@Test
public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillDo_NOT_Propagate() throws Exception {
this.container.setSessionTransacted(true);
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
Session session = mock(Session.class);
// Queue gets created in order to create MessageConsumer for that Destination...
given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
// no MessageSelector...
given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
given(session.getTransacted()).willReturn(true);
Connection connection = mock(Connection.class);
// session gets created in order to register MessageListener...
given(connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode())).willReturn(session);
// and the connection is start()ed after the listener is registered...
ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
given(connectionFactory.createConnection()).willReturn(connection);
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener((MessageListener) message -> {
throw new UnsupportedOperationException();
});
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
final Message message = mock(Message.class);
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
// Session is rolled back 'cos it is transacted...
verify(session).rollback();
verify(connection).setExceptionListener(this.container);
verify(connection).start();
}
use of jakarta.jms.MessageConsumer in project spring-framework by spring-projects.
the class SimpleMessageListenerContainerTests method testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate.
@Test
public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception {
final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer();
Session session = mock(Session.class);
// Queue gets created in order to create MessageConsumer for that Destination...
given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION);
// and then the MessageConsumer gets created...
// no MessageSelector...
given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);
// an exception is thrown, so the rollback logic is being applied here...
given(session.getTransacted()).willReturn(false);
Connection connection = mock(Connection.class);
// session gets created in order to register MessageListener...
given(connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode())).willReturn(session);
// and the connection is start()ed after the listener is registered...
ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
given(connectionFactory.createConnection()).willReturn(connection);
this.container.setConnectionFactory(connectionFactory);
this.container.setDestinationName(DESTINATION_NAME);
this.container.setMessageListener((MessageListener) message -> {
throw new UnsupportedOperationException();
});
this.container.afterPropertiesSet();
this.container.start();
// manually trigger an Exception with the above bad MessageListener...
final Message message = mock(Message.class);
// a Throwable from a MessageListener MUST simply be swallowed...
messageConsumer.sendMessage(message);
verify(connection).setExceptionListener(this.container);
verify(connection).start();
}
use of jakarta.jms.MessageConsumer 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);
}
}
Aggregations