12
12
13
13
@ Singleton
14
14
public class Security {
15
- private final static boolean isRoot ;
15
+ private static Boolean isRoot ;
16
16
public static final String SECRET_PROPERTY_KEY = "power-server.sudo.secret" ;
17
17
18
- static {
19
- isRoot = isRunningAsAdministrator ();
20
- }
21
-
22
18
private final String pwd ;
23
19
24
20
public Security (SmallRyeConfig config ) {
25
21
pwd = config .getConfigValue (SECRET_PROPERTY_KEY ).getValue ();
26
- if (pwd == null && !isRoot ) {
22
+ if (pwd == null && !isRunningAsAdministrator () ) {
27
23
throw new IllegalStateException (
28
24
"This application requires sudo access. Either provide a sudo secret using the 'power-server.sudo.secret' property or run using sudo." );
29
25
}
@@ -32,26 +28,29 @@ public Security(SmallRyeConfig config) {
32
28
// figure out if we're running as admin by trying to write a system-level preference
33
29
// see: https://stackoverflow.com/a/23538961/5752008
34
30
private synchronized static boolean isRunningAsAdministrator () {
35
- final var preferences = Preferences .systemRoot ();
31
+ if (isRoot == null ) {
32
+ final var preferences = Preferences .systemRoot ();
36
33
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
+ }));
43
40
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
+ }
53
51
}
54
52
53
+ return isRoot ;
55
54
}
56
55
57
56
public Process execPowermetrics (String ... options ) throws IOException {
@@ -70,7 +69,7 @@ public Process sudo(String... cmd) throws IOException {
70
69
throw new IllegalArgumentException ("No command specified to run with sudo" );
71
70
}
72
71
73
- if (!isRoot ) {
72
+ if (!isRunningAsAdministrator () ) {
74
73
final var args = new String [cmd .length + 2 ];
75
74
args [0 ] = "sudo" ;
76
75
args [1 ] = "-S" ;
0 commit comments