Search in sources :

Example 16 with Message

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

the class JmsListenerContainerFactoryIntegrationTests method testMessageConverterIsUsed.

private void testMessageConverterIsUsed() throws JMSException {
    MethodJmsListenerEndpoint endpoint = createDefaultMethodJmsEndpoint(this.listener.getClass(), "handleIt", String.class, String.class);
    Message message = new StubTextMessage("foo-bar");
    message.setStringProperty("my-header", "my-value");
    invokeListener(endpoint, message);
    assertListenerMethodInvocation("handleIt");
}
Also used : Message(jakarta.jms.Message) StubTextMessage(org.springframework.jms.StubTextMessage) TextMessage(jakarta.jms.TextMessage) StubTextMessage(org.springframework.jms.StubTextMessage)

Example 17 with Message

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

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

the class JmsTemplate method doReceive.

/**
 * Actually receive a JMS message.
 * @param session the JMS Session to operate on
 * @param consumer the JMS MessageConsumer to receive with
 * @return the JMS Message received, or {@code null} if none
 * @throws JMSException if thrown by JMS API methods
 */
@Nullable
protected Message doReceive(Session session, MessageConsumer consumer) throws JMSException {
    try {
        // Use transaction timeout (if available).
        long timeout = getReceiveTimeout();
        ConnectionFactory connectionFactory = getConnectionFactory();
        JmsResourceHolder resourceHolder = null;
        if (connectionFactory != null) {
            resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(connectionFactory);
        }
        if (resourceHolder != null && resourceHolder.hasTimeout()) {
            timeout = Math.min(timeout, resourceHolder.getTimeToLiveInMillis());
        }
        Message message = receiveFromConsumer(consumer, timeout);
        if (session.getTransacted()) {
            // Commit necessary - but avoid commit call within a JTA transaction.
            if (isSessionLocallyTransacted(session)) {
                // Transacted session created by this template -> commit.
                JmsUtils.commitIfNecessary(session);
            }
        } else if (isClientAcknowledge(session)) {
            // Manually acknowledge message, if any.
            if (message != null) {
                message.acknowledge();
            }
        }
        return message;
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
    }
}
Also used : ConnectionFactory(jakarta.jms.ConnectionFactory) JmsResourceHolder(org.springframework.jms.connection.JmsResourceHolder) Message(jakarta.jms.Message) Nullable(org.springframework.lang.Nullable)

Example 19 with Message

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

the class JmsTemplate method doSendAndReceive.

/**
 * Send a request message to the given {@link Destination} and block until
 * a reply has been received on a temporary queue created on-the-fly.
 * <p>Return the response message or {@code null} if no message has
 * @throws JMSException if thrown by JMS API methods
 */
@Nullable
protected Message doSendAndReceive(Session session, Destination destination, MessageCreator messageCreator) throws JMSException {
    Assert.notNull(messageCreator, "MessageCreator must not be null");
    TemporaryQueue responseQueue = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    try {
        Message requestMessage = messageCreator.createMessage(session);
        responseQueue = session.createTemporaryQueue();
        producer = session.createProducer(destination);
        consumer = session.createConsumer(responseQueue);
        requestMessage.setJMSReplyTo(responseQueue);
        if (logger.isDebugEnabled()) {
            logger.debug("Sending created message: " + requestMessage);
        }
        doSend(producer, requestMessage);
        return receiveFromConsumer(consumer, getReceiveTimeout());
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
        JmsUtils.closeMessageProducer(producer);
        if (responseQueue != null) {
            responseQueue.delete();
        }
    }
}
Also used : MessageConsumer(jakarta.jms.MessageConsumer) Message(jakarta.jms.Message) TemporaryQueue(jakarta.jms.TemporaryQueue) MessageProducer(jakarta.jms.MessageProducer) Nullable(org.springframework.lang.Nullable)

Example 20 with Message

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

the class MessageListenerAdapterTests method testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied.

@Test
void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
    final TextMessage sentTextMessage = mock(TextMessage.class);
    // correlation ID is queried when response is being created...
    given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID);
    // Reply-To is queried when response is being created...
    given(sentTextMessage.getJMSReplyTo()).willReturn(null);
    TextMessage responseTextMessage = mock(TextMessage.class);
    final QueueSession session = mock(QueueSession.class);
    given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage);
    ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
    given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);
    final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {

        @Override
        protected Object extractMessage(Message message) {
            return message;
        }
    };
    assertThatExceptionOfType(ReplyFailureException.class).isThrownBy(() -> adapter.onMessage(sentTextMessage, session)).withCauseExactlyInstanceOf(InvalidDestinationException.class);
    verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID);
    verify(delegate).handleMessage(sentTextMessage);
}
Also used : Message(jakarta.jms.Message) BytesMessage(jakarta.jms.BytesMessage) TextMessage(jakarta.jms.TextMessage) ObjectMessage(jakarta.jms.ObjectMessage) TextMessage(jakarta.jms.TextMessage) QueueSession(jakarta.jms.QueueSession) Test(org.junit.jupiter.api.Test)

Aggregations

Message (jakarta.jms.Message)30 Test (org.junit.jupiter.api.Test)23 TextMessage (jakarta.jms.TextMessage)19 Session (jakarta.jms.Session)18 BytesMessage (jakarta.jms.BytesMessage)13 ObjectMessage (jakarta.jms.ObjectMessage)13 ConnectionFactory (jakarta.jms.ConnectionFactory)9 Connection (jakarta.jms.Connection)8 QueueSession (jakarta.jms.QueueSession)7 MapMessage (jakarta.jms.MapMessage)6 MessageConsumer (jakarta.jms.MessageConsumer)6 MessageProducer (jakarta.jms.MessageProducer)6 SimpleMessageConverter (org.springframework.jms.support.converter.SimpleMessageConverter)6 JMSException (jakarta.jms.JMSException)5 Queue (jakarta.jms.Queue)4 Nullable (org.springframework.lang.Nullable)4 ExceptionListener (jakarta.jms.ExceptionListener)3 HashSet (java.util.HashSet)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 StubQueue (org.springframework.jms.StubQueue)3