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