View Javadoc

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