View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
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   * A filter that will determine if the current message payload is a JSON encoded message.
21   */
22  public class IsJsonFilter implements Filter
23  {
24  
25      /**
26       * logger used by this class
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          // TODO should be checking inbound IMO
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      * Tests if the String possibly represents a valid JSON String.
104      *
105      * @param string Valid JSON strings are:
106      *               <ul>
107      *               <li>"null"</li>
108      *               <li>starts with "[" and ends with "]"</li>
109      *               <li>starts with "{" and ends with "}"</li>
110      *               </ul>
111      * @return true if the test string starts with one of the valid json characters
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 }