Search in sources :

Example 31 with JMSException

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

the class SimpleJmsHeaderMapper method toHeaders.

@Override
public MessageHeaders toHeaders(jakarta.jms.Message jmsMessage) {
    Map<String, Object> headers = new HashMap<>();
    try {
        try {
            String correlationId = jmsMessage.getJMSCorrelationID();
            if (correlationId != null) {
                headers.put(JmsHeaders.CORRELATION_ID, correlationId);
            }
        } catch (Exception ex) {
            logger.debug("Failed to read JMSCorrelationID property - skipping", ex);
        }
        try {
            Destination destination = jmsMessage.getJMSDestination();
            if (destination != null) {
                headers.put(JmsHeaders.DESTINATION, destination);
            }
        } catch (Exception ex) {
            logger.debug("Failed to read JMSDestination property - skipping", ex);
        }
        try {
            int deliveryMode = jmsMessage.getJMSDeliveryMode();
            headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode);
        } catch (Exception ex) {
            logger.debug("Failed to read JMSDeliveryMode property - skipping", ex);
        }
        try {
            long expiration = jmsMessage.getJMSExpiration();
            headers.put(JmsHeaders.EXPIRATION, expiration);
        } catch (Exception ex) {
            logger.debug("Failed to read JMSExpiration property - skipping", ex);
        }
        try {
            String messageId = jmsMessage.getJMSMessageID();
            if (messageId != null) {
                headers.put(JmsHeaders.MESSAGE_ID, messageId);
            }
        } catch (Exception ex) {
            logger.debug("Failed to read JMSMessageID property - skipping", ex);
        }
        try {
            headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority());
        } catch (Exception ex) {
            logger.debug("Failed to read JMSPriority property - skipping", ex);
        }
        try {
            Destination replyTo = jmsMessage.getJMSReplyTo();
            if (replyTo != null) {
                headers.put(JmsHeaders.REPLY_TO, replyTo);
            }
        } catch (Exception ex) {
            logger.debug("Failed to read JMSReplyTo property - skipping", ex);
        }
        try {
            headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered());
        } catch (Exception ex) {
            logger.debug("Failed to read JMSRedelivered property - skipping", ex);
        }
        try {
            String type = jmsMessage.getJMSType();
            if (type != null) {
                headers.put(JmsHeaders.TYPE, type);
            }
        } catch (Exception ex) {
            logger.debug("Failed to read JMSType property - skipping", ex);
        }
        try {
            headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp());
        } catch (Exception ex) {
            logger.debug("Failed to read JMSTimestamp property - skipping", ex);
        }
        Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames();
        if (jmsPropertyNames != null) {
            while (jmsPropertyNames.hasMoreElements()) {
                String propertyName = jmsPropertyNames.nextElement().toString();
                try {
                    String headerName = this.toHeaderName(propertyName);
                    headers.put(headerName, jmsMessage.getObjectProperty(propertyName));
                } catch (Exception ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Error occurred while mapping JMS property '" + propertyName + "' to Message header", ex);
                    }
                }
            }
        }
    } catch (JMSException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error occurred while mapping from JMS properties to MessageHeaders", ex);
        }
    }
    return new MessageHeaders(headers);
}
Also used : Destination(jakarta.jms.Destination) HashMap(java.util.HashMap) JMSException(jakarta.jms.JMSException) MessageHeaders(org.springframework.messaging.MessageHeaders) JMSException(jakarta.jms.JMSException)

Example 32 with JMSException

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

the class JmsTransactionManager method doCommit.

@Override
protected void doCommit(DefaultTransactionStatus status) {
    JmsTransactionObject txObject = (JmsTransactionObject) status.getTransaction();
    Session session = txObject.getResourceHolder().getOriginalSession();
    if (session != null) {
        try {
            if (status.isDebug()) {
                logger.debug("Committing JMS transaction on Session [" + session + "]");
            }
            session.commit();
        } catch (TransactionRolledBackException ex) {
            throw new UnexpectedRollbackException("JMS transaction rolled back", ex);
        } catch (JMSException ex) {
            throw new TransactionSystemException("Could not commit JMS transaction", ex);
        }
    }
}
Also used : UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) TransactionRolledBackException(jakarta.jms.TransactionRolledBackException) JMSException(jakarta.jms.JMSException) TransactionSystemException(org.springframework.transaction.TransactionSystemException) Session(jakarta.jms.Session)

