View Javadoc

1   /*
2    * $Id: XmlToDomDocument.java 12307 2008-07-11 20:39:57Z tcarlson $
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.module.xml.transformer;
12  
13  import org.mule.api.transformer.DiscoverableTransformer;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.module.xml.util.XMLUtils;
16  
17  import javax.xml.stream.XMLStreamReader;
18  import javax.xml.transform.OutputKeys;
19  import javax.xml.transform.Source;
20  import javax.xml.transform.Transformer;
21  
22  import org.w3c.dom.Document;
23  
24  /** <code>XmlToDomDocument</code> transforms a XML String to org.w3c.dom.Document. */
25  public class XmlToDomDocument extends AbstractXmlTransformer implements DiscoverableTransformer
26  {
27      private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING;
28  
29      public Object doTransform(Object src, String encoding) throws TransformerException
30      {
31          try
32          {
33              Source sourceDoc = XMLUtils.toXmlSource(getXMLInputFactory(), isUseStaxSource(), src);
34              if (sourceDoc == null)
35              {
36                  return null;
37              }
38  
39              if (XMLStreamReader.class.equals(returnClass))
40              {
41                  return getXMLInputFactory().createXMLStreamReader(sourceDoc);
42              }
43              else if (returnClass.isAssignableFrom(sourceDoc.getClass()))
44              {
45                  return sourceDoc;
46              }
47              
48              // If returnClass is not set, assume W3C DOM
49              // This is the original behaviour
50              ResultHolder holder = getResultHolder(returnClass);
51              if (holder == null)
52              {
53                  holder = getResultHolder(Document.class);
54              }
55  
56              Transformer idTransformer = XMLUtils.getTransformer();
57              idTransformer.setOutputProperty(OutputKeys.ENCODING, encoding);
58              idTransformer.transform(sourceDoc, holder.getResult());
59  
60              return holder.getResultObject();
61          }
62          catch (Exception e)
63          {
64              throw new TransformerException(this, e);
65          }
66      }
67  
68      public int getPriorityWeighting()
69      {
70          return priorityWeighting;
71      }
72  
73      public void setPriorityWeighting(int priorityWeighting)
74      {
75          this.priorityWeighting = priorityWeighting;
76      }
77  }