View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the 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  public final class SystemPropertyUtil {
24  
25      /**
26       * Returns the value of the Java system property with the specified
27       * {@code key}.
28       *
29       * @return the property value.
30       *         {@code null} if there's no such property or if an access to the
31       *         specified property is not allowed.
32       */
33      public static String get(String key) {
34          try {
35              return System.getProperty(key);
36          } catch (Exception e) {
37              return null;
38          }
39      }
40  
41      /**
42       * Returns the value of the Java system property with the specified
43       * {@code key}, while falling back to the specified default value if
44       * the property access fails.
45       *
46       * @return the property value.
47       *         {@code def} if there's no such property or if an access to the
48       *         specified property is not allowed.
49       */
50      public static String get(String key, String def) {
51          String value = get(key);
52          if (value == null) {
53              value = def;
54          }
55          return value;
56      }
57  
58      /**
59       * Returns the value of the Java system property with the specified
60       * {@code key}, while falling back to the specified default value if
61       * the property access fails.
62       *
63       * @return the property value.
64       *         {@code def} if there's no such property or if an access to the
65       *         specified property is not allowed.
66       */
67      public static int get(String key, int def) {
68          String value = get(key);
69          if (value == null) {
70              return def;
71          }
72  
73          if (Pattern.matches("-?[0-9]+", value)) {
74              return Integer.parseInt(value);
75          } else {
76              return def;
77          }
78      }
79  
80      private SystemPropertyUtil() {
81          // Unused
82      }
83  }