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