1
2
3
4
5
6
7
8
9
10
11 package org.mule.transformer.simple;
12
13 import org.mule.api.MuleEvent;
14 import org.mule.api.transformer.DiscoverableTransformer;
15 import org.mule.api.transformer.TransformerException;
16 import org.mule.api.transport.OutputHandler;
17 import org.mule.config.i18n.MessageFactory;
18 import org.mule.transformer.AbstractTransformer;
19 import org.mule.util.IOUtils;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.io.Serializable;
25
26 import org.apache.commons.lang.SerializationUtils;
27
28
29 public class ObjectToOutputHandler extends AbstractTransformer implements DiscoverableTransformer
30 {
31
32
33 private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING + 1;
34
35 public ObjectToOutputHandler()
36 {
37 registerSourceType(byte[].class);
38 registerSourceType(String.class);
39 registerSourceType(InputStream.class);
40 registerSourceType(Serializable.class);
41 setReturnClass(OutputHandler.class);
42 }
43
44 public Object doTransform(final Object src, final String encoding) throws TransformerException
45 {
46 if (src instanceof String)
47 {
48 return new OutputHandler()
49 {
50 public void write(MuleEvent event, OutputStream out) throws IOException
51 {
52 out.write(((String) src).getBytes(encoding));
53 }
54 };
55 }
56 else if (src instanceof byte[])
57 {
58 return new OutputHandler()
59 {
60 public void write(MuleEvent event, OutputStream out) throws IOException
61 {
62 out.write((byte[]) src);
63 }
64 };
65 }
66 else if (src instanceof InputStream)
67 {
68 return new OutputHandler()
69 {
70 public void write(MuleEvent event, OutputStream out) throws IOException
71 {
72 InputStream is = (InputStream) src;
73 try
74 {
75 IOUtils.copyLarge(is, out);
76 }
77 finally
78 {
79 is.close();
80 }
81 }
82 };
83 }
84 else if (src instanceof Serializable)
85 {
86 return new OutputHandler()
87 {
88 public void write(MuleEvent event, OutputStream out) throws IOException
89 {
90 SerializationUtils.serialize((Serializable) src, out);
91 }
92 };
93 }
94 else
95 {
96 throw new TransformerException(MessageFactory
97 .createStaticMessage("Unable to convert " + src.getClass() + " to OutputHandler."));
98 }
99 }
100
101 public int getPriorityWeighting()
102 {
103 return priorityWeighting;
104 }
105
106 public void setPriorityWeighting(int priorityWeighting)
107 {
108 this.priorityWeighting = priorityWeighting;
109 }
110 }