View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.lang.reflect.Constructor;
17  import java.util.Properties;
18  
19  import ch.qos.logback.core.Context;
20  import ch.qos.logback.core.CoreConstants;
21  import ch.qos.logback.core.spi.ContextAware;
22  import ch.qos.logback.core.spi.PropertyContainer;
23  import ch.qos.logback.core.spi.ScanException;
24  import ch.qos.logback.core.subst.NodeToStringTransformer;
25  
26  /**
27   * @author Ceki Gulcu
28   */
29  public class OptionHelper {
30  
31      public static Object instantiateByClassName(String className, Class<?> superClass, Context context) throws IncompatibleClassException,
32                      DynamicClassLoadingException {
33          ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
34          return instantiateByClassName(className, superClass, classLoader);
35      }
36  
37      public static Object instantiateByClassNameAndParameter(String className, Class<?> superClass, Context context, Class<?> type, Object param)
38                      throws IncompatibleClassException, DynamicClassLoadingException {
39          ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
40          return instantiateByClassNameAndParameter(className, superClass, classLoader, type, param);
41      }
42  
43      public static Object instantiateByClassName(String className, Class<?> superClass, ClassLoader classLoader) throws IncompatibleClassException,
44                      DynamicClassLoadingException {
45          return instantiateByClassNameAndParameter(className, superClass, classLoader, null, null);
46      }
47  
48      public static Object instantiateByClassNameAndParameter(String className, Class<?> superClass, ClassLoader classLoader, Class<?> type, Object parameter)
49                      throws IncompatibleClassException, DynamicClassLoadingException {
50  
51          if (className == null) {
52              throw new NullPointerException();
53          }
54          try {
55              Class<?> classObj = null;
56              classObj = classLoader.loadClass(className);
57              if (!superClass.isAssignableFrom(classObj)) {
58                  throw new IncompatibleClassException(superClass, classObj);
59              }
60              if (type == null) {
61                  return classObj.getConstructor().newInstance();
62              } else {
63                  Constructor<?> constructor = classObj.getConstructor(type);
64                  return constructor.newInstance(parameter);
65              }
66          } catch (IncompatibleClassException ice) {
67              throw ice;
68          } catch (Throwable t) {
69              throw new DynamicClassLoadingException("Failed to instantiate type " + className, t);
70          }
71      }
72  
73      /**
74       * Find the value corresponding to <code>key</code> in <code>props</code>.
75       * Then perform variable substitution on the found value.
76       */
77      // public static String findAndSubst(String key, Properties props) {
78      // String value = props.getProperty(key);
79      //
80      // if (value == null) {
81      // return null;
82      // }
83      //
84      // try {
85      // return substVars(value, props);
86      // } catch (IllegalArgumentException e) {
87      // return value;
88      // }
89      // }
90      final static String DELIM_START = "${";
91      final static char DELIM_STOP = '}';
92      final static String DELIM_DEFAULT = ":-";
93  
94      final static int DELIM_START_LEN = 2;
95      final static int DELIM_STOP_LEN = 1;
96      final static int DELIM_DEFAULT_LEN = 2;
97  
98      final static String _IS_UNDEFINED = "_IS_UNDEFINED";
99  
100     /**
101      * @see #substVars(String, PropertyContainer, PropertyContainer)
102      */
103     public static String substVars(String val, PropertyContainer pc1) {
104         return substVars(val, pc1, null);
105     }
106 
107     /**
108      * See  http://logback.qos.ch/manual/configuration.html#variableSubstitution
109      */
110     public static String substVars(String input, PropertyContainer pc0, PropertyContainer pc1) {
111         try {
112             return NodeToStringTransformer.substituteVariable(input, pc0, pc1);
113         } catch (ScanException e) {
114             throw new IllegalArgumentException("Failed to parse input [" + input + "]", e);
115         }
116     }
117 
118     public static String propertyLookup(String key, PropertyContainer pc1, PropertyContainer pc2) {
119         String value = null;
120         // first try the props passed as parameter
121         value = pc1.getProperty(key);
122 
123         // then try the pc2
124         if (value == null && pc2 != null) {
125             value = pc2.getProperty(key);
126         }
127         // then try in System properties
128         if (value == null) {
129             value = getSystemProperty(key, null);
130         }
131         if (value == null) {
132             value = getEnv(key);
133         }
134         return value;
135     }
136 
137     /**
138      * Very similar to <code>System.getProperty</code> except that the
139      * {@link SecurityException} is absorbed.
140      *
141      * @param key The key to search for.
142      * @param def The default value to return.
143      * @return the string value of the system property, or the default value if
144      *         there is no property with that key.
145      */
146     public static String getSystemProperty(String key, String def) {
147         try {
148             return System.getProperty(key, def);
149         } catch (SecurityException e) {
150             return def;
151         }
152     }
153 
154     /**
155      * Lookup a key from the environment.
156      *
157      * @param key
158      * @return value corresponding to key from the OS environment
159      */
160     public static String getEnv(String key) {
161         try {
162             return System.getenv(key);
163         } catch (SecurityException e) {
164             return null;
165         }
166     }
167 
168     /**
169      * Very similar to <code>System.getProperty</code> except that the
170      * {@link SecurityException} is absorbed.
171      *
172      * @param key The key to search for.
173      * @return the string value of the system property.
174      */
175     public static String getSystemProperty(String key) {
176         try {
177             return System.getProperty(key);
178         } catch (SecurityException e) {
179             return null;
180         }
181     }
182 
183     public static void setSystemProperties(ContextAware contextAware, Properties props) {
184         for (Object o : props.keySet()) {
185             String key = (String) o;
186             String value = props.getProperty(key);
187             setSystemProperty(contextAware, key, value);
188         }
189     }
190 
191     public static void setSystemProperty(ContextAware contextAware, String key, String value) {
192         try {
193             System.setProperty(key, value);
194         } catch (SecurityException e) {
195             contextAware.addError("Failed to set system property [" + key + "]", e);
196         }
197     }
198 
199     /**
200      * Very similar to {@link System#getProperties()} except that the
201      * {@link SecurityException} is absorbed.
202      *
203      * @return the system properties
204      */
205     public static Properties getSystemProperties() {
206         try {
207             return System.getProperties();
208         } catch (SecurityException e) {
209             return new Properties();
210         }
211     }
212 
213     /**
214      * Return a String[] of size two. The first item containing the key part and the second item
215      * containing a default value specified by the user. The second item will be null if no default value
216      * is specified.
217      *
218      * @param key
219      * @return
220      */
221     static public String[] extractDefaultReplacement(String key) {
222         String[] result = new String[2];
223         if (key == null)
224             return result;
225 
226         result[0] = key;
227         int d = key.indexOf(DELIM_DEFAULT);
228         if (d != -1) {
229             result[0] = key.substring(0, d);
230             result[1] = key.substring(d + DELIM_DEFAULT_LEN);
231         }
232         return result;
233     }
234 
235     /**
236      * If <code>value</code> is "true", then <code>true</code> is returned. If
237      * <code>value</code> is "false", then <code>true</code> is returned.
238      * Otherwise, <code>default</code> is returned.
239      * <p> 
240      * Case of value is unimportant.
241      */
242     public static boolean toBoolean(String value, boolean dEfault) {
243         if (value == null) {
244             return dEfault;
245         }
246 
247         String trimmedVal = value.trim();
248 
249         if ("true".equalsIgnoreCase(trimmedVal)) {
250             return true;
251         }
252 
253         if ("false".equalsIgnoreCase(trimmedVal)) {
254             return false;
255         }
256 
257         return dEfault;
258     }
259 
260     public static boolean isEmpty(String str) {
261         return ((str == null) || CoreConstants.EMPTY_STRING.equals(str));
262     }
263 
264 }