Search in sources :

Example 1 with JmsException

use of org.springframework.jms.JmsException in project opennms by OpenNMS.

the class JmsNorthbounder method forwardAlarms.

/* (non-Javadoc)
     * @see org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder#forwardAlarms(java.util.List)
     */
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
    for (final NorthboundAlarm alarm : alarms) {
        final Integer count = alarm.getCount();
        LOG.debug("Does destination {} take only first occurances? {} Is new alarm? Has count of {}.", m_jmsDestination.getName(), m_jmsDestination.isFirstOccurrenceOnly(), count);
        if (count > 1 && m_jmsDestination.isFirstOccurrenceOnly()) {
            LOG.debug("Skipping because not new alarm.");
            continue;
        }
        LOG.debug("Attempting to send a message to {} of type {}", m_jmsDestination.getJmsDestination(), m_jmsDestination.getDestinationType());
        try {
            m_template.send(m_jmsDestination.getJmsDestination(), new MessageCreator() {

                @Override
                public Message createMessage(Session session) throws JMSException {
                    if (m_jmsDestination.isSendAsObjectMessageEnabled()) {
                        return session.createObjectMessage(alarm);
                    } else {
                        return session.createTextMessage(convertAlarmToText(alarm));
                    }
                }
            });
            LOG.debug("Sent message");
        } catch (JmsException e) {
            LOG.error("Unable to send alarm to northbound JMS because {}", e.getLocalizedMessage(), e);
        }
    }
}
Also used : Message(javax.jms.Message) JmsException(org.springframework.jms.JmsException) NorthboundAlarm(org.opennms.netmgt.alarmd.api.NorthboundAlarm) JMSException(javax.jms.JMSException) MessageCreator(org.springframework.jms.core.MessageCreator) Session(javax.jms.Session)

Example 2 with JmsException

use of org.springframework.jms.JmsException 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();
        }
    }
}
Also used : BackOffExecution(org.springframework.util.backoff.BackOffExecution) Connection(jakarta.jms.Connection) JMSException(jakarta.jms.JMSException) JmsException(org.springframework.jms.JmsException) JMSException(jakarta.jms.JMSException)

Example 3 with JmsException

use of org.springframework.jms.JmsException in project spring-framework by spring-projects.

the class JmsUtils method buildExceptionMessage.

/**
 * Build a descriptive exception message for the given JMSException,
 * incorporating a linked exception's message if appropriate.
 * @param ex the JMSException to build a message for
 * @return the descriptive message String
 * @see jakarta.jms.JMSException#getLinkedException()
 */
public static String buildExceptionMessage(JMSException ex) {
    String message = ex.getMessage();
    Exception linkedEx = ex.getLinkedException();
    if (linkedEx != null) {
        if (message == null) {
            message = linkedEx.toString();
        } else {
            String linkedMessage = linkedEx.getMessage();
            if (linkedMessage != null && !message.contains(linkedMessage)) {
                message = message + "; nested exception is " + linkedEx;
            }
        }
    }
    return message;
}
Also used : JmsException(org.springframework.jms.JmsException) MessageNotReadableException(org.springframework.jms.MessageNotReadableException) UncategorizedJmsException(org.springframework.jms.UncategorizedJmsException) JMSException(jakarta.jms.JMSException) TransactionInProgressException(org.springframework.jms.TransactionInProgressException) InvalidDestinationException(org.springframework.jms.InvalidDestinationException) MessageNotWriteableException(org.springframework.jms.MessageNotWriteableException) ResourceAllocationException(org.springframework.jms.ResourceAllocationException) MessageFormatException(org.springframework.jms.MessageFormatException) MessageEOFException(org.springframework.jms.MessageEOFException) TransactionRolledBackException(org.springframework.jms.TransactionRolledBackException) InvalidClientIDException(org.springframework.jms.InvalidClientIDException) JmsSecurityException(org.springframework.jms.JmsSecurityException) InvalidSelectorException(org.springframework.jms.InvalidSelectorException)

Example 4 with JmsException

use of org.springframework.jms.JmsException in project ORCID-Source by ORCID.

the class HandleFailedMessages method resendFailedElements.

@Scheduled(cron = "${org.orcid.cron.reindex-failed}")
public void resendFailedElements() {
    List<RecordStatusEntity> failedElements = manager.getFailedElements(BATCH_SIZE);
    List<RecordStatusEntity> elementsToNotify = new ArrayList<RecordStatusEntity>();
    for (RecordStatusEntity element : failedElements) {
        try {
            // Send RetryMessage for 1.2 dump
            if (element.getDumpStatus12Api() > 0) {
                RetryMessage message = new RetryMessage(element.getId(), AvailableBroker.DUMP_STATUS_1_2_API.value());
                jmsTemplate.convertAndSend(MessageConstants.Queues.RETRY, message.getMap());
            }
            // Send RetryMessage for 2.0 dump
            if (element.getDumpStatus20Api() > 0) {
                RetryMessage message = new RetryMessage(element.getId(), AvailableBroker.DUMP_STATUS_2_0_API.value());
                jmsTemplate.convertAndSend(MessageConstants.Queues.RETRY, message.getMap());
            }
            // Send RetryMessage for solr indexing
            if (element.getSolrStatus20Api() > 0) {
                RetryMessage message = new RetryMessage(element.getId(), AvailableBroker.SOLR.value());
                jmsTemplate.convertAndSend(MessageConstants.Queues.RETRY, message.getMap());
            }
            // Send RetryMessage for 2.0 activities dump
            if (element.getDumpStatus20ActivitiesApi() > 0) {
                RetryMessage message = new RetryMessage(element.getId(), AvailableBroker.DUMP_STATUS_2_0_ACTIVITIES_API.value());
                jmsTemplate.convertAndSend(MessageConstants.Queues.RETRY, message.getMap());
            }
            // Should we notify about this element?
            if ((element.getDumpStatus12Api() > maxFailuresBeforeNotify) || (element.getDumpStatus20Api() > maxFailuresBeforeNotify) || (element.getSolrStatus20Api() > maxFailuresBeforeNotify) || (element.getDumpStatus20ActivitiesApi() > maxFailuresBeforeNotify)) {
                elementsToNotify.add(element);
            }
        } catch (JmsException e) {
            LOGGER.warn("Unable to resend message for " + element.getId());
        }
    }
    // Send summary
    if (!elementsToNotify.isEmpty()) {
        String message = buildNotificationMessage(elementsToNotify);
        sendSystemAlert(message);
    }
}
Also used : RecordStatusEntity(org.orcid.listener.persistence.entities.RecordStatusEntity) JmsException(org.springframework.jms.JmsException) ArrayList(java.util.ArrayList) RetryMessage(org.orcid.utils.listener.RetryMessage) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 5 with JmsException

