View Javadoc

1   /*
2    * $Id: JsonToObject.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.transformers;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.lifecycle.InitialisationException;
15  import org.mule.api.transformer.DataType;
16  import org.mule.api.transformer.TransformerException;
17  import org.mule.config.i18n.CoreMessages;
18  import org.mule.module.json.JsonData;
19  import org.mule.transformer.types.DataTypeFactory;
20  import org.mule.util.IOUtils;
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.InputStream;
26  import java.io.InputStreamReader;
27  import java.io.Reader;
28  import java.net.URL;
29  import java.util.HashMap;
30  import java.util.Map;
31  
32  
33  /**
34   * A transformer that will convert a JSON encoded object graph to a java object. The object type is
35   * determined by the 'returnClass' attribute. Note that this transformers supports Arrays and Lists. For
36   * example, to
37   * convert a JSON string to an array of org.foo.Person, set the the returnClass=[Lorg.foo.Person;.
38   * <p/>
39   * The JSON engine can be configured using the jsonConfig attribute. This is an object reference to an
40   * instance of: {@link net.sf.json.JsonConfig}. This can be created as a spring bean.
41   */
42  public class JsonToObject extends AbstractJsonTransformer
43  {
44      private static final DataType<JsonData> JSON_TYPE = DataTypeFactory.create(JsonData.class);
45      
46      private Map<Class<?>, Class<?>> deserializationMixins = new HashMap<Class<?>, Class<?>>();
47      
48      public JsonToObject()
49      {
50          this.registerSourceType(DataTypeFactory.create(Reader.class));
51          this.registerSourceType(DataTypeFactory.create(URL.class));
52          this.registerSourceType(DataTypeFactory.create(File.class));
53          this.registerSourceType(DataTypeFactory.STRING);
54          this.registerSourceType(DataTypeFactory.INPUT_STREAM);
55          this.registerSourceType(DataTypeFactory.BYTE_ARRAY);
56          setReturnDataType(JSON_TYPE);
57      }
58  
59      @Override
60      public void initialise() throws InitialisationException
61      {
62          super.initialise();
63          //Add shared mixins first
64          for (Map.Entry<Class<?>, Class<?>> entry : getMixins().entrySet())
65          {
66              getMapper().getDeserializationConfig().addMixInAnnotations(entry.getKey(), entry.getValue());
67          }
68  
69          for (Map.Entry<Class<?>, Class<?>> entry : deserializationMixins.entrySet())
70          {
71              getMapper().getDeserializationConfig().addMixInAnnotations(entry.getKey(), entry.getValue());
72          }
73      }
74  
75      @Override
76      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
77      {
78          Object src = message.getPayload();
79          Object returnValue;
80          InputStream is = null;
81          Reader reader = null;
82  
83          try
84          {
85              if (src instanceof InputStream)
86              {
87                  is = (InputStream) src;
88              }
89              else if (src instanceof File)
90              {
91                  is = new FileInputStream((File) src);
92              }
93              else if (src instanceof URL)
94              {
95                  is = ((URL) src).openStream();
96              }
97              else if (src instanceof byte[])
98              {
99                  is = new ByteArrayInputStream((byte[]) src);
100             }
101             
102             if (src instanceof Reader)
103             {
104                 if (getReturnDataType().equals(JSON_TYPE))
105                 {
106                     returnValue = new JsonData((Reader) src);
107                 }
108                 else
109                 {
110                     returnValue = getMapper().readValue((Reader) src, getReturnDataType().getType());
111                 }
112             }
113             else if (src instanceof String)
114             {
115                 if (getReturnDataType().equals(JSON_TYPE))
116                 {
117                     returnValue = new JsonData((String) src);
118                 }
119                 else
120                 {
121                     returnValue = getMapper().readValue((String) src, getReturnDataType().getType());
122                 }
123             }
124             else
125             {
126                 reader = new InputStreamReader(is, outputEncoding);
127                 if (getReturnDataType().equals(JSON_TYPE))
128                 {
129                     returnValue = new JsonData(reader);
130                 }
131                 else
132                 {
133                     returnValue = getMapper().readValue(reader, getReturnDataType().getType());
134                 }
135             }
136             return returnValue;
137         }
138         catch (Exception e)
139         {
140             throw new TransformerException(CoreMessages.transformFailed("json",
141                 getReturnDataType().getType().getName()), this, e);
142         }
143         finally
144         {
145             IOUtils.closeQuietly(reader);
146             IOUtils.closeQuietly(is);
147         }
148     }
149 
150     public Map<Class<?>, Class<?>> getDeserializationMixins()
151     {
152         return deserializationMixins;
153     }
154 
155     public void setDeserializationMixins(Map<Class<?>, Class<?>> deserializationMixins)
156     {
157         this.deserializationMixins = deserializationMixins;
158     }
159 }