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.config.i18n.CoreMessages; |
15 | |
import org.mule.util.IOUtils; |
16 | |
|
17 | |
import java.io.IOException; |
18 | |
import java.io.InputStream; |
19 | |
import java.io.ObjectStreamConstants; |
20 | |
import java.io.PushbackInputStream; |
21 | |
import java.io.UnsupportedEncodingException; |
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | 42 | public class ByteArrayToObject extends ByteArrayToSerializable |
30 | |
{ |
31 | |
|
32 | |
|
33 | |
public Object doTransform(Object src, String encoding) throws TransformerException |
34 | |
{ |
35 | 26 | if (src instanceof byte[]) |
36 | |
{ |
37 | 22 | byte[] bytes = (byte[])src; |
38 | |
|
39 | 22 | if (this.checkStreamHeader(bytes[0])) |
40 | |
{ |
41 | 10 | return super.doTransform(src, encoding); |
42 | |
} |
43 | |
else |
44 | |
{ |
45 | |
try |
46 | |
{ |
47 | 12 | return new String(bytes, encoding); |
48 | |
} |
49 | 0 | catch (UnsupportedEncodingException e) |
50 | |
{ |
51 | 0 | throw new TransformerException(this, e); |
52 | |
} |
53 | |
} |
54 | |
} |
55 | 4 | else if (src instanceof InputStream) |
56 | |
{ |
57 | |
try |
58 | |
{ |
59 | 4 | PushbackInputStream pushbackStream = new PushbackInputStream((InputStream)src); |
60 | 4 | int firstByte = pushbackStream.read(); |
61 | 4 | pushbackStream.unread((byte)firstByte); |
62 | |
|
63 | 4 | if (this.checkStreamHeader((byte)firstByte)) |
64 | |
{ |
65 | 4 | return super.doTransform(pushbackStream, encoding); |
66 | |
} |
67 | |
else |
68 | |
{ |
69 | |
try |
70 | |
{ |
71 | 0 | return IOUtils.toString(pushbackStream, encoding); |
72 | |
} |
73 | |
finally |
74 | |
{ |
75 | |
|
76 | 0 | pushbackStream.close(); |
77 | |
} |
78 | |
} |
79 | |
} |
80 | 0 | catch (IOException iox) |
81 | |
{ |
82 | 0 | throw new TransformerException(this, iox); |
83 | |
} |
84 | |
} |
85 | |
else |
86 | |
{ |
87 | 0 | throw new TransformerException(CoreMessages.transformOnObjectUnsupportedTypeOfEndpoint( |
88 | |
this.getName(), src.getClass(), endpoint)); |
89 | |
} |
90 | |
} |
91 | |
|
92 | |
private boolean checkStreamHeader(byte firstByte) |
93 | |
{ |
94 | 26 | return (firstByte == (byte)((ObjectStreamConstants.STREAM_MAGIC >>> 8) & 0xFF)); |
95 | |
} |
96 | |
} |