Example 33 with JMSException

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

the class AbstractPollingMessageListenerContainer method receiveAndExecute.

/**
 * Execute the listener for a message received from the given consumer,
 * wrapping the entire operation in an external transaction if demanded.
 * @param session the JMS Session to work on
 * @param consumer the MessageConsumer to work on
 * @return whether a message has been received
 * @throws JMSException if thrown by JMS methods
 * @see #doReceiveAndExecute
 */
protected boolean receiveAndExecute(Object invoker, @Nullable Session session, @Nullable MessageConsumer consumer) throws JMSException {
    if (this.transactionManager != null) {
        // Execute receive within transaction.
        TransactionStatus status = this.transactionManager.getTransaction(this.transactionDefinition);
        boolean messageReceived;
        try {
            messageReceived = doReceiveAndExecute(invoker, session, consumer, status);
        } catch (JMSException | RuntimeException | Error ex) {
            rollbackOnException(this.transactionManager, status, ex);
            throw ex;
        }
        try {
            this.transactionManager.commit(status);
        } catch (TransactionException ex) {
            // Propagate transaction system exceptions as infrastructure problems.
            throw ex;
        } catch (RuntimeException ex) {
            // Typically a late persistence exception from a listener-used resource
            // -> handle it as listener exception, not as an infrastructure problem.
            // E.g. a database locking failure should not lead to listener shutdown.
            handleListenerException(ex);
        }
        return messageReceived;
    } else {
        // Execute receive outside of transaction.
        return doReceiveAndExecute(invoker, session, consumer, null);
    }
}
Also used : TransactionException(org.springframework.transaction.TransactionException) TransactionStatus(org.springframework.transaction.TransactionStatus) JMSException(jakarta.jms.JMSException)

Example 34 with JMSException

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

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

the class JmsTemplate method execute.

/**
 * Execute the action specified by the given action object within a
 * JMS Session. Generalized version of {@code execute(SessionCallback)},
 * allowing the JMS Connection to be started on the fly.
 * <p>Use {@code execute(SessionCallback)} for the general case.
 * Starting the JMS Connection is just necessary for receiving messages,
 * which is preferably achieved through the {@code receive} methods.
 * @param action callback object that exposes the Session
 * @param startConnection whether to start the Connection
 * @return the result object from working with the Session
 * @throws JmsException if there is any problem
 * @see #execute(SessionCallback)
 * @see #receive
 */
@Nullable
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
    Assert.notNull(action, "Callback object must not be null");
    Connection conToClose = null;
    Session sessionToClose = null;
    try {
        Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(obtainConnectionFactory(), this.transactionalResourceFactory, startConnection);
        if (sessionToUse == null) {
            conToClose = createConnection();
            sessionToClose = createSession(conToClose);
            if (startConnection) {
                conToClose.start();
            }
            sessionToUse = sessionToClose;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing callback on JMS Session: " + sessionToUse);
        }
        return action.doInJms(sessionToUse);
    } catch (JMSException ex) {
        throw convertJmsAccessException(ex);
    } finally {
        JmsUtils.closeSession(sessionToClose);
        ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
    }
}
Also used : Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) Session(jakarta.jms.Session) Nullable(org.springframework.lang.Nullable)

Aggregations

JMSException (jakarta.jms.JMSException)38 Connection (jakarta.jms.Connection)21 Test (org.junit.jupiter.api.Test)20 ConnectionFactory (jakarta.jms.ConnectionFactory)18 Session (jakarta.jms.Session)16 Destination (jakarta.jms.Destination)10 Message (jakarta.jms.Message)10 MessageProducer (jakarta.jms.MessageProducer)8 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)8 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)8 BDDMockito.given (org.mockito.BDDMockito.given)8 Mockito.mock (org.mockito.Mockito.mock)8 Mockito.times (org.mockito.Mockito.times)8 Mockito.verify (org.mockito.Mockito.verify)8 TransactionStatus (org.springframework.transaction.TransactionStatus)8 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)8 AfterEach (org.junit.jupiter.api.AfterEach)7 StubQueue (org.springframework.jms.StubQueue)7 JmsTemplate (org.springframework.jms.core.JmsTemplate)7 SessionCallback (org.springframework.jms.core.SessionCallback)7