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.transport.tcp.TcpInputStream;
10  import org.mule.transport.tcp.TcpProtocol;
11  
12  import java.io.IOException;
13  import java.io.InputStream;
14  import java.io.OutputStream;
15  
16  public class StreamingProtocol extends EOFProtocol implements TcpProtocol
17  {
18  
19      public StreamingProtocol()
20      {
21          super();
22      }
23  
24      public Object read(InputStream is) throws IOException
25      {
26          if (is instanceof TcpInputStream)
27          {
28              ((TcpInputStream) is).setStreaming(true);
29          }
30          
31          return is;
32      }
33  
34      /**
35       * 
36       * @param is
37       * @param os
38       * @throws IOException
39       */
40      protected void copyStream(InputStream is, OutputStream os) throws IOException
41      {
42          try
43          {
44              int limit = getLimit();
45              byte[] buffer = new byte[bufferSize];
46              int len;
47              int remain = remaining(limit, limit, 0);
48              int total = 0;
49              boolean repeat;
50              do
51              {
52                  len = copy(is, buffer, os, remain);
53                  total += len;
54                  remain = remaining(limit, remain, len);
55                  repeat = EOF != len && remain > 0 && isRepeat(len, is.available());
56                  
57                  // Flush the data if we didn't fill up the whole buffer
58                  // in case we're at the end of the stream and the receiving
59                  // side is waiting for the end of the data before closing the socket
60                  if (len > 0 && len < buffer.length)
61                  {
62                      os.flush();
63                  }
64              }
65              while (repeat);
66          }
67          finally
68          {
69              is.close();
70          }
71      }
72  
73      protected int getLimit()
74      {
75          return UNLIMITED;
76      }
77  
78  }
79  
80