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