1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.util.internal;
17
18 import io.netty5.util.internal.logging.InternalLogger;
19 import io.netty5.util.internal.logging.InternalLoggerFactory;
20
21 import java.security.AccessController;
22 import java.security.PrivilegedAction;
23
24 import static io.netty5.util.internal.ObjectUtil.checkNonEmpty;
25
26
27
28
29 public final class SystemPropertyUtil {
30
31 private static final InternalLogger logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class);
32
33
34
35
36
37 public static boolean contains(String key) {
38 return get(key) != null;
39 }
40
41
42
43
44
45
46
47 public static String get(String key) {
48 return get(key, null);
49 }
50
51
52
53
54
55
56
57
58
59
60 public static String get(final String key, String def) {
61 checkNonEmpty(key, "key");
62
63 String value = null;
64 try {
65 if (System.getSecurityManager() == null) {
66 value = System.getProperty(key);
67 } else {
68 value = AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key));
69 }
70 } catch (SecurityException e) {
71 logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e);
72 }
73
74 if (value == null) {
75 return def;
76 }
77
78 return value;
79 }
80
81
82
83
84
85
86
87
88
89
90 public static boolean getBoolean(String key, boolean def) {
91 String value = get(key);
92 if (value == null) {
93 return def;
94 }
95
96 value = value.trim().toLowerCase();
97 if (value.isEmpty()) {
98 return def;
99 }
100
101 if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
102 return true;
103 }
104
105 if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
106 return false;
107 }
108
109 logger.warn(
110 "Unable to parse the boolean system property '{}':{} - using the default value: {}",
111 key, value, def
112 );
113
114 return def;
115 }
116
117
118
119
120
121
122
123
124
125
126 public static int getInt(String key, int def) {
127 String value = get(key);
128 if (value == null) {
129 return def;
130 }
131
132 value = value.trim();
133 try {
134 return Integer.parseInt(value);
135 } catch (Exception e) {
136
137 }
138
139 logger.warn(
140 "Unable to parse the integer system property '{}':{} - using the default value: {}",
141 key, value, def
142 );
143
144 return def;
145 }
146
147
148
149
150
151
152
153
154
155
156 public static long getLong(String key, long def) {
157 String value = get(key);
158 if (value == null) {
159 return def;
160 }
161
162 value = value.trim();
163 try {
164 return Long.parseLong(value);
165 } catch (Exception e) {
166
167 }
168
169 logger.warn(
170 "Unable to parse the long integer system property '{}':{} - using the default value: {}",
171 key, value, def
172 );
173
174 return def;
175 }
176
177 private SystemPropertyUtil() {
178
179 }
180 }