1 /* *************************************************************************** 2 * Copyright (c) 2008 Brabenetz Harald, Austria. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 *****************************************************************************/ 17 package org.settings4j.connector; 18 19 /** 20 * The Environment variable implementation of an {@link org.settings4j.Connector}. 21 * <p> 22 * 23 * see also {@link System#getenv(String)}. 24 * 25 * @author Harald.Brabenetz 26 * 27 */ 28 public class EnvironmentConnector extends AbstractPropertyConnector { 29 30 /** General Logger for this Class. */ 31 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(EnvironmentConnector.class); 32 33 /** 34 * Very similar to <code>System.getenv</code> except that the {@link SecurityException} is hidden. 35 * 36 * @param key The key to search for. 37 * @param def The default value to return. 38 * @return the string value of the Environment variable, or the default value if there is no property with that key. 39 */ 40 @Override 41 protected String getProperty(final String key, final String def) { 42 try { 43 final String envValue = System.getenv(key); 44 if (envValue == null) { 45 return def; 46 } 47 return envValue; 48 } catch (final SecurityException e) { 49 LOG.info("Was not allowed to read environment value for key '{}'.", key); 50 return def; 51 } catch (final Throwable e) { 52 LOG.warn("Exception reading environment value for key '{}': {}", key, e.getMessage()); 53 return def; 54 } 55 } 56 }