View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.tcp.protocols;
8   
9   import org.mule.DefaultMuleMessage;
10  import org.mule.RequestContext;
11  import org.mule.api.MuleException;
12  import org.mule.api.transformer.wire.WireFormat;
13  
14  import java.io.ByteArrayInputStream;
15  import java.io.ByteArrayOutputStream;
16  import java.io.IOException;
17  import java.io.InputStream;
18  
19  /**
20   * Helper class for Mule message handling so that we can apply the same logic across all
21   * sub-protocols (default, EOF and length).
22   */
23  class MuleMessageWorker
24  {
25  
26      private final WireFormat wireFormat;
27  
28      MuleMessageWorker(WireFormat wireFormat)
29      {
30          this.wireFormat = wireFormat;
31      }
32  
33      public byte[] doWrite() throws IOException
34      {
35          //TODO fix the api here so there is no need to use the RequestContext
36          DefaultMuleMessage msg = (DefaultMuleMessage) RequestContext.getEvent().getMessage();
37          ByteArrayOutputStream baos = new ByteArrayOutputStream();
38          try
39          {
40              wireFormat.write(baos, msg, msg.getEncoding());
41          }
42          catch (MuleException e)
43          {
44              throw new IOException(e.getDetailedMessage());
45          }
46          return baos.toByteArray();
47      }
48  
49      public Object doRead(Object message) throws IOException
50      {
51          if (message == null)
52          {
53              return null;
54          }
55  
56          InputStream in;
57          if (message instanceof byte[])
58          {
59              in = new ByteArrayInputStream((byte[]) message);
60          }
61          else
62          {
63              in = (InputStream) message;
64          }
65  
66          try
67          {
68              return wireFormat.read(in);
69          }
70          catch (MuleException e)
71          {
72              throw new IOException(e.getDetailedMessage());
73          }
74  
75      }
76  
77  }