Search in sources :

Example 1 with MessageConsumer

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();
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) Message(jakarta.jms.Message) TextMessage(jakarta.jms.TextMessage) TemporaryQueue(jakarta.jms.TemporaryQueue) MessageProducer(jakarta.jms.MessageProducer) TextMessage(jakarta.jms.TextMessage) Session(jakarta.jms.Session)

Example 2 with MessageConsumer

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();
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) ConnectionFactory(jakarta.jms.ConnectionFactory) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) Connection(jakarta.jms.Connection) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Example 3 with MessageConsumer

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();
}
Also used : Message(jakarta.jms.Message) StubQueue(org.springframework.jms.StubQueue) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Set(java.util.Set) JMSException(jakarta.jms.JMSException) MessageListener(jakarta.jms.MessageListener) ExceptionListener(jakarta.jms.ExceptionListener) Session(jakarta.jms.Session) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) Mockito.verify(org.mockito.Mockito.verify) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) ErrorHandler(org.springframework.util.ErrorHandler) Assertions.fail(org.assertj.core.api.Assertions.fail) MessageConsumer(jakarta.jms.MessageConsumer) BDDMockito.given(org.mockito.BDDMockito.given) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Nullable(org.springframework.lang.Nullable) ConnectionFactory(jakarta.jms.ConnectionFactory) Connection(jakarta.jms.Connection) Mockito.mock(org.mockito.Mockito.mock) ConnectionFactory(jakarta.jms.ConnectionFactory) Message(jakarta.jms.Message) Connection(jakarta.jms.Connection) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Example 4 with MessageConsumer

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();
}
Also used : Message(jakarta.jms.Message) StubQueue(org.springframework.jms.StubQueue) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Set(java.util.Set) JMSException(jakarta.jms.JMSException) MessageListener(jakarta.jms.MessageListener) ExceptionListener(jakarta.jms.ExceptionListener) Session(jakarta.jms.Session) GenericApplicationContext(org.springframework.context.support.GenericApplicationContext) Mockito.verify(org.mockito.Mockito.verify) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) ErrorHandler(org.springframework.util.ErrorHandler) Assertions.fail(org.assertj.core.api.Assertions.fail) MessageConsumer(jakarta.jms.MessageConsumer) BDDMockito.given(org.mockito.BDDMockito.given) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Nullable(org.springframework.lang.Nullable) ConnectionFactory(jakarta.jms.ConnectionFactory) Connection(jakarta.jms.Connection) Mockito.mock(org.mockito.Mockito.mock) ConnectionFactory(jakarta.jms.ConnectionFactory) Message(jakarta.jms.Message) Connection(jakarta.jms.Connection) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Example 5 with MessageConsumer

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);
    }
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) Message(jakarta.jms.Message) Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session)

Aggregations

MessageConsumer (jakarta.jms.MessageConsumer)11 Session (jakarta.jms.Session)8 Connection (jakarta.jms.Connection)7 Message (jakarta.jms.Message)6 ConnectionFactory (jakarta.jms.ConnectionFactory)5 Test (org.junit.jupiter.api.Test)5 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)4 JMSException (jakarta.jms.JMSException)3 Nullable (org.springframework.lang.Nullable)3 ExceptionListener (jakarta.jms.ExceptionListener)2 MessageListener (jakarta.jms.MessageListener)2 MessageProducer (jakarta.jms.MessageProducer)2 TemporaryQueue (jakarta.jms.TemporaryQueue)2 TextMessage (jakarta.jms.TextMessage)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)2 Assertions.fail (org.assertj.core.api.Assertions.fail)2 BDDMockito.given (org.mockito.BDDMockito.given)2