001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import java.lang.reflect.Constructor;
017import java.lang.reflect.InvocationTargetException;
018import java.util.Objects;
019import java.util.Properties;
020
021import ch.qos.logback.core.Context;
022import ch.qos.logback.core.CoreConstants;
023import ch.qos.logback.core.spi.ContextAware;
024import ch.qos.logback.core.spi.PropertyContainer;
025import ch.qos.logback.core.spi.ScanException;
026import ch.qos.logback.core.subst.NodeToStringTransformer;
027
028import static ch.qos.logback.core.CoreConstants.FALSE_STR;
029import static ch.qos.logback.core.CoreConstants.TRUE_STR;
030
031/**
032 * @author Ceki Gulcu
033 */
034public class OptionHelper {
035
036    public static Object instantiateByClassName(String className, Class<?> superClass, Context context)
037            throws IncompatibleClassException, DynamicClassLoadingException {
038        ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
039        return instantiateByClassName(className, superClass, classLoader);
040    }
041
042    public static Object instantiateByClassNameAndParameter(String className, Class<?> superClass, Context context,
043            Class<?> type, Object param) throws IncompatibleClassException, DynamicClassLoadingException {
044        ClassLoader classLoader = Loader.getClassLoaderOfObject(context);
045        return instantiateByClassNameAndParameter(className, superClass, classLoader, type, param);
046    }
047
048    public static Object instantiateByClassName(String className, Class<?> superClass, ClassLoader classLoader)
049            throws IncompatibleClassException, DynamicClassLoadingException {
050        return instantiateByClassNameAndParameter(className, superClass, classLoader, null, null);
051    }
052
053
054    public static Object instantiateClassWithSuperclassRestriction(Class<?> classObj, Class<?> superClass)
055            throws IncompatibleClassException, DynamicClassLoadingException {
056        if (!superClass.isAssignableFrom(classObj)) {
057            throw new IncompatibleClassException(superClass, classObj);
058        }
059
060        try {
061            return classObj.getConstructor().newInstance();
062        } catch (NoSuchMethodException|InstantiationException|IllegalAccessException|InvocationTargetException e) {
063            throw new DynamicClassLoadingException("Failed to instantiate type " + classObj.getName(), e);
064        }
065    }
066
067    public static Object instantiateByClassNameAndParameter(String className, Class<?> superClass,
068            ClassLoader classLoader, Class<?> type, Object parameter)
069            throws IncompatibleClassException, DynamicClassLoadingException {
070
071        if (className == null) {
072            throw new NullPointerException();
073        }
074        try {
075            Class<?> classObj = null;
076            classObj = classLoader.loadClass(className);
077            if (!superClass.isAssignableFrom(classObj)) {
078                throw new IncompatibleClassException(superClass, classObj);
079            }
080            if (type == null) {
081                return classObj.getConstructor().newInstance();
082            } else {
083                Constructor<?> constructor = classObj.getConstructor(type);
084                return constructor.newInstance(parameter);
085            }
086        } catch (IncompatibleClassException ice) {
087            throw ice;
088        } catch (Throwable t) {
089            throw new DynamicClassLoadingException("Failed to instantiate type " + className, t);
090        }
091    }
092
093    /**
094     * Find the value corresponding to <code>key</code> in <code>props</code>. Then
095     * perform variable substitution on the found value.
096     */
097    // public static String findAndSubst(String key, Properties props) {
098    // String value = props.getProperty(key);
099    //
100    // if (value == null) {
101    // return null;
102    // }
103    //
104    // try {
105    // return substVars(value, props);
106    // } catch (IllegalArgumentException e) {
107    // return value;
108    // }
109    // }
110    final static String DELIM_START = "${";
111    final static char DELIM_STOP = '}';
112    final static String DELIM_DEFAULT = ":-";
113
114    final static int DELIM_START_LEN = 2;
115    final static int DELIM_STOP_LEN = 1;
116    final static int DELIM_DEFAULT_LEN = 2;
117
118    final static String _IS_UNDEFINED = "_IS_UNDEFINED";
119
120    /**
121     * @see #substVars(String, PropertyContainer, PropertyContainer)
122     */
123    public static String substVars(String val, PropertyContainer pc1) throws ScanException {
124        return substVars(val, pc1, null);
125    }
126
127    /**
128     * See http://logback.qos.ch/manual/configuration.html#variableSubstitution
129     */
130    public static String substVars(String input, PropertyContainer pc0, PropertyContainer pc1) throws ScanException {
131        // may throw IllegalArgumentException or ScanException
132        return NodeToStringTransformer.substituteVariable(input, pc0, pc1);
133
134    }
135
136    /**
137     * Try to lookup the property in the following order:
138     * <ol>
139     * <li>pc1 (the local property container, usually the {@link ch.qos.logback.core.model.processor.ModelInterpretationContext ModelInterpretationContext})</li>
140     * <li>pc2 (usually the {@link Context context})</li>
141     * <li>System properties</li>
142     * <li>Environment variables</li>
143     * </ol>
144     *
145     * @param key the property key
146     * @param pc1 the first property container to search
147     * @param pc2 the second property container to search
148     * @return the property value or null if not found
149     */
150    public static String propertyLookup(String key, PropertyContainer pc1, PropertyContainer pc2) {
151        String value = null;
152        // first try the props passed as parameter
153        value = pc1.getProperty(key);
154
155        // then try the pc2
156        if (value == null && pc2 != null) {
157            value = pc2.getProperty(key);
158        }
159        // then try in System properties
160        if (value == null) {
161            value = getSystemProperty(key, null);
162        }
163        if (value == null) {
164            value = getEnv(key);
165        }
166        return value;
167    }
168
169    /**
170     * Very similar to <code>System.getProperty</code> except that the
171     * {@link SecurityException} is absorbed.
172     *
173     * @param key The key to search for.
174     * @param def The default value to return.
175     * @return the string value of the system property, or the default value if
176     *         there is no property with that key.
177     */
178    public static String getSystemProperty(String key, String def) {
179        try {
180            return System.getProperty(key, def);
181        } catch (SecurityException e) {
182            return def;
183        }
184    }
185
186    /**
187     * Lookup a key from the environment.
188     *
189     * @param key
190     * @return value corresponding to key from the OS environment
191     */
192    public static String getEnv(String key) {
193        try {
194            return System.getenv(key);
195        } catch (SecurityException e) {
196            return null;
197        }
198    }
199
200    /**
201     * Very similar to <code>System.getProperty</code> except that the
202     * {@link SecurityException} is absorbed.
203     *
204     * @param key The key to search for.
205     * @return the string value of the system property.
206     */
207    public static String getSystemProperty(String key) {
208        try {
209            return System.getProperty(key);
210        } catch (SecurityException e) {
211            return null;
212        }
213    }
214
215    public static void setSystemProperties(ContextAware contextAware, Properties props) {
216        for (Object o : props.keySet()) {
217            String key = (String) o;
218            String value = props.getProperty(key);
219            setSystemProperty(contextAware, key, value);
220        }
221    }
222
223    public static void setSystemProperty(ContextAware contextAware, String key, String value) {
224        try {
225            System.setProperty(key, value);
226        } catch (SecurityException e) {
227            contextAware.addError("Failed to set system property [" + key + "]", e);
228        }
229    }
230
231    /**
232     * Very similar to {@link System#getProperties()} except that the
233     * {@link SecurityException} is absorbed.
234     *
235     * @return the system properties
236     */
237    public static Properties getSystemProperties() {
238        try {
239            return System.getProperties();
240        } catch (SecurityException e) {
241            return new Properties();
242        }
243    }
244
245    /**
246     * Return a String[] of size two. The first item containing the key part and the
247     * second item containing a default value specified by the user. The second item
248     * will be null if no default value is specified.
249     *
250     * @param key
251     * @return
252     */
253    static public String[] extractDefaultReplacement(String key) {
254        String[] result = new String[2];
255        if (key == null)
256            return result;
257
258        result[0] = key;
259        int d = key.indexOf(DELIM_DEFAULT);
260        if (d != -1) {
261            result[0] = key.substring(0, d);
262            result[1] = key.substring(d + DELIM_DEFAULT_LEN);
263        }
264        return result;
265    }
266
267
268    /**
269     * Delegates to {@link #toBooleanObject(String, Boolean)} with a default value of null.
270     */
271    public static Boolean toBooleanObject(String value) {
272        return toBooleanObject(value, null);
273    }
274
275    /**
276     * <p>If <code>value</code> is "true", then <code>true</code> is returned. If
277     * <code>value</code> is "false", then <code>false</code> is returned. Otherwise,
278     * <code>defaultVal</code> is returned.</p>
279     *
280     * <p>Comparisons are case-insensitive.</p>
281     *
282     * @param value a string representation of a boolean value
283     * @param defaultVal the default value to return if <code>value</code> is null, empty or not a valid boolean value
284     * @return a {@link Boolean} object corresponding to the input string, or {@code defaultVal} if the input is invalid
285     * @since 1.6.7
286     */
287    public static Boolean toBooleanObject(String value, Boolean defaultVal) {
288        if (OptionHelper.isNullOrEmptyOrAllSpaces(value)) {
289            return defaultVal;
290        }
291
292        String trimmedVal = value.trim();
293
294        if (TRUE_STR.equalsIgnoreCase(trimmedVal)) {
295            return Boolean.TRUE;
296        }
297
298        if (FALSE_STR.equalsIgnoreCase(trimmedVal)) {
299            return Boolean.FALSE;
300        }
301        return defaultVal;
302    }
303
304    /**
305     * <p>If <code>value</code> is "true", then <code>true</code> is returned. If
306     * <code>value</code> is "false", then <code>false</code> is returned. If <code>value</code> is null or empty,
307     * then null is returned. Otherwise, <code>defaultVal</code> is returned.</p>
308     *
309     * <p>Comparisons are case-insensitive.</p>
310     *
311     * @param value a string representation of a boolean value
312     * @param defaultVal the default value to return if <code>value</code> is not null, not empty or not "true" or "false"
313     * @return a {@link Boolean} object as described above
314     * @since 1.6.7
315     */
316    static public Boolean toLopsidedBooleanObject(String value, Boolean defaultVal) {
317        if (OptionHelper.isNullOrEmptyOrAllSpaces(value))
318            return null;
319
320        return OptionHelper.toBooleanObject(value, defaultVal);
321    }
322
323    /**
324     * <p>If <code>value</code> is "true", then <code>true</code> is returned. If
325     * <code>value</code> is "false", then <code>false</code> is returned. Otherwise,
326     * <code>defaultVal</code> is returned.
327     * </p>
328     *
329     * <p>Comparisons are case-insensitive.</p>
330     *
331     * @param value a string representation of a boolean value
332     * @param defaultVal the default value to return if <code>value</code> is null, empty or not a valid boolean value
333     */
334    public static boolean toBoolean(String value, boolean defaultVal) {
335        if (value == null) {
336            return defaultVal;
337        }
338
339        String trimmedVal = value.trim();
340
341        if (TRUE_STR.equalsIgnoreCase(trimmedVal)) {
342            return true;
343        }
344
345        if (FALSE_STR.equalsIgnoreCase(trimmedVal)) {
346            return false;
347        }
348
349        return defaultVal;
350    }
351
352    public static boolean containsUnicodeEscape(String value) {
353        return value.contains("\\u") || value.contains("\\U");
354    }
355
356    /**
357     * @deprecated
358     * @since 1.3
359     */
360    public static boolean isEmpty(String str) {
361        return isNullOrEmptyOrAllSpaces(str);
362    }
363
364    /**
365     * Returns true if input str is null or empty.
366     * 
367     * @param str
368     * @return
369     */
370    public static boolean isNullOrEmpty(String str) {
371        return ((str == null) || str.trim().length() == 0);
372    }
373
374    /**
375     * isNullOrEmpty xisNullOrEmptyOrAllSpaces
376     * @param str
377     * @return
378     * @since  1.5.0
379     */
380    public static boolean isNullOrEmptyOrAllSpaces(String str) {
381        return ((str == null) || str.trim().length() == 0);
382    }
383
384
385    final public static boolean isNullOrEmpty(Object[] array) {
386        if(array == null || array.length == 0)
387                return true;
388        else
389                return false;
390    }
391
392    final public static boolean isNotEmtpy(Object[] array) {
393        return !isNullOrEmpty(array);
394    }
395}