1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.util.internal;
17
18 import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
19
20 import io.netty.util.internal.logging.InternalLogger;
21 import io.netty.util.internal.logging.InternalLoggerFactory;
22
23 import java.security.AccessController;
24 import java.security.PrivilegedAction;
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(new PrivilegedAction<String>() {
69 @Override
70 public String run() {
71 return System.getProperty(key);
72 }
73 });
74 }
75 } catch (SecurityException e) {
76 logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e);
77 }
78
79 if (value == null) {
80 return def;
81 }
82
83 return value;
84 }
85
86
87
88
89
90
91
92
93
94
95 public static boolean getBoolean(String key, boolean def) {
96 String value = get(key);
97 if (value == null) {
98 return def;
99 }
100
101 value = value.trim().toLowerCase();
102 if (value.isEmpty()) {
103 return def;
104 }
105
106 if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
107 return true;
108 }
109
110 if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
111 return false;
112 }
113
114 logger.warn(
115 "Unable to parse the boolean system property '{}':{} - using the default value: {}",
116 key, value, def
117 );
118
119 return def;
120 }
121
122
123
124
125
126
127
128
129
130
131 public static int getInt(String key, int def) {
132 String value = get(key);
133 if (value == null) {
134 return def;
135 }
136
137 value = value.trim();
138 try {
139 return Integer.parseInt(value);
140 } catch (Exception e) {
141
142 }
143
144 logger.warn(
145 "Unable to parse the integer system property '{}':{} - using the default value: {}",
146 key, value, def
147 );
148
149 return def;
150 }
151
152
153
154
155
156
157
158
159
160
161 public static long getLong(String key, long def) {
162 String value = get(key);
163 if (value == null) {
164 return def;
165 }
166
167 value = value.trim();
168 try {
169 return Long.parseLong(value);
170 } catch (Exception e) {
171
172 }
173
174 logger.warn(
175 "Unable to parse the long integer system property '{}':{} - using the default value: {}",
176 key, value, def
177 );
178
179 return def;
180 }
181
182 private SystemPropertyUtil() {
183
184 }
185 }