Java Code Examples for org.apache.logging.log4j.util.LoaderUtil#newInstanceOf()

The following examples show how to use org.apache.logging.log4j.util.LoaderUtil#newInstanceOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OptionConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate an object given a class name. Check that the
 * <code>className</code> is a subclass of
 * <code>superClass</code>. If that test fails or the object could
 * not be instantiated, then <code>defaultValue</code> is returned.
 *
 * @param className    The fully qualified class name of the object to instantiate.
 * @param superClass   The class to which the new object should belong.
 * @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) {
    if (className != null) {
        try {
            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 (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
                | InstantiationException | InvocationTargetException e) {
            LOGGER.error("Could not instantiate class [" + className + "].", e);
        }
    }
    return defaultValue;
}
 
Example 2
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private RewritePolicy buildRewritePolicy(String className, Element element) {
    try {
        RewritePolicy policy = LoaderUtil.newInstanceOf(className);
        PropertySetter propSetter = new PropertySetter(policy);

        forEachElement(element.getChildNodes(), (currentElement) -> {
            if (currentElement.getTagName().equalsIgnoreCase(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            }
        });
        propSetter.activate();
        return policy;
    } catch (ConsumerException ex) {
        Throwable t = ex.getCause();
        if (t instanceof InterruptedException || t instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create an RewritePolicy. Reported error follows.", t);
    } catch (Exception oops) {
        if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create an RewritePolicy. Reported error follows.", oops);
    }
    return null;
}
 
Example 3
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends AbstractBuilder> T createBuilder(PluginType<?> plugin, String prefix, Properties props) {
    try {
        Class<?> clazz = plugin.getPluginClass();
        if (AbstractBuilder.class.isAssignableFrom(clazz)) {
            @SuppressWarnings("unchecked")
            Constructor<T> constructor =
                    (Constructor<T>) clazz.getConstructor(constructorParams);
            return constructor.newInstance(prefix, props);
        } else {
            @SuppressWarnings("unchecked")
            T builder = (T) LoaderUtil.newInstanceOf(clazz);
            return builder;
        }
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
        LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        return null;
    }
}
 
Example 4
Source File: OptionConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate an object given a class name. Check that the
 * <code>className</code> is a subclass of
 * <code>superClass</code>. If that test fails or the object could
 * not be instantiated, then <code>defaultValue</code> is returned.
 *
 * @param className    The fully qualified class name of the object to instantiate.
 * @param superClass   The class to which the new object should belong.
 * @param defaultValue The object to return in case of non-fulfillment
 */
public static Object instantiateByClassName(String className, Class<?> superClass,
        Object defaultValue) {
    if (className != null) {
        try {
            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 (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
                | InstantiationException | InvocationTargetException e) {
            LOGGER.error("Could not instantiate class [" + className + "].", e);
        }
    }
    return defaultValue;
}
 
Example 5
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public static AuthorizationProvider authorizationProvider(PropertiesUtil props) {
    final String authClass = props.getStringProperty(AUTHORIZATION_PROVIDER);
    AuthorizationProvider provider = null;
    if (authClass != null) {
        try {
            Object obj = LoaderUtil.newInstanceOf(authClass);
            if (obj instanceof AuthorizationProvider) {
                provider = (AuthorizationProvider) obj;
            } else {
                LOGGER.warn("{} is not an AuthorizationProvider, using default", obj.getClass().getName());
            }
        } catch (Exception ex) {
            LOGGER.warn("Unable to create {}, using default: {}", authClass, ex.getMessage());
        }
    }
    if (provider == null) {
        provider = new BasicAuthorizationProvider(props);
    }
    return provider;
}
 
Example 6
Source File: BasicAuthorizationProvider.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public BasicAuthorizationProvider(PropertiesUtil props) {
    String userName = props.getStringProperty(PREFIXES,AUTH_USER_NAME,
            () -> props.getStringProperty(CONFIG_USER_NAME));
    String password = props.getStringProperty(PREFIXES, AUTH_PASSWORD,
            () -> props.getStringProperty(CONFIG_PASSWORD));
    String decryptor = props.getStringProperty(PREFIXES, AUTH_PASSWORD_DECRYPTOR,
            () -> props.getStringProperty(PASSWORD_DECRYPTOR));
    if (decryptor != null) {
        try {
            Object obj = LoaderUtil.newInstanceOf(decryptor);
            if (obj instanceof PasswordDecryptor) {
                password = ((PasswordDecryptor) obj).decryptPassword(password);
            }
        } catch (Exception ex) {
            LOGGER.warn("Unable to decrypt password.", ex);
        }
    }
    if (userName != null && password != null) {
        authString = "Basic " + encoder.encodeToString((userName + ":" + password).getBytes());
    }
}
 
Example 7
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout buildLayout(String className, Element layout_element) {
    try {
        Layout layout = LoaderUtil.newInstanceOf(className);
        PropertySetter propSetter = new PropertySetter(layout);
        forEachElement(layout_element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            } else {
                try {
                    parseUnrecognizedElement(layout, currentElement, props);
                } catch (Exception ex) {
                    throw new ConsumerException(ex);
                }
            }
        });

        propSetter.activate();
        return layout;
    } catch (ConsumerException ce) {
        Throwable cause = ce.getCause();
        if (cause instanceof InterruptedException || cause instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create the Layout. Reported error follows.", cause);
    } catch (Exception oops) {
        if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create the Layout. Reported error follows.", oops);
    }
    return null;
}
 
Example 8
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static <T> T newInstanceOf(String className, String type) {
    try {
        return LoaderUtil.newInstanceOf(className);
    } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException |
            InstantiationException | InvocationTargetException ex) {
        LOGGER.error("Unable to create {} {} due to {}:{}", type,  className,
                ex.getClass().getSimpleName(), ex.getMessage());
        return null;
    }
}
 
Example 9
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Appender parseAppender(String className, Element appenderElement, XmlConfiguration config) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            AppenderBuilder builder = (AppenderBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseAppender(appenderElement, config);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 10
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Filter parseFilter(String className, Element filterElement, XmlConfiguration config) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            FilterBuilder builder = (FilterBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseFilter(filterElement, config);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 11
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Layout parseLayout(String className, Element layoutElement, XmlConfiguration config) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            LayoutBuilder builder = (LayoutBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseLayout(layoutElement, config);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 12
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public RewritePolicy parseRewritePolicy(String className, Element rewriteElement, XmlConfiguration config) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            RewritePolicyBuilder builder = (RewritePolicyBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseRewritePolicy(rewriteElement, config);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 13
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout buildLayout(String className, Element layout_element) {
    try {
        Layout layout = LoaderUtil.newInstanceOf(className);
        PropertySetter propSetter = new PropertySetter(layout);
        forEachElement(layout_element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            } else {
                try {
                    parseUnrecognizedElement(layout, currentElement, props);
                } catch (Exception ex) {
                    throw new ConsumerException(ex);
                }
            }
        });

        propSetter.activate();
        return layout;
    } catch (ConsumerException ce) {
        Throwable cause = ce.getCause();
        if (cause instanceof InterruptedException || cause instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create the Layout. Reported error follows.", cause);
    } catch (Exception oops) {
        if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
            Thread.currentThread().interrupt();
        }
        LOGGER.error("Could not create the Layout. Reported error follows.", oops);
    }
    return null;
}
 
Example 14
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Appender parseAppender(String className, Element appenderElement, XmlConfigurationFactory factory) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            AppenderBuilder builder = (AppenderBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseAppender(appenderElement, factory);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 15
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Filter parseFilter(String className, Element filterElement, XmlConfigurationFactory factory) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            FilterBuilder builder = (FilterBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseFilter(filterElement, factory);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}
 
Example 16
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Layout parseLayout(String className, Element layoutElement, XmlConfigurationFactory factory) {
    PluginType<?> plugin = plugins.get(className.toLowerCase());
    if (plugin != null) {
        try {
            @SuppressWarnings("unchecked")
            LayoutBuilder builder = (LayoutBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
            return builder.parseLayout(layoutElement, factory);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
            LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
        }
    }
    return null;
}