Search in sources :

Example 1 with PluginFactory

use of org.apache.logging.log4j.plugins.PluginFactory in project logging-log4j2 by apache.

the class IdlePurgePolicy method createPurgePolicy.

/**
 * Create the PurgePolicy
 *
 * @param timeToLive    the number of increments of timeUnit before the Appender should be purged.
 * @param checkInterval when all appenders purged, the number of increments of timeUnit to check if any appenders appeared
 * @param timeUnit      the unit of time the timeToLive and the checkInterval is expressed in.
 * @return The Routes container.
 */
@PluginFactory
public static PurgePolicy createPurgePolicy(@PluginAttribute final String timeToLive, @PluginAttribute final String checkInterval, @PluginAttribute final String timeUnit, @PluginConfiguration final Configuration configuration) {
    if (timeToLive == null) {
        LOGGER.error("A timeToLive value is required");
        return null;
    }
    TimeUnit units;
    if (timeUnit == null) {
        units = TimeUnit.MINUTES;
    } else {
        try {
            units = TimeUnit.valueOf(timeUnit.toUpperCase());
        } catch (final Exception ex) {
            LOGGER.error("Invalid timeUnit value {}. timeUnit set to MINUTES", timeUnit, ex);
            units = TimeUnit.MINUTES;
        }
    }
    long ttl = units.toMillis(Long.parseLong(timeToLive));
    if (ttl < 0) {
        LOGGER.error("timeToLive must be positive. timeToLive set to 0");
        ttl = 0;
    }
    long ci;
    if (checkInterval == null) {
        ci = ttl;
    } else {
        ci = units.toMillis(Long.parseLong(checkInterval));
        if (ci < 0) {
            LOGGER.error("checkInterval must be positive. checkInterval set equal to timeToLive = {}", ttl);
            ci = ttl;
        }
    }
    return new IdlePurgePolicy(ttl, ci, configuration.getScheduler());
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory)

Example 2 with PluginFactory

use of org.apache.logging.log4j.plugins.PluginFactory in project logging-log4j2 by apache.

the class DynamicThresholdFilter method createFilter.

/**
 * Creates a DynamicThresholdFilter.
 * @param key The name of the key to compare.
 * @param pairs An array of value and Level pairs.
 * @param defaultThreshold The default Level.
 * @param onMatch The action to perform if a match occurs.
 * @param onMismatch The action to perform if no match occurs.
 * @return The DynamicThresholdFilter.
 */
// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static DynamicThresholdFilter createFilter(@PluginAttribute final String key, @PluginElement final KeyValuePair[] pairs, @PluginAttribute final Level defaultThreshold, @PluginAttribute final Result onMatch, @PluginAttribute final Result onMismatch) {
    final Map<String, Level> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        map.put(pair.getKey(), Level.toLevel(pair.getValue()));
    }
    final Level level = defaultThreshold == null ? Level.ERROR : defaultThreshold;
    return new DynamicThresholdFilter(key, map, level, onMatch, onMismatch);
}
Also used : KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) HashMap(java.util.HashMap) Level(org.apache.logging.log4j.Level) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory)

Example 3 with PluginFactory

use of org.apache.logging.log4j.plugins.PluginFactory in project logging-log4j2 by apache.

the class MapFilter method createFilter.

