You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by gg...@apache.org on 2022/01/13 23:43:12 UTC

[logging-log4j2] branch release-2.x updated: Add missing methods in OptionConverter.

This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch release-2.x
in repository https://gitbox.apache.org/repos/asf/logging-log4j2.git


The following commit(s) were added to refs/heads/release-2.x by this push:
     new d34874c  Add missing methods in OptionConverter.
d34874c is described below

commit d34874c90a2d10434b46caa26e7cd339953a7d74
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Thu Jan 13 18:43:08 2022 -0500

    Add missing methods in OptionConverter.
---
 .../org/apache/log4j/helpers/OptionConverter.java  | 161 +++++++++++++--------
 1 file changed, 101 insertions(+), 60 deletions(-)

diff --git a/log4j-1.2-api/src/main/java/org/apache/log4j/helpers/OptionConverter.java b/log4j-1.2-api/src/main/java/org/apache/log4j/helpers/OptionConverter.java
index f7ed3e6..5ebe695 100644
--- a/log4j-1.2-api/src/main/java/org/apache/log4j/helpers/OptionConverter.java
+++ b/log4j-1.2-api/src/main/java/org/apache/log4j/helpers/OptionConverter.java
@@ -17,25 +17,23 @@
 
 package org.apache.log4j.helpers;
 
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
 import org.apache.log4j.Level;
 import org.apache.log4j.PropertyConfigurator;
 import org.apache.log4j.spi.Configurator;
 import org.apache.log4j.spi.LoggerRepository;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.lookup.StrSubstitutor;
 import org.apache.logging.log4j.util.LoaderUtil;
 import org.apache.logging.log4j.util.PropertiesUtil;
 import org.apache.logging.log4j.util.Strings;
 
-import java.io.InputStream;
-import java.io.InterruptedIOException;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
 /**
  * A convenience class to convert property values to specific types.
  */
