1 21 package com.jaspersoft.jasperserver.api.metadata.common.domain.util; 22 23 import java.io.ByteArrayOutputStream ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 import java.sql.Blob ; 27 import java.sql.SQLException ; 28 29 import org.apache.commons.logging.Log; 30 import org.apache.commons.logging.LogFactory; 31 32 import com.jaspersoft.jasperserver.api.JSException; 33 import com.jaspersoft.jasperserver.api.JSExceptionWrapper; 34 import com.jaspersoft.jasperserver.api.metadata.common.domain.FileResourceData; 35 36 40 public class StreamUtils { 41 private static final Log log = LogFactory.getLog(FileResourceData.class); 42 private static final int READ_STREAM_BUFFER_SIZE = 10000; 43 44 public static byte[] readData(InputStream is) { 45 if (is == null) { 46 return null; 47 } 48 49 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 50 51 byte[] bytes = new byte[READ_STREAM_BUFFER_SIZE]; 52 int ln = 0; 53 try { 54 while ((ln = is.read(bytes)) > 0) { 55 baos.write(bytes, 0, ln); 56 } 57 } catch (IOException e) { 58 log.error("Error while reading data.", e); 59 throw new JSExceptionWrapper(e); 60 } 61 62 return baos.toByteArray(); 63 } 64 65 public static byte[] readData(InputStream is, int size) { 66 if (is == null) { 67 return null; 68 } 69 70 try { 71 byte[] data = new byte[size]; 72 int offset = 0; 73 while (size > 0) { 74 int read = is.read(data, offset, size); 75 if (read < 0) { 76 throw new JSException("Input stream exhausted before reading " + size + " bytes"); 77 } 78 offset += read; 79 size -= read; 80 } 81 return data; 82 } catch (IOException e) { 83 log.error("Error while reading data.", e); 84 throw new JSExceptionWrapper(e); 85 } 86 } 87 88 public static byte[] readData(Blob blob) { 89 if (blob == null) { 90 return null; 91 } 92 93 try { 94 return readData(blob.getBinaryStream()); 95 } catch (SQLException e) { 96 log.error("Error while reading blob data", e); 97 throw new JSExceptionWrapper(e); 98 } 99 } 100 101 } 102 | Popular Tags |