1 /*
2 * Copyright 2009 Red Hat, Inc.
3 *
4 * Red Hat licenses this file to you under the Apache License, version 2.0
5 * (the "License"); you may not use this file except in compliance with the
6 * License. You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package org.jboss.netty.util.internal;
17
18 import java.util.regex.Pattern;
19
20 /**
21 * Accesses the system property swallowing a {@link SecurityException}.
22 *
23 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
24 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
25 *
26 * @version $Rev: 2161 $, $Date: 2010-02-18 11:12:15 +0900 (Thu, 18 Feb 2010) $
27 *
28 */
29 public class SystemPropertyUtil {
30
31 /**
32 * Returns the value of the Java system property with the specified
33 * {@code key}.
34 *
35 * @return the property value.
36 * {@code null} if there's no such property or if an access to the
37 * specified property is not allowed.
38 */
39 public static String get(String key) {
40 try {
41 return System.getProperty(key);
42 } catch (Exception e) {
43 return null;
44 }
45 }
46
47 /**
48 * Returns the value of the Java system property with the specified
49 * {@code key}, while falling back to the specified default value if
50 * the property access fails.
51 *
52 * @return the property value.
53 * {@code def} if there's no such property or if an access to the
54 * specified property is not allowed.
55 */
56 public static String get(String key, String def) {
57 String value = get(key);
58 if (value == null) {
59 value = def;
60 }
61 return value;
62 }
63
64 /**
65 * Returns the value of the Java system property with the specified
66 * {@code key}, while falling back to the specified default value if
67 * the property access fails.
68 *
69 * @return the property value.
70 * {@code def} if there's no such property or if an access to the
71 * specified property is not allowed.
72 */
73 public static int get(String key, int def) {
74 String value = get(key);
75 if (value == null) {
76 return def;
77 }
78
79 if (Pattern.matches("-?[0-9]+", value)) {
80 return Integer.parseInt(value);
81 } else {
82 return def;
83 }
84 }
85
86 private SystemPropertyUtil() {
87 // Unused
88 }
89 }