// TODO Consider refactoring to use AbstractFilter.AbstractFilterBuilder
@PluginFactory
public static MapFilter createFilter(@PluginElement final KeyValuePair[] pairs, @PluginAttribute final String operator, @PluginAttribute final Result onMatch, @PluginAttribute final Result onMismatch) {
    if (pairs == null || pairs.length == 0) {
        LOGGER.error("keys and values must be specified for the MapFilter");
        return null;
    }
    final Map<String, List<String>> map = new HashMap<>();
    for (final KeyValuePair pair : pairs) {
        final String key = pair.getKey();
        if (key == null) {
            LOGGER.error("A null key is not valid in MapFilter");
            continue;
        }
        final String value = pair.getValue();
        if (value == null) {
            LOGGER.error("A null value for key " + key + " is not allowed in MapFilter");
            continue;
        }
        List<String> list = map.get(pair.getKey());
        if (list != null) {
            list.add(value);
        } else {
            list = new ArrayList<>();
            list.add(value);
            map.put(pair.getKey(), list);
        }
    }
    if (map.isEmpty()) {
        LOGGER.error("MapFilter is not configured with any valid key value pairs");
        return null;
    }
    final boolean isAnd = operator == null || !operator.equalsIgnoreCase("or");
    return new MapFilter(map, isAnd, onMatch, onMismatch);
}
Also used : KeyValuePair(org.apache.logging.log4j.core.util.KeyValuePair) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory)

Example 4 with PluginFactory

use of org.apache.logging.log4j.plugins.PluginFactory in project logging-log4j2 by apache.

the class ScriptFile method createScript.

@PluginFactory
public static ScriptFile createScript(// @formatter:off
@PluginAttribute String name, @PluginAttribute String language, @PluginAttribute("path") final String filePathOrUri, @PluginAttribute final Boolean isWatched, @PluginAttribute final Charset charset) {
    // @formatter:on
    if (filePathOrUri == null) {
        LOGGER.error("No script path provided for ScriptFile");
        return null;
    }
    if (name == null) {
        name = filePathOrUri;
    }
    final URI uri = NetUtils.toURI(filePathOrUri);
    final File file = FileUtils.fileFromUri(uri);
    if (language == null && file != null) {
        final String fileExtension = FileUtils.getFileExtension(file);
        if (fileExtension != null) {
            final ExtensionLanguageMapping mapping = ExtensionLanguageMapping.getByExtension(fileExtension);
            if (mapping != null) {
                language = mapping.getLanguage();
            }
        }
    }
    if (language == null) {
        LOGGER.info("No script language supplied, defaulting to {}", DEFAULT_LANGUAGE);
        language = DEFAULT_LANGUAGE;
    }
    final Charset actualCharset = charset == null ? Charset.defaultCharset() : charset;
    final String scriptText;
    try (final Reader reader = new InputStreamReader(file != null ? new FileInputStream(file) : uri.toURL().openStream(), actualCharset)) {
        scriptText = IOUtils.toString(reader);
    } catch (final IOException e) {
        LOGGER.error("{}: language={}, path={}, actualCharset={}", e.getClass().getSimpleName(), language, filePathOrUri, actualCharset);
        return null;
    }
    final Path path = file != null ? Paths.get(file.toURI()) : Paths.get(uri);
    if (path == null) {
        LOGGER.error("Unable to convert {} to a Path", uri.toString());
        return null;
    }
    return new ScriptFile(name, path, language, isWatched == null ? Boolean.FALSE : isWatched, scriptText);
}
Also used : Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ExtensionLanguageMapping(org.apache.logging.log4j.core.util.ExtensionLanguageMapping) IOException(java.io.IOException) URI(java.net.URI) File(java.io.File) FileInputStream(java.io.FileInputStream) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory)

Example 5 with PluginFactory

use of org.apache.logging.log4j.plugins.PluginFactory in project logging-log4j2 by apache.

the class CouchDbProvider method createNoSqlProvider.

/**
 * Factory method for creating an Apache CouchDB provider within the plugin manager.
 *
 * @param databaseName The name of the database to which log event documents will be written.
 * @param protocol Either "http" or "https," defaults to "http" and mutually exclusive with
 *                 {@code factoryClassName&factoryMethodName!=null}.
 * @param server The host name of the CouchDB server, defaults to localhost and mutually exclusive with
 *               {@code factoryClassName&factoryMethodName!=null}.
 * @param port The port that CouchDB is listening on, defaults to 80 if {@code protocol} is "http" and 443 if
 *             {@code protocol} is "https," and mutually exclusive with
 *             {@code factoryClassName&factoryMethodName!=null}.
 * @param username The username to authenticate against the MongoDB server with, mutually exclusive with
 *                 {@code factoryClassName&factoryMethodName!=null}.
 * @param password The password to authenticate against the MongoDB server with, mutually exclusive with
 *                 {@code factoryClassName&factoryMethodName!=null}.
 * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
 *                         {@link CouchDbClient} or {@link CouchDbProperties}.
 * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
 *                          class.
 * @return a new Apache CouchDB provider.
 */
