View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.module.xml.transformer;
8   
9   import org.mule.api.MuleMessage;
10  import org.mule.api.transformer.DiscoverableTransformer;
11  import org.mule.api.transformer.TransformerException;
12  import org.mule.module.xml.util.XMLUtils;
13  
14  import javax.xml.stream.XMLStreamReader;
15  import javax.xml.transform.OutputKeys;
16  import javax.xml.transform.Source;
17  import javax.xml.transform.Transformer;
18  
19  import org.w3c.dom.Document;
20  
21  /**
22   * <code>XmlToDomDocument</code> transforms a XML String to org.w3c.dom.Document.
23   */
24  public class XmlToDomDocument extends AbstractXmlTransformer implements DiscoverableTransformer
25  {
26      private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING;
27  
28      @Override
29      public Object transformMessage(MuleMessage message, String encoding) throws TransformerException
30      {
31          Object src = message.getPayload();
32          try
33          {
34              Source sourceDoc = XMLUtils.toXmlSource(getXMLInputFactory(), isUseStaxSource(), src);
35              if (sourceDoc == null)
36              {
37                  return null;
38              }
39  
40              if (XMLStreamReader.class.equals(returnType))
41              {
42                  return getXMLInputFactory().createXMLStreamReader(sourceDoc);
43              }
44              else if (returnType.getType().isAssignableFrom(sourceDoc.getClass()))
45              {
46                  return sourceDoc;
47              }
48  
49              // If returnClass is not set, assume W3C DOM
50              // This is the original behaviour
51              ResultHolder holder = getResultHolder(returnType.getType());
52              if (holder == null)
53              {
54                  holder = getResultHolder(Document.class);
55              }
56  
57              Transformer idTransformer = XMLUtils.getTransformer();
58              idTransformer.setOutputProperty(OutputKeys.ENCODING, encoding);
59              idTransformer.transform(sourceDoc, holder.getResult());
60  
61              return holder.getResultObject();
62          }
63          catch (Exception e)
64          {
65              throw new TransformerException(this, e);
66          }
67      }
68  
69      public int getPriorityWeighting()
70      {
71          return priorityWeighting;
72      }
73  
74      public void setPriorityWeighting(int priorityWeighting)
75      {
76          this.priorityWeighting = priorityWeighting;
77      }
78  }