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