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 @Override
38 public void init(Object init)
39 {
40 super.init(init);
41
42 _templates=new String[Array.getLength(init)];
43 _replaces=new String[_templates.length];
44
45 for (int i=0;i<_templates.length;i++)
46 {
47 Object entry = Array.get(init,i);
48 _templates[i]=(String)Array.get(entry,0);
49 _replaces[i]=(String)Array.get(entry,1);
50 }
51
52 checkPatterns();
53 }
54
55 private void checkPatterns()
56 {
57 // TODO replace this check with a terracotta transient init clause
58 synchronized(this)
59 {
60 if (_patterns==null)
61 {
62 _patterns=new Pattern[_templates.length];
63 for (int i=0;i<_patterns.length;i++)
64 {
65 _patterns[i]=Pattern.compile(_templates[i]);
66 }
67 }
68 }
69 }
70
71 @Override
72 protected Object filterString(String string)
73 {
74 checkPatterns();
75
76 for (int i=0;i<_patterns.length;i++)
77 {
78 if (_replaces[i]!=null)
79 string=_patterns[i].matcher(string).replaceAll(_replaces[i]);
80 else if (_patterns[i].matcher(string).matches())
81 throw new IllegalStateException("matched "+_patterns[i]+" in "+string);
82 }
83 return string;
84 }
85 }