View Javadoc

1   /*
2    * $Id: XmlToObject.java 9594 2007-11-05 11:15:16Z holger $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.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.transformers.xml;
12  
13  import org.mule.umo.UMOEventContext;
14  import org.mule.umo.transformer.TransformerException;
15  
16  import java.io.ByteArrayInputStream;
17  import java.io.InputStreamReader;
18  import java.io.Reader;
19  import java.io.UnsupportedEncodingException;
20  
21  /**
22   * <code>XmlToObject</code> converts xml created by the ObjectToXml transformer in to a
23   * java object graph. This transformer uses XStream. Xstream uses some clever tricks so
24   * objects that get marshalled to XML do not need to implement any interfaces including
25   * Serializable and you don't even need to specify a default constructor.
26   * 
27   * @see org.mule.transformers.xml.ObjectToXml
28   */
29  
30  public class XmlToObject extends AbstractXStreamTransformer
31  {
32  
33      private final DomDocumentToXml domTransformer = new DomDocumentToXml();
34  
35      public XmlToObject()
36      {
37          registerSourceType(String.class);
38          registerSourceType(byte[].class);
39          registerSourceType(org.w3c.dom.Document.class);
40          registerSourceType(org.dom4j.Document.class);
41      }
42  
43      public Object transform(Object src, String encoding, UMOEventContext context) throws TransformerException
44      {
45          if (src instanceof byte[])
46          {
47              try
48              {
49                  Reader xml = new InputStreamReader(new ByteArrayInputStream((byte[]) src), encoding);
50                  return getXStream().fromXML(xml);
51              }
52              catch (UnsupportedEncodingException uee)
53              {
54                  throw new TransformerException(this, uee);
55              }
56          }
57          else if (src instanceof String)
58          {
59              return getXStream().fromXML(src.toString());
60          }
61          else
62          {
63              return getXStream().fromXML((String) domTransformer.transform(src));
64          }
65      }
66  
67  }