1212
1313@ Singleton
1414public class Security {
15- private final static boolean isRoot ;
15+ private static Boolean isRoot ;
1616 public static final String SECRET_PROPERTY_KEY = "power-server.sudo.secret" ;
1717
18- static {
19- isRoot = isRunningAsAdministrator ();
20- }
21-
2218 private final String pwd ;
2319
2420 public Security (SmallRyeConfig config ) {
2521 pwd = config .getConfigValue (SECRET_PROPERTY_KEY ).getValue ();
26- if (pwd == null && !isRoot ) {
22+ if (pwd == null && !isRunningAsAdministrator () ) {
2723 throw new IllegalStateException (
2824 "This application requires sudo access. Either provide a sudo secret using the 'power-server.sudo.secret' property or run using sudo." );
2925 }
@@ -32,26 +28,29 @@ public Security(SmallRyeConfig config) {
3228 // figure out if we're running as admin by trying to write a system-level preference
3329 // see: https://stackoverflow.com/a/23538961/5752008
3430 private synchronized static boolean isRunningAsAdministrator () {
35- final var preferences = Preferences .systemRoot ();
31+ if (isRoot == null ) {
32+ final var preferences = Preferences .systemRoot ();
3633
37- // avoid outputting errors
38- System .setErr (new PrintStream (new OutputStream () {
39- @ Override
40- public void write (int b ) {
41- }
42- }));
34+ // avoid outputting errors
35+ System .setErr (new PrintStream (new OutputStream () {
36+ @ Override
37+ public void write (int b ) {
38+ }
39+ }));
4340
44- try {
45- preferences .put ("foo" , "bar" ); // SecurityException on Windows
46- preferences .remove ("foo" );
47- preferences .flush (); // BackingStoreException on Linux and macOS
48- return true ;
49- } catch (Exception exception ) {
50- return false ;
51- } finally {
52- System .setErr (System .err );
41+ try {
42+ preferences .put ("foo" , "bar" ); // SecurityException on Windows
43+ preferences .remove ("foo" );
44+ preferences .flush (); // BackingStoreException on Linux and macOS
45+ isRoot = true ;
46+ } catch (Exception exception ) {
47+ isRoot = false ;
48+ } finally {
49+ System .setErr (System .err );
50+ }
5351 }
5452
53+ return isRoot ;
5554 }
5655
5756 public Process execPowermetrics (String ... options ) throws IOException {
@@ -70,7 +69,7 @@ public Process sudo(String... cmd) throws IOException {
7069 throw new IllegalArgumentException ("No command specified to run with sudo" );
7170 }
7271
73- if (!isRoot ) {
72+ if (!isRunningAsAdministrator () ) {
7473 final var args = new String [cmd .length + 2 ];
7574 args [0 ] = "sudo" ;
7675 args [1 ] = "-S" ;
0 commit comments