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  package org.apache.logging.log4j.core.appender.rolling.action;
18  
19  import java.nio.file.FileSystem;
20  import java.nio.file.FileSystems;
21  import java.nio.file.Path;
22  import java.nio.file.PathMatcher;
23  import java.nio.file.attribute.BasicFileAttributes;
24  import java.util.Arrays;
25  import java.util.Collections;
26  import java.util.List;
27  import java.util.regex.Pattern;
28  
29  import org.apache.logging.log4j.Logger;
30  import org.apache.logging.log4j.core.config.plugins.Plugin;
31  import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
32  import org.apache.logging.log4j.core.config.plugins.PluginElement;
33  import org.apache.logging.log4j.core.config.plugins.PluginFactory;
34  import org.apache.logging.log4j.status.StatusLogger;
35  
36  /**
37   * PathCondition that accepts files for deletion if their relative path matches either a glob pattern or a regular
38   * expression. If both a regular expression and a glob pattern are specified the glob pattern is used and the regular
39   * expression is ignored.
40   * <p>
41   * The regular expression is a pattern as defined by the {@link Pattern} class. A glob is a simplified pattern
42   * expression described in {@link FileSystem#getPathMatcher(String)}.
43   */
44  @Plugin(name = "IfFileName", category = "Core", printObject = true)
45  public final class IfFileName implements PathCondition {
46      private static final Logger LOGGER = StatusLogger.getLogger();
47      private final PathMatcher pathMatcher;
48      private final String syntaxAndPattern;
49      private final PathCondition[] nestedConditions;
50  
51      /**
52       * Constructs a FileNameFilter filter. If both a regular expression and a glob pattern are specified the glob
53       * pattern is used and the regular expression is ignored.
54       * 
55       * @param glob the baseDir-relative path pattern of the files to delete (may contain '*' and '?' wildcarts)
56       * @param regex the regular expression that matches the baseDir-relative path of the file(s) to delete
57       * @param nestedConditions nested conditions to evaluate if this condition accepts a path
58       */
59      private IfFileName(final String glob, final String regex, final PathCondition[] nestedConditions) {
60          if (regex == null && glob == null) {
61              throw new IllegalArgumentException("Specify either a path glob or a regular expression. "
62                      + "Both cannot be null.");
63          }
64          this.syntaxAndPattern = createSyntaxAndPatternString(glob, regex);
65          this.pathMatcher = FileSystems.getDefault().getPathMatcher(syntaxAndPattern);
66          this.nestedConditions = nestedConditions == null ? new PathCondition[0] : Arrays.copyOf(nestedConditions,
67                  nestedConditions.length);
68      }
69  
70      static String createSyntaxAndPatternString(final String glob, final String regex) {
71          if (glob != null) {
72              return glob.startsWith("glob:") ? glob : "glob:" + glob;
73          }
74          return regex.startsWith("regex:") ? regex : "regex:" + regex;
75      }
76  
77      /**
78       * Returns the baseDir-relative path pattern of the files to delete. The returned string takes the form
79       * {@code syntax:pattern} where syntax is one of "glob" or "regex" and the pattern is either a {@linkplain Pattern
80       * regular expression} or a simplified pattern expression described under "glob" in
81       * {@link FileSystem#getPathMatcher(String)}.
82       * 
83       * @return relative path of the file(s) to delete (may contain regular expression or wildcarts)
84       */
85      public String getSyntaxAndPattern() {
86          return syntaxAndPattern;
87      }
88  
89      public List<PathCondition> getNestedConditions() {
90          return Collections.unmodifiableList(Arrays.asList(nestedConditions));
91      }
92  
93      /*
94       * (non-Javadoc)
95       * 
96       * @see org.apache.logging.log4j.core.appender.rolling.action.PathCondition#accept(java.nio.file.Path,
97       * java.nio.file.Path, java.nio.file.attribute.BasicFileAttributes)
98       */
99      @Override
100     public boolean accept(final Path basePath, final Path relativePath, final BasicFileAttributes attrs) {
101         final boolean result = pathMatcher.matches(relativePath);
102 
103         final String match = result ? "matches" : "does not match";
104         final String accept = result ? "ACCEPTED" : "REJECTED";
105         LOGGER.trace("IfFileName {}: '{}' {} relative path '{}'", accept, syntaxAndPattern, match, relativePath);
106         if (result) {
107             return IfAll.accept(nestedConditions, basePath, relativePath, attrs);
108         }
109         return result;
110     }
111 
112     /*
113      * (non-Javadoc)
114      * 
115      * @see org.apache.logging.log4j.core.appender.rolling.action.PathCondition#beforeFileTreeWalk()
116      */
117     @Override
118     public void beforeFileTreeWalk() {
119         IfAll.beforeFileTreeWalk(nestedConditions);
120     }
121 
122     /**
123      * Creates a IfFileName condition that returns true if either the specified
124      * {@linkplain FileSystem#getPathMatcher(String) glob pattern} or the regular expression matches the relative path.
125      * If both a regular expression and a glob pattern are specified the glob pattern is used and the regular expression
126      * is ignored.
127      * 
128      * @param glob the baseDir-relative path pattern of the files to delete (may contain '*' and '?' wildcarts)
129      * @param regex the regular expression that matches the baseDir-relative path of the file(s) to delete
130      * @param nestedConditions nested conditions to evaluate if this condition accepts a path
131      * @return A IfFileName condition.
132      * @see FileSystem#getPathMatcher(String)
133      */
134     @PluginFactory
135     public static IfFileName createNameCondition( //
136             // @formatter:off
137             @PluginAttribute("glob") final String glob, //
138             @PluginAttribute("regex") final String regex, //
139             @PluginElement("PathConditions") final PathCondition... nestedConditions) {
140             // @formatter:on
141         return new IfFileName(glob, regex, nestedConditions);
142     }
143 
144     @Override
145     public String toString() {
146         final String nested = nestedConditions.length == 0 ? "" : " AND " + Arrays.toString(nestedConditions);
147         return "IfFileName(" + syntaxAndPattern + nested + ")";
148     }
149 }