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 | 0 | { |
32 | 0 | this.registerSourceType(DataTypeFactory.INPUT_STREAM); |
33 | 0 | this.registerSourceType(DataTypeFactory.STRING); |
34 | 0 | this.registerSourceType(DataTypeFactory.create(OutputHandler.class)); |
35 | 0 | setReturnDataType(DataTypeFactory.BYTE_ARRAY); |
36 | 0 | } |
37 | |
|
38 | |
@Override |
39 | |
public Object doTransform(Object src, String outputEncoding) throws TransformerException |
40 | |
{ |
41 | |
try |
42 | |
{ |
43 | 0 | if (src instanceof String) |
44 | |
{ |
45 | 0 | return src.toString().getBytes(outputEncoding); |
46 | |
} |
47 | 0 | else if (src instanceof InputStream) |
48 | |
{ |
49 | 0 | InputStream is = (InputStream) src; |
50 | 0 | ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); |
51 | |
try |
52 | |
{ |
53 | 0 | IOUtils.copyLarge(is, byteOut); |
54 | |
} |
55 | |
finally |
56 | |
{ |
57 | 0 | is.close(); |
58 | 0 | } |
59 | 0 | return byteOut.toByteArray(); |
60 | |
} |
61 | 0 | else if (src instanceof OutputHandler) |
62 | |
{ |
63 | 0 | ByteArrayOutputStream bytes = new ByteArrayOutputStream(); |
64 | |
|
65 | |
try |
66 | |
{ |
67 | 0 | ((OutputHandler) src).write(RequestContext.getEvent(), bytes); |
68 | |
|
69 | 0 | return bytes.toByteArray(); |
70 | |
} |
71 | 0 | catch (IOException e) |
72 | |
{ |
73 | 0 | throw new TransformerException(this, e); |
74 | |
} |
75 | |
} |
76 | |
} |
77 | 0 | catch (Exception e) |
78 | |
{ |
79 | 0 | throw new TransformerException(this, e); |
80 | 0 | } |
81 | |
|
82 | 0 | return super.doTransform(src, outputEncoding); |
83 | |
} |
84 | |
} |