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  package org.openehealth.ipf.commons.audit.protocol;
17  
18  
19  import java.nio.charset.StandardCharsets;
20  import java.time.Instant;
21  
22  import static java.util.Objects.requireNonNull;
23  
24  /**
25   * Base client implementation of RFC 5424 syslog for sending audit messages to an Audit Record Repository
26   * that implements RFC 5424 SYSLOG.
27   *
28   * @author Christian Ohr
29   * @since 3.5
30   */
31  public class RFC5424Protocol {
32  
33      /**
34       * Default syslog priority for this transport, according to
35       * http://dicom.nema.org/medical/dicom/current/output/html/part15.html#sect_A.6
36       */
37      private static final int TRANSPORT_PRI = 10 * 8 + 5;
38  
39      /**
40       * Default syslog MSGID for this transport, according to
41       * http://dicom.nema.org/medical/dicom/current/output/html/part15.html#sect_A.6
42       */
43      private static final String TRANSPORT_MSGID = "IHE+RFC-3881";
44  
45      private final String senderHostName;
46      private final String senderProcessId;
47  
48      public RFC5424Protocol(String senderHostName, String senderProcessId) {
49          this.senderHostName = requireNonNull(senderHostName);
50          this.senderProcessId = requireNonNull(senderProcessId);
51      }
52  
53      /**
54       * Serialize the syslog message payload body for sending by this transport
55       *
56       * @param auditMessage Message to prepare
57       * @return serialized message
58       */
59      protected byte[] getTransportPayload(String sendingApplication, String auditMessage) {
60          String msg = String.format("<%s>1 %s %s %s %s %s - \uFEFF<?xml version=\"1.0\" encoding=\"UTF-8\"?>%s",
61                  TRANSPORT_PRI,
62                  Instant.now(),
63                  senderHostName,
64                  sendingApplication,
65                  senderProcessId,
66                  TRANSPORT_MSGID,
67                  auditMessage);
68          return msg.trim().getBytes(StandardCharsets.UTF_8);
69      }
70  
71  }