View Javadoc

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