/** * */ package at.gv.egiz.pdfas.impl.input.helper; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import at.gv.egiz.pdfas.performance.PerformanceCounters; import at.gv.egiz.pdfas.framework.input.DataSource; import at.gv.egiz.pdfas.framework.input.PdfDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author wprinz * */ public class DataSourceHelper { /** * The log. */ private static final Log log = LogFactory.getLog(DataSourceHelper.class); /** * Converts a PdfDataSource to a byte array. * *

* Note that this function is very memory intensive. Use the Streams whereever * possible. *

* * @deprecated * * @param pdfDataSource * @return * @throws IOException */ public static byte[] convertDataSourceToByteArray(DataSource pdfDataSource) { return pdfDataSource.getAsByteArray(); // try // { // PerformanceCounters.byteArrays.increment(); // // byte[] data = new byte[pdfDataSource.getLength()]; // // int bytes_written = 0; // // InputStream is = pdfDataSource.createInputStream(); // int n = 0; // while ((n = is.read(data, bytes_written, data.length - bytes_written)) > 0) // { // bytes_written += n; // } // is.close(); // // assert bytes_written == data.length; // // return data; // } // catch (IOException e) // { // log.error(e); // throw new RuntimeException(e); // } } public static byte [] convertInputStreamToByteArray(InputStream inputStream) { try { PerformanceCounters.byteArrays.increment(); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); byte[] temp = new byte[4096]; int n = 0; while ((n = inputStream.read(temp)) > 0) { baos.write(temp, 0, n); } inputStream.close(); baos.close(); byte [] data = baos.toByteArray(); return data; } catch (IOException e) { log.error(e); throw new RuntimeException(e); } } public static void debugDataSourceToFile(DataSource dataSource, File file) { try { InputStream is = dataSource.createInputStream(); FileOutputStream fos = new FileOutputStream(file); byte[] data = new byte[2048]; int n = -1; while ((n = is.read(data)) > 0) { fos.write(data, 0, n); } is.close(); fos.close(); } catch (IOException e) { log.error(e); } } }