1   // ========================================================================
2   // Copyright 2007 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // Licensed under the Apache License, Version 2.0 (the "License");
5   // you may not use this file except in compliance with the License.
6   // You may obtain a copy of the License at 
7   // http://www.apache.org/licenses/LICENSE-2.0
8   // Unless required by applicable law or agreed to in writing, software
9   // distributed under the License is distributed on an "AS IS" BASIS,
10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  // See the License for the specific language governing permissions and
12  // limitations under the License.
13  //========================================================================
14  
15  package org.mortbay.cometd.filter;
16  
17  import java.lang.reflect.Array;
18  import java.util.regex.Pattern;
19  
20  
21  /**
22   * @author gregw
23   *
24   */
25  public class RegexFilter extends JSONDataFilter
26  {
27      String[] _templates;
28      String[] _replaces;
29      
30      transient Pattern[] _patterns;
31      
32      /**
33       * Assumes the init object is an Array of 2 element Arrays:  [regex,replacement].
34       * if the regex replacement string is null, then an IllegalStateException is thrown if
35       * the pattern matches.
36       */
37      public void init(Object init)
38      {
39          super.init(init);
40          
41          _templates=new String[Array.getLength(init)];
42          _replaces=new String[_templates.length];
43  
44          for (int i=0;i<_templates.length;i++)
45          {
46              Object entry = Array.get(init,i);
47              _templates[i]=(String)Array.get(entry,0);
48              _replaces[i]=(String)Array.get(entry,1);
49          }
50          
51          checkPatterns();
52      }
53      
54      private void checkPatterns()
55      {
56          // TODO replace this check with a terracotta transient init clause
57          synchronized(this)
58          {
59              if (_patterns==null)
60              {
61                  _patterns=new Pattern[_templates.length];
62                  for (int i=0;i<_patterns.length;i++)
63                  {
64                      _patterns[i]=Pattern.compile(_templates[i]);
65                  }
66              }
67          }
68      }
69  
70      protected Object filterString(String string)
71      {
72          checkPatterns();
73          
74          for (int i=0;i<_patterns.length;i++)
75          {
76              if (_replaces[i]!=null)
77                  string=_patterns[i].matcher(string).replaceAll(_replaces[i]);
78              else if (_patterns[i].matcher(string).matches())
79                  throw new IllegalStateException("matched "+_patterns[i]+" in "+string);
80          }
81          return string;
82      }
83  }