1
2
3
4
5
6
7
8
9
10
11 package org.mule.transformer.simple;
12
13 import org.mule.api.transformer.TransformerException;
14 import org.mule.util.IOUtils;
15
16 import java.io.ByteArrayOutputStream;
17 import java.io.InputStream;
18
19
20
21
22
23
24 public class ObjectToByteArray extends SerializableToByteArray
25 {
26
27 public ObjectToByteArray()
28 {
29 this.registerSourceType(InputStream.class);
30 this.registerSourceType(String.class);
31 setReturnClass(byte[].class);
32 }
33
34
35 public Object doTransform(Object src, String encoding) throws TransformerException
36 {
37 try
38 {
39 if (src instanceof String)
40 {
41 return src.toString().getBytes(encoding);
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 }
58 catch (Exception e)
59 {
60 throw new TransformerException(this, e);
61 }
62
63 return super.doTransform(src, encoding);
64 }
65
66 }