1
2
3
4
5
6
7
8
9
10
11 package org.mule.routing.filters;
12
13 import org.mule.api.MuleMessage;
14 import org.mule.api.routing.filter.Filter;
15 import org.mule.api.routing.filter.ObjectFilter;
16 import org.mule.api.transformer.TransformerException;
17 import org.mule.config.i18n.CoreMessages;
18 import org.mule.transformer.simple.ByteArrayToObject;
19 import org.mule.util.ClassUtils;
20
21 import java.util.regex.Pattern;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25
26 import static org.mule.util.ClassUtils.hash;
27
28
29
30
31 public class RegExFilter implements Filter, ObjectFilter
32 {
33 private static final int NO_FLAGS = 0;
34 protected transient Log logger = LogFactory.getLog(getClass());
35
36 private Pattern pattern;
37
38 private int flags = NO_FLAGS;
39
40 public RegExFilter()
41 {
42 super();
43 }
44
45 public RegExFilter(String pattern)
46 {
47 this(pattern, NO_FLAGS);
48 }
49
50 public RegExFilter(String pattern, int flags)
51 {
52 this.pattern = Pattern.compile(pattern, flags);
53 this.flags = flags;
54 }
55
56 public boolean accept(MuleMessage message)
57 {
58 try
59 {
60 return accept(message.getPayloadAsString());
61 }
62 catch (Exception e)
63 {
64 throw new IllegalArgumentException(e);
65 }
66 }
67
68 public boolean accept(Object object)
69 {
70 if (object == null)
71 {
72 return false;
73 }
74
75 Object tempObject = object;
76
77
78
79
80
81 if (object instanceof byte[])
82 {
83 ByteArrayToObject transformer = new ByteArrayToObject();
84 try
85 {
86 object = transformer.transform(object);
87 }
88 catch (TransformerException e)
89 {
90 logger.warn(CoreMessages.transformFailedBeforeFilter(), e);
91
92 object = tempObject;
93 }
94 }
95 else if (object instanceof char[])
96 {
97 object = new String((char[]) object);
98 }
99
100 return (pattern != null && pattern.matcher(object.toString()).find());
101 }
102
103 public String getPattern()
104 {
105 return (pattern == null ? null : pattern.pattern());
106 }
107
108 public void setPattern(String pattern)
109 {
110 this.pattern = (pattern != null ? Pattern.compile(pattern, flags) : null);
111 }
112
113 public int getFlags()
114 {
115 return flags;
116 }
117
118 public void setFlags(int flags)
119 {
120 this.flags = flags;
121 this.pattern = (this.pattern != null ? Pattern.compile(pattern.pattern(), flags) : null);
122 }
123
124 @Override
125 public boolean equals(Object obj)
126 {
127 if (this == obj) return true;
128 if (obj == null || getClass() != obj.getClass()) return false;
129
130 final RegExFilter other = (RegExFilter) obj;
131 boolean patternsAreEqual = ClassUtils.equal(pattern.pattern(), other.pattern.pattern());
132 boolean flagsAreEqual = (flags == other.flags);
133 return (patternsAreEqual && flagsAreEqual);
134 }
135
136 @Override
137 public int hashCode()
138 {
139 return hash(new Object[]{this.getClass(), pattern});
140 }
141 }