001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.appender.rolling.action;
019
020import java.nio.file.Path;
021import java.util.List;
022import java.util.Objects;
023
024import javax.script.SimpleBindings;
025
026import org.apache.logging.log4j.Logger;
027import org.apache.logging.log4j.core.config.Configuration;
028import org.apache.logging.log4j.core.config.plugins.Plugin;
029import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
030import org.apache.logging.log4j.core.config.plugins.PluginElement;
031import org.apache.logging.log4j.core.config.plugins.PluginFactory;
032import org.apache.logging.log4j.core.script.AbstractScript;
033import org.apache.logging.log4j.core.script.ScriptRef;
034import org.apache.logging.log4j.status.StatusLogger;
035
036/**
037 * A condition of the {@link DeleteAction} where a user-provided script selects the files to delete from a provided
038 * list. The specified script may be a {@link Script}, a {@link ScriptFile} or a {@link ScriptRef}.
039 * 
040 * @see #createCondition(AbstractScript, Configuration)
041 */
042@Plugin(name = "ScriptCondition", category = "Core", printObject = true)
043public class ScriptCondition {
044    private static Logger LOGGER = StatusLogger.getLogger();
045
046    private final AbstractScript script;
047    private final Configuration configuration;
048
049    /**
050     * Constructs a new ScriptCondition.
051     * 
052     * @param script the script that can select files to delete
053     * @param configuration configuration containing the StrSubstitutor passed to the script
054     */
055    public ScriptCondition(final AbstractScript script, final Configuration configuration) {
056        this.script = Objects.requireNonNull(script, "script");
057        this.configuration = Objects.requireNonNull(configuration, "configuration");
058        if (!(script instanceof ScriptRef)) {
059            configuration.getScriptManager().addScript(script);
060        }
061    }
062
063    /**
064     * Executes the script
065     * 
066     * @param baseDir
067     * @param candidates
068     * @return
069     */
070    @SuppressWarnings("unchecked")
071    public List<PathWithAttributes> selectFilesToDelete(final Path basePath, final List<PathWithAttributes> candidates) {
072        final SimpleBindings bindings = new SimpleBindings();
073        bindings.put("basePath", basePath);
074        bindings.put("pathList", candidates);
075        bindings.putAll(configuration.getProperties());
076        bindings.put("configuration", configuration);
077        bindings.put("substitutor", configuration.getStrSubstitutor());
078        bindings.put("statusLogger", LOGGER);
079        final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
080        return (List<PathWithAttributes>) object;
081    }
082
083    /**
084     * Creates the ScriptCondition.
085     * 
086     * @param script The script to run. This may be a {@link Script}, a {@link ScriptFile} or a {@link ScriptRef}. The
087     *            script must return a {@code List<PathWithAttributes>}. When the script is executed, it is provided the
088     *            following bindings:
089     *            <ul>
090     *            <li>basePath - the directory from where the {@link DeleteAction Delete} action started scanning for
091     *            files to delete. Can be used to relativize the paths in the pathList.</li>
092     *            <li>pathList - a {@code java.util.List} containing {@link PathWithAttribute} objects. (The script is
093     *            free to modify and return this list.)</li>
094     *            <li>substitutor - a {@link StrSubstitutor} that can be used to look up variables embedded in the base
095     *            dir or other properties
096     *            <li>statusLogger - the {@link StatusLogger} that can be used to log events during script execution
097     *            <li>any properties declared in the configuration</li>
098     *            </ul>
099     * @param configuration the configuration
100     * @return A ScriptCondition.
101     */
102    @PluginFactory
103    public static ScriptCondition createCondition(@PluginElement("Script") final AbstractScript script,
104            @PluginConfiguration final Configuration configuration) {
105
106        if (script == null) {
107            LOGGER.error("A Script, ScriptFile or ScriptRef element must be provided for this ScriptCondition");
108            return null;
109        }
110        if (script instanceof ScriptRef) {
111            if (configuration.getScriptManager().getScript(script.getName()) == null) {
112                LOGGER.error("ScriptCondition: No script with name {} has been declared.", script.getName());
113                return null;
114            }
115        }
116        return new ScriptCondition(script, configuration);
117    }
118}