2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.logging.context;
19 import java.net.InetAddress;
20 import java.net.UnknownHostException;
23 * Holds a reference to local host address as returned by Java runtime. A value of host address will be cached for the
24 * interval specified in the constructor or {@link #DEFAULT_REFRESH_INTERVAL}. The caching helps to avoid many low-level
25 * calls, but at the same time pick up any IP or FQDN changes. Although the underlying JDK implementation uses caching
26 * too, the refresh interval for logging may be much longer due to the nature of the use.
31 @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace", "squid:S106", "squid:S1148"})
32 public class HostAddress {
34 private static final long DEFAULT_REFRESH_INTERVAL = 60000L; // 1 min
36 private final long interval;
38 private CacheEntry cachedAddress;
40 public HostAddress() {
41 this(DEFAULT_REFRESH_INTERVAL);
45 * Creates a cache for host address with a custom refresh interval.
47 public HostAddress(long refreshInterval) {
48 this.interval = refreshInterval;
49 this.cachedAddress = new CacheEntry(System.currentTimeMillis(), read());
53 * Returns an address (host name and IP address) of the local system.
55 * @return local host address or <code>null</code> if it could not be read for some reason
57 public synchronized InetAddress get() {
59 long current = System.currentTimeMillis();
60 if (current - cachedAddress.lastUpdated < interval) {
61 return cachedAddress.address;
64 InetAddress address = read();
65 cachedAddress = new CacheEntry(current, address);
69 private InetAddress read() {
72 return InetAddress.getLocalHost();
73 } catch (UnknownHostException e) {
74 e.printStackTrace(); // can't really use logging
75 return null; // let register the attempt even if failed
79 private static class CacheEntry {
81 private final long lastUpdated;
82 private final InetAddress address;
84 private CacheEntry(long lastUpdated, InetAddress address) {
85 this.lastUpdated = lastUpdated;
86 this.address = address;