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