View Javadoc

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