View Javadoc

1   /*
2    * $Id: XmlToObject.java 7976 2007-08-21 14:26:13Z dirk.olmes $
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  
18  /**
19   * <code>XmlToObject</code> converts xml created by the ObjectToXml transformer in
20   * to a java object graph. This transformer uses XStream. Xstream uses some clever
21   * tricks so objects that get marshalled to XML do not need to implement any
22   * interfaces including Serializable and you don't even need to specify a default
23   * constructor.
24   * 
25   * @see org.mule.transformers.xml.ObjectToXml
26   */
27  
28  public class XmlToObject extends AbstractXStreamTransformer
29  {
30  
31      private final DomDocumentToXml domTransformer = new DomDocumentToXml();
32  
33      public XmlToObject()
34      {
35          registerSourceType(String.class);
36          registerSourceType(byte[].class);
37          registerSourceType(org.w3c.dom.Document.class);
38          registerSourceType(org.dom4j.Document.class);
39      }
40  
41      public Object transform(Object src, String encoding, UMOEventContext context) throws TransformerException
42      {
43          if (src instanceof byte[])
44          {
45              return getXStream().fromXML(new ByteArrayInputStream((byte[]) src));
46          }
47          else if (src instanceof String)
48          {
49              return getXStream().fromXML(src.toString());
50          }
51          else
52          {
53              return getXStream().fromXML((String) domTransformer.transform(src));
54          }
55      }
56  
57  }