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