1
2
3
4
5
6
7
8
9
10
11 package org.mule.transformer.simple;
12
13 import org.mule.RequestContext;
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.CoreMessages;
18 import org.mule.transformer.AbstractTransformer;
19 import org.mule.util.IOUtils;
20 import org.mule.util.StringMessageUtils;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.UnsupportedEncodingException;
26
27
28
29
30
31
32 public class ObjectToString extends AbstractTransformer implements DiscoverableTransformer
33 {
34 protected static final int DEFAULT_BUFFER_SIZE = 80;
35
36
37 private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING + 1;
38
39 public ObjectToString()
40 {
41 registerSourceType(Object.class);
42 registerSourceType(byte[].class);
43 registerSourceType(InputStream.class);
44 registerSourceType(OutputHandler.class);
45 setReturnClass(String.class);
46 }
47
48 public Object doTransform(Object src, String encoding) throws TransformerException
49 {
50 String output = "";
51
52 if (src instanceof InputStream)
53 {
54 InputStream is = (InputStream) src;
55 try
56 {
57 ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
58 IOUtils.copy(is, byteOut);
59 output = new String(byteOut.toByteArray(), encoding);
60 }
61 catch (IOException e)
62 {
63 throw new TransformerException(CoreMessages.errorReadingStream(), e);
64 }
65 finally
66 {
67 try
68 {
69 is.close();
70 }
71 catch (IOException e)
72 {
73 logger.warn("Could not close stream", e);
74 }
75 }
76 }
77 else if (src instanceof OutputHandler)
78 {
79 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
80
81 try
82 {
83 ((OutputHandler) src).write(RequestContext.getEvent(), bytes);
84
85 output = new String(bytes.toByteArray(), encoding);
86 }
87 catch (IOException e)
88 {
89 throw new TransformerException(this, e);
90 }
91
92
93 }
94 else if (src instanceof byte[])
95 {
96 try
97 {
98 output = new String((byte[]) src, encoding);
99 }
100 catch (UnsupportedEncodingException e)
101 {
102 throw new TransformerException(this, e);
103 }
104 }
105 else
106 {
107 output = StringMessageUtils.toString(src);
108 }
109
110 return output;
111 }
112
113 public int getPriorityWeighting()
114 {
115 return priorityWeighting;
116 }
117
118 public void setPriorityWeighting(int priorityWeighting)
119 {
120 this.priorityWeighting = priorityWeighting;
121 }
122 }