View Javadoc
1   /*
2    * Copyright 2018 the original author or authors.
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package org.openehealth.ipf.commons.audit.queue;
18  
19  import org.openehealth.ipf.commons.audit.AuditContext;
20  import org.slf4j.Logger;
21  import org.slf4j.LoggerFactory;
22  
23  import javax.jms.JMSException;
24  import javax.jms.Message;
25  import javax.jms.MessageListener;
26  import javax.jms.TextMessage;
27  
28  import static java.util.Objects.requireNonNull;
29  
30  /**
31   * JMS Message Listener that receives audit messages from a queue and sends them
32   * to an audit repository. It is recommended to use infrastructure classes such
33   * as Spring's JMS MessageListenerContainers to control transactional behavior,
34   * message redelivery and other features.
35   *
36   * @author Christian Ohr
37   * @since 3.5
38   */
39  public class JmsAuditMessageListener implements MessageListener {
40  
41      private static final Logger LOG = LoggerFactory.getLogger(JmsAuditMessageListener.class);
42  
43      private final AuditContext auditContext;
44  
45      public JmsAuditMessageListener(AuditContext auditContext) {
46          this.auditContext = requireNonNull(auditContext, "AuditContext must not be null");
47      }
48  
49      @Override
50      public void onMessage(Message message) {
51          TextMessage textMessage = (TextMessage) message;
52          try {
53              String text = textMessage.getText();
54              auditContext.getAuditTransmissionProtocol().send(auditContext, text);
55          } catch (JMSException jmsException1) {
56              LOG.error("Could not obtain text from JMS message", jmsException1);
57          } catch (Exception e) {
58              LOG.warn("Could not send audit message, rolling back", e);
59              throw new RuntimeException(e);
60          }
61      }
62  }