View Javadoc

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