View Javadoc
1   /*
2    * Copyright 2017 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.openehealth.ipf.commons.audit.AuditException;
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  import java.util.concurrent.CompletableFuture;
25  import java.util.concurrent.ExecutorService;
26  import java.util.concurrent.TimeUnit;
27  
28  /**
29   * Audit queue that uses an injectable {@link ExecutorService} to asynchonously send away audit events.
30   * When this queue is {@link #shutdown() shut down}, the executor service is also, waiting for at most
31   * {@link #shutdownTimeoutSeconds} until all pending events are sent.
32   * <p>
33   * Note that the {@link ExecutorService} must be explicitly set, otherwise the implementation sends away the event synchronously.
34   * The parameters of the {@link ExecutorService} determine the behavior of the queue implementation, e.g. in case the
35   * audit destination is not reachable.
36   * </p>
37   *
38   * @author Christian Ohr
39   * @since 3.5
40   */
41  public class AsynchronousAuditMessageQueue extends AbstractAuditMessageQueue {
42  
43      private static final Logger LOG = LoggerFactory.getLogger(AsynchronousAuditMessageQueue.class);
44  
45      private ExecutorService executorService;
46      private int shutdownTimeoutSeconds = 30;
47  
48      /**
49       * Sets the executor service. If this is null (or not used), audit events are sent synchronously
50       *
51       * @param executorService executor service
52       */
53      public void setExecutorService(ExecutorService executorService) {
54          this.executorService = executorService;
55      }
56  
57      /**
58       * Sets the timeout before the executor service closes. Defaults to 10
59       *
60       * @param shutdownTimeoutSeconds timeout before the executor service closes
61       */
62      public void setShutdownTimeoutSeconds(int shutdownTimeoutSeconds) {
63          this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
64      }
65  
66      @Override
67      protected void handle(AuditContext auditContext, String... auditRecords) {
68          Runnable runnable = runnable(auditContext, auditRecords);
69          if (executorService != null && !executorService.isShutdown()) {
70              CompletableFuture.runAsync(runnable, executorService)
71                      .exceptionally(e -> {
72                          auditContext.getAuditExceptionHandler().handleException(auditContext, e, auditRecords);
73                          return null;
74                      });
75          } else {
76              runnable.run();
77          }
78      }
79  
80      private Runnable runnable(AuditContext auditContext, String... auditRecords) {
81          return () -> {
82              try {
83                  auditContext.getAuditTransmissionProtocol().send(auditContext, auditRecords);
84              } catch (Exception e) {
85                  throw new AuditException(e);
86              }
87          };
88      }
89  
90      @Override
91      public void shutdown() {
92          if (executorService != null) {
93              executorService.shutdown();
94              try {
95                  if (!executorService.awaitTermination(shutdownTimeoutSeconds, TimeUnit.SECONDS)) {
96                      LOG.warn("Timeout occurred when flushing Audit events, some events might have been lost");
97                      executorService.shutdownNow();
98                  }
99              } catch (InterruptedException e) {
100                 LOG.warn("Thread interrupt when flushing ATNA events, some events might have been lost", e);
101             }
102         }
103     }
104 
105 }