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