55import com .fasterxml .jackson .databind .ObjectMapper ;
66import com .google .common .base .Splitter ;
77import com .google .common .collect .ImmutableList ;
8+ import java .io .BufferedReader ;
9+ import java .io .IOException ;
10+ import java .io .InputStreamReader ;
811import java .net .Inet4Address ;
912import java .net .InetAddress ;
1013import java .net .NetworkInterface ;
1114import java .net .SocketException ;
12- import java .util .Collections ;
13- import java .util .Enumeration ;
14- import java .util .List ;
15- import java .util .MissingResourceException ;
16- import java .util .ResourceBundle ;
15+ import java .util .*;
1716import java .util .function .Supplier ;
17+ import java .util .logging .Logger ;
1818import javax .annotation .Nonnull ;
1919import javax .annotation .Nullable ;
2020import javax .ws .rs .core .Response ;
@@ -31,6 +31,8 @@ public abstract class Utils {
3131 private static final ResourceBundle buildProps = ResourceBundle .getBundle ("build" );
3232 private static final List <Integer > UUID_SEGMENTS = ImmutableList .of (8 , 4 , 4 , 4 , 12 );
3333
34+ private static final Logger log = Logger .getLogger (Utils .class .getCanonicalName ());
35+
3436 /**
3537 * A lazy initialization wrapper for {@code Supplier}
3638 *
@@ -155,6 +157,27 @@ public static String getJavaVersion() {
155157 * @return name for localhost
156158 */
157159 public static String getLocalHostName () {
160+ for (String env : Arrays .asList ("COMPUTERNAME" , "HOSTNAME" , "PROXY_HOSTNAME" )) {
161+ String hostname = System .getenv (env );
162+ if (StringUtils .isNotBlank (hostname )) {
163+ log .info ("Hostname: '" + hostname + "' (detected using '" + env + "' env variable)" );
164+ return hostname ;
165+ }
166+ }
167+
168+ try {
169+ String hostname =
170+ new BufferedReader (
171+ new InputStreamReader (Runtime .getRuntime ().exec ("hostname" ).getInputStream ()))
172+ .readLine ();
173+ if (StringUtils .isNotBlank (hostname )) {
174+ log .info ("Hostname: '" + hostname + "' (detected using 'hostname' command)" );
175+ return hostname ;
176+ }
177+ } catch (IOException e ) {
178+ log .fine ("Error running 'hostname' command. " + e .getMessage ());
179+ }
180+
158181 InetAddress localAddress = null ;
159182 try {
160183 Enumeration <NetworkInterface > nics = NetworkInterface .getNetworkInterfaces ();
@@ -184,8 +207,12 @@ public static String getLocalHostName() {
184207 // ignore
185208 }
186209 if (localAddress != null ) {
187- return localAddress .getCanonicalHostName ();
210+ String hostname = localAddress .getCanonicalHostName ();
211+ log .info ("Hostname: '" + hostname + "' (detected using network interfaces)" );
212+ return hostname ;
188213 }
214+
215+ log .info ("Hostname not detected, using 'localhost')" );
189216 return "localhost" ;
190217 }
191218
0 commit comments