View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  
18  package org.apache.logging.log4j.core.appender.rolling.action;
19  
20  import java.nio.file.Path;
21  import java.util.List;
22  import java.util.Objects;
23  
24  import javax.script.SimpleBindings;
25  
26  import org.apache.logging.log4j.Logger;
27  import org.apache.logging.log4j.core.config.Configuration;
28  import org.apache.logging.log4j.core.config.plugins.Plugin;
29  import org.apache.logging.log4j.core.config.plugins.PluginConfiguration;
30  import org.apache.logging.log4j.core.config.plugins.PluginElement;
31  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
32  import org.apache.logging.log4j.core.script.AbstractScript;
33  import org.apache.logging.log4j.core.script.ScriptRef;
34  import org.apache.logging.log4j.status.StatusLogger;
35  
36  /**
37   * A condition of the {@link DeleteAction} where a user-provided script selects the files to delete from a provided
38   * list. The specified script may be a {@link Script}, a {@link ScriptFile} or a {@link ScriptRef}.
39   * 
40   * @see #createCondition(AbstractScript, Configuration)
41   */
42  @Plugin(name = "ScriptCondition", category = "Core", printObject = true)
43  public class ScriptCondition {
44      private static Logger LOGGER = StatusLogger.getLogger();
45  
46      private final AbstractScript script;
47      private final Configuration configuration;
48  
49      /**
50       * Constructs a new ScriptCondition.
51       * 
52       * @param script the script that can select files to delete
53       * @param configuration configuration containing the StrSubstitutor passed to the script
54       */
55      public ScriptCondition(final AbstractScript script, final Configuration configuration) {
56          this.script = Objects.requireNonNull(script, "script");
57          this.configuration = Objects.requireNonNull(configuration, "configuration");
58          if (!(script instanceof ScriptRef)) {
59              configuration.getScriptManager().addScript(script);
60          }
61      }
62  
63      /**
64       * Executes the script
65       * 
66       * @param baseDir
67       * @param candidates
68       * @return
69       */
70      @SuppressWarnings("unchecked")
71      public List<PathWithAttributes> selectFilesToDelete(final Path basePath, final List<PathWithAttributes> candidates) {
72          final SimpleBindings bindings = new SimpleBindings();
73          bindings.put("basePath", basePath);
74          bindings.put("pathList", candidates);
75          bindings.putAll(configuration.getProperties());
76          bindings.put("configuration", configuration);
77          bindings.put("substitutor", configuration.getStrSubstitutor());
78          bindings.put("statusLogger", LOGGER);
79          final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
80          return (List<PathWithAttributes>) object;
81      }
82  
83      /**
84       * Creates the ScriptCondition.
85       * 
86       * @param script The script to run. This may be a {@link Script}, a {@link ScriptFile} or a {@link ScriptRef}. The
87       *            script must return a {@code List<PathWithAttributes>}. When the script is executed, it is provided the
88       *            following bindings:
89       *            <ul>
90       *            <li>basePath - the directory from where the {@link DeleteAction Delete} action started scanning for
91       *            files to delete. Can be used to relativize the paths in the pathList.</li>
92       *            <li>pathList - a {@code java.util.List} containing {@link PathWithAttribute} objects. (The script is
93       *            free to modify and return this list.)</li>
94       *            <li>substitutor - a {@link StrSubstitutor} that can be used to look up variables embedded in the base
95       *            dir or other properties
96       *            <li>statusLogger - the {@link StatusLogger} that can be used to log events during script execution
97       *            <li>any properties declared in the configuration</li>
98       *            </ul>
99       * @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 }