View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.file.filters;
8   
9   import java.util.regex.Matcher;
10  import java.util.regex.Pattern;
11  
12  /**
13   * <code>FilenameRegexFilter</code> filters incoming files from a directory, based
14   * on a regular expression. If the expression evaluates to true, then the file will
15   * be accepted.
16   */
17  public class FilenameRegexFilter extends FilenameWildcardFilter
18  {
19      protected volatile Pattern[] compiledPatterns = null;
20  
21      /**
22       * Filter condition decider method.
23       * <p>
24       * Returns <code>boolean</code> <code>TRUE</code> if the file conforms to the
25       * regular expression pattern or <code>FALSE</code> otherwise.
26       * 
27       * @return indication of acceptance as boolean.
28       */
29      @Override
30      public boolean accept(Object object)
31      {
32          if (object == null)
33          {
34              return false;
35          }
36  
37          boolean foundMatch = false;
38  
39          if (compiledPatterns != null)
40          {
41              for (int i = 0; i < compiledPatterns.length; i++)
42              {
43                  Pattern pattern = compiledPatterns[i];
44                  String string = object.toString();
45  
46                  /* Determine if there is an exact match. */
47                  Matcher matcher = pattern.matcher(string);
48                  foundMatch = matcher.matches();
49  
50                  if (foundMatch)
51                  {
52                      // we found a match, bail
53                      break;
54                  }
55              }
56          }
57  
58          return foundMatch;
59      }
60  
61      @Override
62      public void setCaseSensitive(boolean caseSensitive)
63      {
64          super.setCaseSensitive(caseSensitive);
65          this.setPattern(pattern);
66      }
67  
68      @Override
69      public void setPattern(String pattern)
70      {
71          super.setPattern(pattern);
72  
73          if (patterns != null)
74          {
75              compiledPatterns = new Pattern[patterns.length];
76  
77              for (int i = 0; i < patterns.length; i++)
78              {
79                  if (!isCaseSensitive())
80                  {
81                      /* Add insensitive option if set in the configuration. */
82                      compiledPatterns[i] = Pattern.compile(patterns[i], Pattern.CASE_INSENSITIVE);
83                  }
84                  else
85                  {
86                      compiledPatterns[i] = Pattern.compile(patterns[i]);
87                  }
88              }
89          }
90      }
91  
92  }