View Javadoc

1   /*
2    * $Id: ObjectToJson.java 19713 2010-09-24 14:54:29Z dirk.olmes $
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  package org.mule.module.json.transformers;
11  
12  import org.mule.api.MuleMessage;
13  import org.mule.api.lifecycle.InitialisationException;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.module.json.filters.IsJsonFilter;
16  import org.mule.transformer.types.DataTypeFactory;
17  
18  import java.io.IOException;
19  import java.io.StringWriter;
20  import java.io.UnsupportedEncodingException;
21  import java.util.ArrayList;
22  import java.util.HashMap;
23  import java.util.List;
24  import java.util.Map;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  /**
30   * Converts a java object to a JSON encoded object that can be consumed by other languages such as
31   * Javascript or Ruby.
32   * <p/>
33   * The returnClass for this transformer is always java.lang.String, there is no need to set this.
34   */
35  public class ObjectToJson extends AbstractJsonTransformer
36  {
37      /**
38       * logger used by this class
39       */
40      protected transient final Log logger = LogFactory.getLog(ObjectToJson.class);
41  
42      private Map<Class<?>, Class<?>> serializationMixins = new HashMap<Class<?>, Class<?>>();
43  
44      protected Class<?> sourceClass;
45  
46      private boolean handleException = false;
47  
48      private IsJsonFilter isJsonFilter = new IsJsonFilter();
49  
50      public ObjectToJson()
51      {
52          this.setReturnDataType(DataTypeFactory.JSON_STRING);
53      }
54  
55      @Override
56      public void initialise() throws InitialisationException
57      {
58          super.initialise();
59  
60          //restrict the handled types
61          if (getSourceClass() != null)
62          {
63              sourceTypes.clear();
64              registerSourceType(DataTypeFactory.create(getSourceClass()));
65          }
66  
67          //Add shared mixins first
68          for (Map.Entry<Class<?>, Class<?>> entry : getMixins().entrySet())
69          {
70              getMapper().getSerializationConfig().addMixInAnnotations(entry.getKey(), entry.getValue());
71          }
72  
73          for (Map.Entry<Class<?>, Class<?>> entry : serializationMixins.entrySet())
74          {
75              getMapper().getSerializationConfig().addMixInAnnotations(entry.getKey(), entry.getValue());
76          }
77      }
78  
79      @Override
80      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
81      {
82          Object src = message.getPayload();
83          if (src instanceof String && isJsonFilter.accept(src))
84          {
85              //Nothing to transform
86              return src;
87          }
88  
89          // Checks if there's an exception
90          if (message.getExceptionPayload() != null && this.isHandleException())
91          {
92              if (logger.isDebugEnabled())
93              {
94                  logger.debug("Found exception with null payload");
95              }
96              src = this.getException(message.getExceptionPayload().getException());
97          }
98  
99          StringWriter writer = new StringWriter();
100         try
101         {
102             getMapper().writeValue(writer, src);
103         }
104         catch (IOException e)
105         {
106             throw new TransformerException(this, e);
107         }
108         
109         if (returnType.getType().equals(byte[].class))
110         {
111             try
112             {
113                 return writer.toString().getBytes(outputEncoding);
114             }
115             catch (UnsupportedEncodingException uee)
116             {
117                 throw new TransformerException(this, uee);
118             }
119         }
120         else
121         {
122             return writer.toString();
123         }
124     }
125 
126     /**
127      * The reason of having this is because the original exception object is way too
128      * complex and it breaks JSON-lib.
129      */
130     private Exception getException(Throwable t)
131     {
132         Exception returnValue = null;
133         List<Throwable> causeStack = new ArrayList<Throwable>();
134 
135         for (Throwable tempCause = t; tempCause != null; tempCause = tempCause.getCause())
136         {
137             causeStack.add(tempCause);
138         }
139 
140         for (int i = causeStack.size() - 1; i >= 0; i--)
141         {
142             Throwable tempCause = causeStack.get(i);
143 
144             // There is no cause at the very root
145             if (i == causeStack.size())
146             {
147                 returnValue = new Exception(tempCause.getMessage());
148                 returnValue.setStackTrace(tempCause.getStackTrace());
149             }
150             else
151             {
152                 returnValue = new Exception(tempCause.getMessage(), returnValue);
153                 returnValue.setStackTrace(tempCause.getStackTrace());
154             }
155         }
156 
157         return returnValue;
158     }
159 
160     public boolean isHandleException()
161     {
162         return this.handleException;
163     }
164 
165     public void setHandleException(boolean handleException)
166     {
167         this.handleException = handleException;
168     }
169 
170     public Class<?> getSourceClass()
171     {
172         return sourceClass;
173     }
174 
175     public void setSourceClass(Class<?> sourceClass)
176     {
177         this.sourceClass = sourceClass;
178     }
179 
180     public Map<Class<?>, Class<?>> getSerializationMixins()
181     {
182         return serializationMixins;
183     }
184 
185     public void setSerializationMixins(Map<Class<?>, Class<?>> serializationMixins)
186     {
187         this.serializationMixins = serializationMixins;
188     }
189 }
190