1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
package org.mule.module.json.filters; |
12 | |
|
13 | |
import org.mule.api.MuleMessage; |
14 | |
import org.mule.api.routing.filter.Filter; |
15 | |
import org.mule.util.StringUtils; |
16 | |
|
17 | |
import java.io.IOException; |
18 | |
|
19 | |
import org.apache.commons.logging.Log; |
20 | |
import org.apache.commons.logging.LogFactory; |
21 | |
import org.codehaus.jackson.map.ObjectMapper; |
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
public class IsJsonFilter implements Filter |
27 | |
{ |
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | 0 | protected transient final Log logger = LogFactory.getLog(IsJsonFilter.class); |
33 | |
|
34 | 0 | private boolean validateParsing = false; |
35 | |
|
36 | |
public IsJsonFilter() |
37 | |
{ |
38 | 0 | super(); |
39 | 0 | } |
40 | |
|
41 | |
public boolean accept(MuleMessage obj) |
42 | |
{ |
43 | |
|
44 | 0 | final String contentType = obj.getOutboundProperty("Content-Type", StringUtils.EMPTY); |
45 | 0 | if (contentType.contains("application/json")) |
46 | |
{ |
47 | 0 | return true; |
48 | |
} |
49 | |
try |
50 | |
{ |
51 | 0 | return accept(obj.getPayloadAsString()); |
52 | |
} |
53 | 0 | catch (Exception e) |
54 | |
{ |
55 | 0 | logger.warn("Failed to read object payload as string for isJsonFilter", e); |
56 | 0 | return false; |
57 | |
} |
58 | |
} |
59 | |
|
60 | |
public boolean accept(Object obj) |
61 | |
{ |
62 | |
|
63 | |
try |
64 | |
{ |
65 | 0 | if (obj instanceof byte[]) |
66 | |
{ |
67 | 0 | obj = new String((byte[])obj); |
68 | |
} |
69 | |
|
70 | 0 | if (obj instanceof String) |
71 | |
{ |
72 | 0 | if (!mayBeJSON((String) obj)) |
73 | |
{ |
74 | 0 | return false; |
75 | |
} |
76 | |
|
77 | 0 | if (isValidateParsing()) |
78 | |
{ |
79 | 0 | new ObjectMapper().readTree((String) obj); |
80 | |
} |
81 | 0 | return true; |
82 | |
} |
83 | |
else |
84 | |
{ |
85 | 0 | return false; |
86 | |
} |
87 | |
|
88 | |
} |
89 | 0 | catch (IOException e) |
90 | |
{ |
91 | 0 | logger.error("Filter result = false (message is not valid JSON): " + e.getMessage()); |
92 | 0 | return false; |
93 | |
} |
94 | |
} |
95 | |
|
96 | |
public boolean isValidateParsing() |
97 | |
{ |
98 | 0 | return validateParsing; |
99 | |
} |
100 | |
|
101 | |
public void setValidateParsing(boolean validateParsing) |
102 | |
{ |
103 | 0 | this.validateParsing = validateParsing; |
104 | 0 | } |
105 | |
|
106 | |
|
107 | |
|
108 | |
|
109 | |
|
110 | |
|
111 | |
|
112 | |
|
113 | |
|
114 | |
|
115 | |
|
116 | |
|
117 | |
protected boolean mayBeJSON(String string) |
118 | |
{ |
119 | 0 | return string != null |
120 | |
&& ("null".equals(string) |
121 | |
|| (string.startsWith("[") && string.endsWith("]")) || (string.startsWith("{") && string.endsWith("}"))); |
122 | |
} |
123 | |
} |