1
2
3
4
5
6
7 package org.mule.transformer.simple;
8
9 import org.mule.RequestContext;
10 import org.mule.api.transformer.TransformerException;
11 import org.mule.api.transport.OutputHandler;
12 import org.mule.transformer.types.DataTypeFactory;
13 import org.mule.util.IOUtils;
14
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18
19
20
21
22
23
24 public class ObjectToByteArray extends SerializableToByteArray
25 {
26 public ObjectToByteArray()
27 {
28 this.registerSourceType(DataTypeFactory.INPUT_STREAM);
29 this.registerSourceType(DataTypeFactory.STRING);
30 this.registerSourceType(DataTypeFactory.create(OutputHandler.class));
31 setReturnDataType(DataTypeFactory.BYTE_ARRAY);
32 }
33
34 @Override
35 public Object doTransform(Object src, String outputEncoding) throws TransformerException
36 {
37 try
38 {
39 if (src instanceof String)
40 {
41 return src.toString().getBytes(outputEncoding);
42 }
43 else if (src instanceof InputStream)
44 {
45 InputStream is = (InputStream) src;
46 ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
47 try
48 {
49 IOUtils.copyLarge(is, byteOut);
50 }
51 finally
52 {
53 is.close();
54 }
55 return byteOut.toByteArray();
56 }
57 else if (src instanceof OutputHandler)
58 {
59 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
60
61 try
62 {
63 ((OutputHandler) src).write(RequestContext.getEvent(), bytes);
64
65 return bytes.toByteArray();
66 }
67 catch (IOException e)
68 {
69 throw new TransformerException(this, e);
70 }
71 }
72 }
73 catch (Exception e)
74 {
75 throw new TransformerException(this, e);
76 }
77
78 return super.doTransform(src, outputEncoding);
79 }
80 }