@@ -45,7 +43,7 @@ public class OptionConverter {
         final char key;
         final char replacement;
 
-        public CharMap(char key, char replacement) {
+        public CharMap(final char key, final char replacement) {
             this.key = key;
             this.replacement = replacement;
         }
@@ -67,9 +65,9 @@ public class OptionConverter {
         new CharMap('\\', '\\')
     };
 
-    public static String[] concatanateArrays(String[] l, String[] r) {
-        int len = l.length + r.length;
-        String[] a = new String[len];
+    public static String[] concatanateArrays(final String[] l, final String[] r) {
+        final int len = l.length + r.length;
+        final String[] a = new String[len];
 
         System.arraycopy(l, 0, a, 0, l.length);
         System.arraycopy(r, 0, a, l.length, r.length);
@@ -77,7 +75,7 @@ public class OptionConverter {
         return a;
     }
 
-    public static  org.apache.logging.log4j.Level convertLevel(Level level) {
+    public static  org.apache.logging.log4j.Level convertLevel(final Level level) {
         if (level == null) {
             return org.apache.logging.log4j.Level.ERROR;
         }
@@ -98,7 +96,7 @@ public class OptionConverter {
     }
 
 
-    public static Level convertLevel(org.apache.logging.log4j.Level level) {
+    public static Level convertLevel(final org.apache.logging.log4j.Level level) {
         if (level == null) {
             return Level.ERROR;
         }
@@ -122,23 +120,23 @@ public class OptionConverter {
         }
     }
 
-    public static org.apache.logging.log4j.Level convertLevel(String level,
-            org.apache.logging.log4j.Level defaultLevel) {
-        Level l = toLevel(level, null);
+    public static org.apache.logging.log4j.Level convertLevel(final String level,
+            final org.apache.logging.log4j.Level defaultLevel) {
+        final Level l = toLevel(level, null);
         return l != null ? convertLevel(l) : defaultLevel;
     }
 
-    public static String convertSpecialChars(String s) {
+    public static String convertSpecialChars(final String s) {
         char c;
-        int len = s.length();
-        StringBuilder sbuf = new StringBuilder(len);
+        final int len = s.length();
+        final StringBuilder sbuf = new StringBuilder(len);
 
         int i = 0;
         while (i < len) {
             c = s.charAt(i++);
             if (c == '\\') {
                 c = s.charAt(i++);
-                for (CharMap entry : charMap) {
+                for (final CharMap entry : charMap) {
                     if (entry.key == c) {
                         c = entry.replacement;
                     }
@@ -157,15 +155,15 @@ public class OptionConverter {
      * @param props The properties to use in the substitution.
      * @return The substituted string.
      */
-    public static String findAndSubst(String key, Properties props) {
-        String value = props.getProperty(key);
+    public static String findAndSubst(final String key, final Properties props) {
+        final String value = props.getProperty(key);
         if (value == null) {
             return null;
         }
 
         try {
             return substVars(value, props);
-        } catch (IllegalArgumentException e) {
+        } catch (final IllegalArgumentException e) {
             LOGGER.error("Bad option value [{}].", value, e);
             return value;
         }
@@ -182,10 +180,10 @@ public class OptionConverter {
      * value if there is no property with that key.
      * @since 1.1
      */
-    public static String getSystemProperty(String key, String def) {
+    public static String getSystemProperty(final String key, final String def) {
         try {
             return System.getProperty(key, def);
-        } catch (Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
+        } catch (final Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx
             LOGGER.debug("Was not allowed to read system property \"{}\".", key);
             return def;
         }
@@ -202,28 +200,28 @@ public class OptionConverter {
      * @param defaultValue The object to return in case of non-fulfillment
      * @return The created object.
      */
-    public static Object instantiateByClassName(String className, Class<?> superClass,
-            Object defaultValue) {
+    public static Object instantiateByClassName(final String className, final Class<?> superClass,
+            final Object defaultValue) {
         if (className != null) {
             try {
-                Object obj = LoaderUtil.newInstanceOf(className);
+                final Object obj = LoaderUtil.newInstanceOf(className);
                 if (!superClass.isAssignableFrom(obj.getClass())) {
                     LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable", className,
                             superClass.getName());
                     return defaultValue;
                 }
                 return obj;
-            } catch (ReflectiveOperationException e) {
+            } catch (final ReflectiveOperationException e) {
                 LOGGER.error("Could not instantiate class [" + className + "].", e);
             }
         }
         return defaultValue;
     }
 
-    public static Object instantiateByKey(Properties props, String key, Class superClass, Object defaultValue) {
+    public static Object instantiateByKey(final Properties props, final String key, final Class superClass, final Object defaultValue) {
 
         // Get the value of the property in string form
-        String className = findAndSubst(key, props);
+        final String className = findAndSubst(key, props);
         if (className == null) {
             LogLog.error("Could not find value for key " + key);
             return defaultValue;
@@ -240,7 +238,7 @@ public class OptionConverter {
      * <p>
      * All configurations steps are taken on the <code>hierarchy</code> passed as a parameter.
      * </p>
-     * 
+     *
      * @param inputStream The configuration input stream.
      * @param clazz The class name, of the log4j configurator which will parse the <code>inputStream</code>. This must be a
      *        subclass of {@link Configurator}, or null. If this value is null then a default configurator of
@@ -248,7 +246,7 @@ public class OptionConverter {
      * @param hierarchy The {@link LoggerRepository} to act on.
      * @since 1.2.17
      */
-    static public void selectAndConfigure(InputStream inputStream, String clazz, LoggerRepository hierarchy) {
+    static public void selectAndConfigure(final InputStream inputStream, final String clazz, final LoggerRepository hierarchy) {
         Configurator configurator = null;
 
         if (clazz != null) {
@@ -273,19 +271,19 @@ public class OptionConverter {
      * <p>
      * All configurations steps are taken on the <code>hierarchy</code> passed as a parameter.
      * </p>
-     * 
+     *
      * @param url The location of the configuration file or resource.
      * @param clazz The classname, of the log4j configurator which will parse the file or resource at <code>url</code>. This
      *        must be a subclass of {@link Configurator}, or null. If this value is null then a default configurator of
      *        {@link PropertyConfigurator} is used, unless the filename pointed to by <code>url</code> ends in '.xml', in
      *        which case {@link org.apache.log4j.xml.DOMConfigurator} is used.
      * @param hierarchy The {@link LoggerRepository} to act on.
-     * 
+     *
      * @since 1.1.4
      */
-    static public void selectAndConfigure(URL url, String clazz, LoggerRepository hierarchy) {
+    static public void selectAndConfigure(final URL url, String clazz, final LoggerRepository hierarchy) {
         Configurator configurator = null;
-        String filename = url.getFile();
+        final String filename = url.getFile();
 
         if (clazz == null && filename != null && filename.endsWith(".xml")) {
             clazz = "org.apache.log4j.xml.DOMConfigurator";
@@ -342,11 +340,11 @@ public class OptionConverter {
      * @return The substituted string.
      * @throws IllegalArgumentException if <code>val</code> is malformed.
      */
-    public static String substVars(String val, Properties props) throws IllegalArgumentException {
+    public static String substVars(final String val, final Properties props) throws IllegalArgumentException {
         return substVars(val, props, new ArrayList<>());
     }
 
-    private static String substVars(final String val, final Properties props, List<String> keys)
+    private static String substVars(final String val, final Properties props, final List<String> keys)
             throws IllegalArgumentException {
 
         final StringBuilder sbuf = new StringBuilder();
@@ -363,7 +361,7 @@ public class OptionConverter {
                     return val;
                 }
                 // add the tail string which contails no variables and return the result.
-                sbuf.append(val.substring(i, val.length()));
+                sbuf.append(val.substring(i));
                 return sbuf.toString();
             }
             sbuf.append(val.substring(i, j));
@@ -390,7 +388,7 @@ public class OptionConverter {
                 // x1=p1
                 // x2=${x1}
                 if (!keys.contains(key)) {
-                    List<String> usedKeys = new ArrayList<>(keys);
+                    final List<String> usedKeys = new ArrayList<>(keys);
                     usedKeys.add(key);
                     final String recursiveReplacement = substVars(replacement, props, usedKeys);
                     sbuf.append(recursiveReplacement);
@@ -414,11 +412,11 @@ public class OptionConverter {
      * @param dEfault The default value.
      * @return the value of the result.
      */
-    public static boolean toBoolean(String value, boolean dEfault) {
+    public static boolean toBoolean(final String value, final boolean dEfault) {
         if (value == null) {
             return dEfault;
         }
-        String trimmedVal = value.trim();
+        final String trimmedVal = value.trim();
         if ("true".equalsIgnoreCase(trimmedVal)) {
             return true;
         }
@@ -428,6 +426,49 @@ public class OptionConverter {
         return dEfault;
     }
 
+    public static long toFileSize(final String value, final long defaultValue) {
+        if (value == null) {
+            return defaultValue;
+        }
+
+        String s = value.trim().toUpperCase();
+        long multiplier = 1;
+        int index;
+
+        if ((index = s.indexOf("KB")) != -1) {
+            multiplier = 1024;
+            s = s.substring(0, index);
+        } else if ((index = s.indexOf("MB")) != -1) {
+            multiplier = 1024 * 1024;
+            s = s.substring(0, index);
+        } else if ((index = s.indexOf("GB")) != -1) {
+            multiplier = 1024 * 1024 * 1024;
+            s = s.substring(0, index);
+        }
+        if (s != null) {
+            try {
+                return Long.valueOf(s).longValue() * multiplier;
+            } catch (final NumberFormatException e) {
+                LogLog.error("[" + s + "] is not in proper int form.");
+                LogLog.error("[" + value + "] not in expected format.", e);
+            }
+        }
+        return defaultValue;
+    }
+
+    public static int toInt(final String value, final int dEfault) {
+        if (value != null) {
+            final String s = value.trim();
+            try {
+                return Integer.valueOf(s).intValue();
+            } catch (final NumberFormatException e) {
+                LogLog.error("[" + s + "] is not in proper int form.");
+                e.printStackTrace();
+            }
+        }
+        return dEfault;
+    }
+
     /**
      * Converts a standard or custom priority level to a Level
      * object.  <p> If <code>value</code> is of form
@@ -452,14 +493,14 @@ public class OptionConverter {
      *
      * @since 1.1
      */
-    public static Level toLevel(String value, Level defaultValue) {
+    public static Level toLevel(String value, final Level defaultValue) {
         if (value == null) {
             return defaultValue;
         }
 
         value = value.trim();
 
-        int hashIndex = value.indexOf('#');
+        final int hashIndex = value.indexOf('#');
         if (hashIndex == -1) {
             if ("NULL".equalsIgnoreCase(value)) {
                 return null;
@@ -470,8 +511,8 @@ public class OptionConverter {
 
         Level result = defaultValue;
 
-        String clazz = value.substring(hashIndex + 1);
-        String levelName = value.substring(0, hashIndex);
+        final String clazz = value.substring(hashIndex + 1);
+        final String levelName = value.substring(0, hashIndex);
 
         // This is degenerate case but you never know.
         if ("NULL".equalsIgnoreCase(levelName)) {
@@ -482,38 +523,38 @@ public class OptionConverter {
                 + ":pri=[" + levelName + "]");
 
         try {
-            Class<?> customLevel = LoaderUtil.loadClass(clazz);
+            final Class<?> customLevel = LoaderUtil.loadClass(clazz);
 
             // get a ref to the specified class' static method
             // toLevel(String, org.apache.log4j.Level)
-            Class<?>[] paramTypes = new Class[] { String.class, org.apache.log4j.Level.class };
-            java.lang.reflect.Method toLevelMethod =
+            final Class<?>[] paramTypes = new Class[] { String.class, org.apache.log4j.Level.class };
+            final java.lang.reflect.Method toLevelMethod =
                     customLevel.getMethod("toLevel", paramTypes);
 
             // now call the toLevel method, passing level string + default
-            Object[] params = new Object[]{levelName, defaultValue};
-            Object o = toLevelMethod.invoke(null, params);
+            final Object[] params = new Object[]{levelName, defaultValue};
+            final Object o = toLevelMethod.invoke(null, params);
 
             result = (Level) o;
-        } catch (ClassNotFoundException e) {
+        } catch (final ClassNotFoundException e) {
             LOGGER.warn("custom level class [" + clazz + "] not found.");
-        } catch (NoSuchMethodException e) {
+        } catch (final NoSuchMethodException e) {
             LOGGER.warn("custom level class [" + clazz + "]"
                     + " does not have a class function toLevel(String, Level)", e);
-        } catch (java.lang.reflect.InvocationTargetException e) {
+        } catch (final java.lang.reflect.InvocationTargetException e) {
             if (e.getTargetException() instanceof InterruptedException
                     || e.getTargetException() instanceof InterruptedIOException) {
                 Thread.currentThread().interrupt();
             }
             LOGGER.warn("custom level class [" + clazz + "]"
                     + " could not be instantiated", e);
-        } catch (ClassCastException e) {
+        } catch (final ClassCastException e) {
             LOGGER.warn("class [" + clazz
                     + "] is not a subclass of org.apache.log4j.Level", e);
-        } catch (IllegalAccessException e) {
+        } catch (final IllegalAccessException e) {
             LOGGER.warn("class [" + clazz +
                     "] cannot be instantiated due to access restrictions", e);
-        } catch (RuntimeException e) {
+        } catch (final RuntimeException e) {
             LOGGER.warn("class [" + clazz + "], level [" + levelName +
                     "] conversion failed.", e);
         }