1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
package org.mule.module.xml.transformer; |
12 | |
|
13 | |
import org.mule.api.MuleMessage; |
14 | |
import org.mule.api.transformer.TransformerException; |
15 | |
|
16 | |
import java.io.ByteArrayInputStream; |
17 | |
import java.io.IOException; |
18 | |
import java.io.InputStream; |
19 | |
import java.io.InputStreamReader; |
20 | |
import java.io.Reader; |
21 | |
import java.io.UnsupportedEncodingException; |
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
public class XmlToObject extends AbstractXStreamTransformer |
33 | |
{ |
34 | |
|
35 | 44 | private final DomDocumentToXml domTransformer = new DomDocumentToXml(); |
36 | |
|
37 | |
public XmlToObject() |
38 | 44 | { |
39 | 44 | registerSourceType(String.class); |
40 | 44 | registerSourceType(byte[].class); |
41 | 44 | registerSourceType(InputStream.class); |
42 | 44 | registerSourceType(org.w3c.dom.Document.class); |
43 | 44 | registerSourceType(org.dom4j.Document.class); |
44 | 44 | setReturnClass(Object.class); |
45 | 44 | } |
46 | |
|
47 | |
public Object transform(MuleMessage message, String outputEncoding) throws TransformerException |
48 | |
{ |
49 | 22 | Object src = message.getPayload(); |
50 | 22 | if (src instanceof byte[]) |
51 | |
{ |
52 | |
try |
53 | |
{ |
54 | 4 | Reader xml = new InputStreamReader(new ByteArrayInputStream((byte[]) src), outputEncoding); |
55 | 4 | return getXStream().fromXML(xml); |
56 | |
} |
57 | 0 | catch (UnsupportedEncodingException uee) |
58 | |
{ |
59 | 0 | throw new TransformerException(this, uee); |
60 | |
} |
61 | |
} |
62 | 18 | else if(src instanceof InputStream) |
63 | |
{ |
64 | 6 | InputStream input = (InputStream) src; |
65 | |
try |
66 | |
{ |
67 | 6 | Reader xml = new InputStreamReader(input, outputEncoding); |
68 | 6 | return getXStream().fromXML(xml); |
69 | |
} |
70 | 0 | catch (UnsupportedEncodingException uee) |
71 | |
{ |
72 | 0 | throw new TransformerException(this, uee); |
73 | |
} |
74 | |
finally |
75 | |
{ |
76 | 0 | try |
77 | |
{ |
78 | 6 | input.close(); |
79 | |
} |
80 | 0 | catch (IOException e) |
81 | |
{ |
82 | 0 | logger.warn("Exception closing stream: ", e); |
83 | 12 | } |
84 | |
} |
85 | |
} |
86 | 12 | else if (src instanceof String) |
87 | |
{ |
88 | 12 | return getXStream().fromXML(src.toString()); |
89 | |
} |
90 | |
else |
91 | |
{ |
92 | 0 | return getXStream().fromXML((String) domTransformer.transform(src)); |
93 | |
} |
94 | |
} |
95 | |
|
96 | |
} |