use of org.springframework.jms.JmsException in project spring-integration by spring-projects.

the class JmsOutboundGatewayTests method testReplyContainerRecovery.

@SuppressWarnings("serial")
@Test
public void testReplyContainerRecovery() throws Exception {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestinationName("foo");
    gateway.setUseReplyContainer(true);
    ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties();
    final List<Throwable> errors = new ArrayList<Throwable>();
    ExecutorService exec = Executors.newFixedThreadPool(10);
    ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor(exec, t -> {
        errors.add(t);
        throw new RuntimeException(t);
    });
    replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor);
    replyContainerProperties.setRecoveryInterval(100L);
    gateway.setReplyContainerProperties(replyContainerProperties);
    final Connection connection = mock(Connection.class);
    final AtomicInteger connectionAttempts = new AtomicInteger();
    doAnswer(invocation -> {
        int theCount = connectionAttempts.incrementAndGet();
        if (theCount > 1 && theCount < 4) {
            throw new JmsException("bar") {
            };
        }
        return connection;
    }).when(connectionFactory).createConnection();
    Session session = mock(Session.class);
    when(connection.createSession(false, 1)).thenReturn(session);
    MessageConsumer consumer = mock(MessageConsumer.class);
    when(session.createConsumer(any(Destination.class), isNull())).thenReturn(consumer);
    when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class));
    final Message message = mock(Message.class);
    final AtomicInteger count = new AtomicInteger();
    doAnswer(invocation -> {
        int theCount = count.incrementAndGet();
        if (theCount > 1 && theCount < 4) {
            throw new JmsException("foo") {
            };
        }
        if (theCount > 4) {
            Thread.sleep(100);
            return null;
        }
        return message;
    }).when(consumer).receive(anyLong());
    when(message.getJMSCorrelationID()).thenReturn("foo");
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    beanFactory.registerSingleton("taskScheduler", taskScheduler);
    gateway.setBeanFactory(beanFactory);
    gateway.afterPropertiesSet();
    gateway.start();
    try {
        int n = 0;
        while (n++ < 100 && count.get() < 5) {
            Thread.sleep(100);
        }
        assertTrue(count.get() > 4);
        assertEquals(0, errors.size());
    } finally {
        gateway.stop();
        exec.shutdownNow();
    }
}
Also used : Destination(javax.jms.Destination) MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) GenericMessage(org.springframework.messaging.support.GenericMessage) JmsException(org.springframework.jms.JmsException) ArrayList(java.util.ArrayList) Connection(javax.jms.Connection) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) CachingConnectionFactory(org.springframework.jms.connection.CachingConnectionFactory) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) ConnectionFactory(javax.jms.ConnectionFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReplyContainerProperties(org.springframework.integration.jms.JmsOutboundGateway.ReplyContainerProperties) ExecutorService(java.util.concurrent.ExecutorService) TemporaryQueue(javax.jms.TemporaryQueue) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) Session(javax.jms.Session) Test(org.junit.Test)

Aggregations

JmsException (org.springframework.jms.JmsException)6 JMSException (jakarta.jms.JMSException)3 ArrayList (java.util.ArrayList)2 Message (javax.jms.Message)2 Session (javax.jms.Session)2 InvalidClientIDException (org.springframework.jms.InvalidClientIDException)2 InvalidDestinationException (org.springframework.jms.InvalidDestinationException)2 InvalidSelectorException (org.springframework.jms.InvalidSelectorException)2 JmsSecurityException (org.springframework.jms.JmsSecurityException)2 MessageEOFException (org.springframework.jms.MessageEOFException)2 MessageFormatException (org.springframework.jms.MessageFormatException)2 MessageNotReadableException (org.springframework.jms.MessageNotReadableException)2 MessageNotWriteableException (org.springframework.jms.MessageNotWriteableException)2 ResourceAllocationException (org.springframework.jms.ResourceAllocationException)2 TransactionInProgressException (org.springframework.jms.TransactionInProgressException)2 TransactionRolledBackException (org.springframework.jms.TransactionRolledBackException)2 UncategorizedJmsException (org.springframework.jms.UncategorizedJmsException)2 Connection (jakarta.jms.Connection)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1