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