KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > tcp > protocols > EOFProtocol


1 /*
2  * $Id: EOFProtocol.java 3798 2006-11-04 04:07:14Z aperepel $
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 MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.tcp.protocols;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.mule.providers.tcp.TcpProtocol;
16
17 import org.apache.commons.io.output.ByteArrayOutputStream;
18 import java.io.IOException JavaDoc;
19 import java.io.InputStream JavaDoc;
20 import java.io.OutputStream JavaDoc;
21 import java.net.SocketException JavaDoc;
22 import java.net.SocketTimeoutException JavaDoc;
23
24 /**
25  * The EOFProtocol class is an application level tcp protocol that does nothing.
26  * Reading is terminated by the stream being closed by the client
27  *
28  * @author <a HREF="mailto:ross.mason@symphonysoft.com">Ross Mason</a>
29  * @version $Revision: 3798 $
30  */

31 public class EOFProtocol implements TcpProtocol
32 {
33
34     private static final int BUFFER_SIZE = 8192;
35
36     private static final Log logger = LogFactory.getLog(EOFProtocol.class);
37
38     public byte[] read(InputStream JavaDoc is) throws IOException JavaDoc
39     {
40         ByteArrayOutputStream baos = new ByteArrayOutputStream(EOFProtocol.BUFFER_SIZE);
41
42         byte[] buffer = new byte[EOFProtocol.BUFFER_SIZE];
43         int len = 0;
44         try
45         {
46             while ((len = is.read(buffer)) == 0)
47             {
48                 // wait
49
}
50         }
51         catch (SocketException JavaDoc e)
52         {
53             // do not pollute the log with a stacktrace, log only the message
54
EOFProtocol.logger.debug("Socket exception occured: " + e.getMessage());
55             return null;
56         }
57         catch (SocketTimeoutException JavaDoc e)
58         {
59             EOFProtocol.logger.debug("Socket timeout, returning null.");
60             return null;
61         }
62         if (len == -1)
63         {
64             return null;
65         }
66         else
67         {
68             do
69             {
70                 baos.write(buffer, 0, len);
71             }
72             while ((len = is.read(buffer)) >= 0);
73
74             baos.flush();
75             baos.close();
76             return baos.toByteArray();
77         }
78     }
79
80     public void write(OutputStream os, byte[] data) throws IOException JavaDoc
81     {
82         os.write(data);
83     }
84
85 }
86
Popular Tags