View Javadoc

1   /*
2    * $Id: RegExFilter.java 10534 2008-01-25 14:30:31Z marie.rizzo $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.routing.filters;
12  
13  import org.apache.commons.logging.Log;
14  import org.apache.commons.logging.LogFactory;
15  import org.mule.config.i18n.CoreMessages;
16  import org.mule.transformers.simple.ByteArrayToString;
17  import org.mule.umo.UMOFilter;
18  import org.mule.umo.UMOMessage;
19  import org.mule.umo.transformer.TransformerException;
20  
21  import java.util.regex.Pattern;
22  
23  /**
24   * <code>RegExFilter</code> is used to match a String argument against a regular
25   * expression.
26   */
27  
28  public class RegExFilter implements UMOFilter, ObjectFilter
29  {
30      protected transient Log logger = LogFactory.getLog(getClass());
31  
32      private Pattern pattern;
33  
34      public RegExFilter()
35      {
36          super();
37      }
38  
39      public RegExFilter(String pattern)
40      {
41          this.pattern = Pattern.compile(pattern);
42      }
43  
44      public boolean accept(UMOMessage message)
45      {
46          return accept(message.getPayload());
47      }
48  
49      public boolean accept(Object object)
50      {
51          if (object == null)
52          {
53              return false;
54          }
55  
56          Object tempObject = object;
57  
58          // check whether the payload is a byte[] or a char[]. If it is, then it has 
59          // to be transformed otherwise the toString will not represent the true contents
60          // of the payload for the RegEx filter to use.
61          if (object instanceof byte[])
62          {
63              ByteArrayToString transformer = new ByteArrayToString();
64              try
65              {
66                  object = transformer.transform(object);
67              }
68              catch (TransformerException e)
69              {
70              	logger.warn(CoreMessages.transformFailedBeforeFilter(), e);
71                  // revert transformation
72                  object = tempObject;
73              }
74          }
75          else if (object instanceof char[])
76          {
77              object = new String((char[]) object);
78          }
79  
80          return (pattern != null ? pattern.matcher(object.toString()).find() : false);
81      }
82  
83      public String getPattern()
84      {
85          return (pattern == null ? null : pattern.pattern());
86      }
87  
88      public void setPattern(String pattern)
89      {
90          this.pattern = (pattern != null ? Pattern.compile(pattern) : null);
91      }
92  
93  }