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.integration;
8   
9   import org.mule.transport.tcp.protocols.AbstractByteProtocol;
10  
11  import java.io.ByteArrayOutputStream;
12  import java.io.IOException;
13  import java.io.InputStream;
14  import java.io.OutputStream;
15  
16  public class CustomByteProtocol extends AbstractByteProtocol
17  {
18  
19      /**
20       * Create a CustomSerializationProtocol object.
21       */
22      public CustomByteProtocol()
23      {
24          super(false); // This protocol does not support streaming.
25      }
26  
27      /**
28       * Write the message's bytes to the socket, then terminate each message with '>>>'.
29       */
30      @Override
31      protected void writeByteArray(OutputStream os, byte[] data) throws IOException
32      {
33          super.writeByteArray(os, data);
34          os.write('>');
35          os.write('>');
36          os.write('>');
37          os.flush();
38      }
39  
40      /**
41       * Read bytes until we see '>>>', which ends the message
42       * */
43      public Object read(InputStream is) throws IOException
44      {
45          ByteArrayOutputStream baos = new ByteArrayOutputStream();
46          int count = 0;
47          byte read[] = new byte[1];
48  
49          while (true)
50          {
51              // if no bytes are currently avalable, safeRead() will wait until some arrive
52              if (safeRead(is, read) < 0)
53              {
54                  // We've reached EOF.  Return null, so that our caller will know there are no
55                  // remaining messages
56                  return null;
57              }
58              byte b = read[0];
59              if (b == '>')
60              {
61                  count++;
62                  if (count == 3)
63                  {
64                      return baos.toByteArray();
65                  }
66              }
67              else
68              {
69                  for (int i = 0; i < count; i++)
70                  {
71                      baos.write('>');
72                  }
73                  count = 0;
74                  baos.write(b);
75              }
76          }
77      }
78  }