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 protected transient final Log logger = LogFactory.getLog(IsJsonFilter.class);
29
30 private boolean validateParsing = false;
31
32 public IsJsonFilter()
33 {
34 super();
35 }
36
37 public boolean accept(MuleMessage obj)
38 {
39
40 final String contentType = obj.getOutboundProperty("Content-Type", StringUtils.EMPTY);
41 if (contentType.contains("application/json"))
42 {
43 return true;
44 }
45 try
46 {
47 return accept(obj.getPayloadAsString());
48 }
49 catch (Exception e)
50 {
51 logger.warn("Failed to read object payload as string for isJsonFilter", e);
52 return false;
53 }
54 }
55
56 public boolean accept(Object obj)
57 {
58
59 try
60 {
61 if (obj instanceof byte[])
62 {
63 obj = new String((byte[])obj);
64 }
65
66 if (obj instanceof String)
67 {
68 if (!mayBeJSON((String) obj))
69 {
70 return false;
71 }
72
73 if (isValidateParsing())
74 {
75 new ObjectMapper().readTree((String) obj);
76 }
77 return true;
78 }
79 else
80 {
81 return false;
82 }
83
84 }
85 catch (IOException e)
86 {
87 logger.error("Filter result = false (message is not valid JSON): " + e.getMessage());
88 return false;
89 }
90 }
91
92 public boolean isValidateParsing()
93 {
94 return validateParsing;
95 }
96
97 public void setValidateParsing(boolean validateParsing)
98 {
99 this.validateParsing = validateParsing;
100 }
101
102
103
104
105
106
107
108
109
110
111
112
113 protected boolean mayBeJSON(String string)
114 {
115 return string != null
116 && ("null".equals(string)
117 || (string.startsWith("[") && string.endsWith("]")) || (string.startsWith("{") && string.endsWith("}")));
118 }
119 }