001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.util; 018 019 import java.io.InputStream; 020 import java.util.Properties; 021 022 /** 023 * Utility class to help with accessing System Properties. 024 */ 025 public class PropsUtil { 026 027 private Properties props; 028 029 public PropsUtil(Properties props) { 030 this.props = props; 031 } 032 033 public PropsUtil(String propsLocn) { 034 this.props = new Properties(); 035 ClassLoader loader = findClassLoader(); 036 InputStream in = loader.getResourceAsStream(propsLocn); 037 if (null != in) { 038 try { 039 this.props.load(in); 040 in.close(); 041 } catch(java.io.IOException e) { 042 // ignored 043 } 044 } 045 } 046 047 public String getStringProperty(String name) { 048 String prop = null; 049 try { 050 prop = System.getProperty(name); 051 } catch (SecurityException e) { 052 // Ignore 053 } 054 return (prop == null) ? props.getProperty(name) : prop; 055 } 056 057 public String getStringProperty(String name, String defaultValue) { 058 String prop = getStringProperty(name); 059 return (prop == null) ? defaultValue : prop; 060 } 061 062 public boolean getBooleanProperty(String name, boolean defaultValue) { 063 String prop = getStringProperty(name); 064 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop); 065 } 066 067 private static ClassLoader findClassLoader() { 068 ClassLoader cl; 069 if (System.getSecurityManager() == null) { 070 cl = Thread.currentThread().getContextClassLoader(); 071 } else { 072 cl = java.security.AccessController.doPrivileged( 073 new java.security.PrivilegedAction<ClassLoader>() { 074 public ClassLoader run() { 075 return Thread.currentThread().getContextClassLoader(); 076 } 077 } 078 ); 079 } 080 if (cl == null) { 081 cl = PropsUtil.class.getClassLoader(); 082 } 083 084 return cl; 085 } 086 }