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.utils;
18  
19  import java.lang.management.ManagementFactory;
20  import java.lang.management.RuntimeMXBean;
21  import java.net.DatagramSocket;
22  import java.net.InetAddress;
23  import java.util.Map;
24  import java.util.Optional;
25  import java.util.concurrent.ConcurrentHashMap;
26  
27  /**
28   * Utility functions for obtaining local system context such as
29   * local hostname or IP address
30   *
31   * @author Christian Ohr
32   * @since 3.5
33   */
34  public class AuditUtils {
35  
36      private static Map<String, String> systemData = new ConcurrentHashMap<>();
37  
38      private static final String PID = "PID";
39      private static final String IP = "IP";
40      private static final String HOST = "IP";
41      private static final String USER = "USER";
42  
43      /**
44       * @return the process ID of the running process or "unknown"
45       */
46      public static String getProcessId() {
47          return systemData.computeIfAbsent(PID, s -> {
48              RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
49              String name = mx.getName();
50              int pointer;
51              if ((pointer = name.indexOf('@')) != -1) {
52                  return name.substring(0, pointer);
53              }
54              return "unknown";
55          });
56      }
57  
58      /**
59       * @return the IP Address of the local host or "unknown"
60       */
61      public static String getLocalIPAddress() {
62          return systemData.computeIfAbsent(IP, s ->
63                  localInetAddress()
64                          .map(InetAddress::getHostAddress)
65                          .orElse("unknown")).trim();
66      }
67  
68      /**
69       * @return the name of the host or "unknown"
70       */
71      public static String getLocalHostName() {
72          return systemData.computeIfAbsent(HOST, s ->
73                  localInetAddress()
74                          .map(InetAddress::getCanonicalHostName)
75                          .orElse("unknown")).trim();
76      }
77  
78      /**
79       * @return the name of the user running the process
80       */
81      public static String getUserName() {
82          return systemData.computeIfAbsent(HOST, s -> System.getProperty("user.name"));
83      }
84  
85      /**
86       * @param url a (remote) url
87       * @return the host name extracted from the provided URL
88       */
89      public static String getHostFromUrl(String url) {
90          if (url == null) return null;
91  
92          // drop schema
93          int pos = url.indexOf("://");
94          if (pos > 0) {
95              url = url.substring(pos + 3);
96          }
97  
98          // drop user authentication information
99          pos = url.indexOf('@');
100         if (pos > 0) {
101             url = url.substring(pos + 1);
102         }
103 
104         // drop trailing parts: port number, query parameters, path, fragment
105         for (int i = 0; i < url.length(); ++i) {
106             char c = url.charAt(i);
107             if ((c == ':') || (c == '?') || (c == '/') || (c == '#')) {
108                 return url.substring(0, i);
109             }
110         }
111         return url;
112     }
113 
114     public static Optional<InetAddress> localInetAddress() {
115         try (DatagramSocket socket = new DatagramSocket()) {
116             socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
117             return Optional.of(socket.getLocalAddress());
118         } catch (Exception e) {
119             return Optional.empty();
120         }
121     }
122 }