1 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 ; 19 import java.io.InputStream ; 20 import java.io.OutputStream ; 21 import java.net.SocketException ; 22 import java.net.SocketTimeoutException ; 23 24 32 public class DefaultProtocol implements TcpProtocol 33 { 34 35 private static final int BUFFER_SIZE = 8192; 36 37 private static final Log logger = LogFactory.getLog(DefaultProtocol.class); 38 39 public byte[] read(InputStream is) throws IOException 40 { 41 ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); 42 43 byte[] buffer = new byte[BUFFER_SIZE]; 44 int len = 0; 45 try 46 { 47 while ((len = is.read(buffer)) == 0) 48 { 49 } 51 } 52 catch (SocketException e) 53 { 54 logger.debug("Socket exception occured: " + e.getMessage()); 56 return null; 57 } 58 catch (SocketTimeoutException e) 59 { 60 logger.debug("Socket timeout, returning null."); 61 return null; 62 } 63 if (len == -1) 64 { 65 return null; 66 } 67 else 68 { 69 do 70 { 71 baos.write(buffer, 0, len); 72 if (len < buffer.length) 73 { 74 break; 75 } 76 int av = is.available(); 77 if (av == 0) 78 { 79 break; 80 } 81 } 82 while ((len = is.read(buffer)) > 0); 83 84 baos.flush(); 85 baos.close(); 86 return baos.toByteArray(); 87 } 88 } 89 90 public void write(OutputStream os, byte[] data) throws IOException 91 { 92 os.write(data); 93 } 94 95 } 96 | Popular Tags |