View Javadoc
1   /*
2    * #%L
3    * settings4j
4    * ===============================================================
5    * Copyright (C) 2008 - 2015 Brabenetz Harald, Austria
6    * ===============================================================
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * 
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   * 
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package org.settings4j.connector;
21  
22  import java.util.Locale;
23  
24  /**
25   * The Environment variable implementation of an {@link org.settings4j.Connector}.
26   * <p>
27   * see also {@link System#getenv(String)}.
28   * </p>
29   *
30   * @author Harald.Brabenetz
31   */
32  public class EnvironmentConnector extends AbstractPropertyConnector {
33  
34      /** General Logger for this Class. */
35      private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(EnvironmentConnector.class);
36  
37      /**
38       * Very similar to <code>System.getenv</code> except that the {@link SecurityException} is hidden.
39       *
40       * @param key The key to search for.
41       * @return the string value of the Environment variable, or the default value if there is no property with that key.
42       */
43      @Override
44      public String getString(final String key) {
45          final String value = getEnv(key);
46          if (value == null) {
47              final String uppercaseKey = key.toUpperCase(Locale.ENGLISH).replaceAll("\\W", "_");
48              LOG.debug("Try to find value for KEY: {}", uppercaseKey);
49              return getEnv(uppercaseKey);
50          }
51          return value;
52      }
53  
54      private String getEnv(final String key) {
55          try {
56              return System.getenv(key);
57          } catch (final SecurityException e) {
58              LOG.info("Was not allowed to read environment value for key '{}'.", key, e);
59              return null;
60          } catch (final Throwable e) {
61              LOG.warn("Exception reading environment value for key '{}': {}", key, e.getMessage());
62              return null;
63          }
64      }
65  }