@PluginFactory
public static CouchDbProvider createNoSqlProvider(@PluginAttribute final String databaseName, @PluginAttribute String protocol, @PluginAttribute(defaultString = "localhost") @ValidHost final String server, @PluginAttribute(defaultString = "0") @ValidPort final String port, @PluginAttribute final String username, @PluginAttribute(sensitive = true) final String password, @PluginAttribute final String factoryClassName, @PluginAttribute final String factoryMethodName) {
    CouchDbClient client;
    String description;
    if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
        try {
            final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName);
            final Method method = factoryClass.getMethod(factoryMethodName);
            final Object object = method.invoke(null);
            if (object instanceof CouchDbClient) {
                client = (CouchDbClient) object;
                description = "uri=" + client.getDBUri();
            } else if (object instanceof CouchDbProperties) {
                final CouchDbProperties properties = (CouchDbProperties) object;
                client = new CouchDbClient(properties);
                description = "uri=" + client.getDBUri() + ", username=" + properties.getUsername() + ", maxConnections=" + properties.getMaxConnections() + ", connectionTimeout=" + properties.getConnectionTimeout() + ", socketTimeout=" + properties.getSocketTimeout();
            } else if (object == null) {
                LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName);
                return null;
            } else {
                LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName, factoryMethodName, object.getClass().getName());
                return null;
            }
        } catch (final ClassNotFoundException e) {
            LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
            return null;
        } catch (final NoSuchMethodException e) {
            LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName, factoryMethodName, e);
            return null;
        } catch (final Exception e) {
            LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName, e);
            return null;
        }
    } else if (Strings.isNotEmpty(databaseName)) {
        if (protocol != null && protocol.length() > 0) {
            protocol = protocol.toLowerCase();
            if (!protocol.equals("http") && !protocol.equals("https")) {
                LOGGER.error("Only protocols [http] and [https] are supported, [{}] specified.", protocol);
                return null;
            }
        } else {
            protocol = "http";
            LOGGER.warn("No protocol specified, using default port [http].");
        }
        final int portInt = TypeConverters.convert(port, int.class, protocol.equals("https") ? HTTPS : HTTP);
        if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
            LOGGER.error("You must provide a username and password for the CouchDB provider.");
            return null;
        }
        client = new CouchDbClient(databaseName, false, protocol, server, portInt, username, password);
        description = "uri=" + client.getDBUri() + ", username=" + username;
    } else {
        LOGGER.error("No factory method was provided so the database name is required.");
        return null;
    }
    return new CouchDbProvider(client, description);
}
Also used : CouchDbClient(org.lightcouch.CouchDbClient) CouchDbProperties(org.lightcouch.CouchDbProperties) Method(java.lang.reflect.Method) PluginFactory(org.apache.logging.log4j.plugins.PluginFactory)

Aggregations

PluginFactory (org.apache.logging.log4j.plugins.PluginFactory)13 HashMap (java.util.HashMap)5 KeyValuePair (org.apache.logging.log4j.core.util.KeyValuePair)5 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Level (org.apache.logging.log4j.Level)3 Method (java.lang.reflect.Method)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 PrintWriter (java.io.PrintWriter)1 Reader (java.io.Reader)1 URI (java.net.URI)1 Charset (java.nio.charset.Charset)1 Path (java.nio.file.Path)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 TimeUnit (java.util.concurrent.TimeUnit)1 DataSource (javax.sql.DataSource)1