001package io.ebean.enhance.common; 002 003import io.ebean.enhance.Transformer; 004 005import java.io.BufferedInputStream; 006import java.io.BufferedOutputStream; 007import java.io.ByteArrayInputStream; 008import java.io.ByteArrayOutputStream; 009import java.io.File; 010import java.io.FileInputStream; 011import java.io.FileNotFoundException; 012import java.io.FileOutputStream; 013import java.io.IOException; 014import java.io.InputStream; 015import java.io.OutputStream; 016import java.lang.instrument.IllegalClassFormatException; 017 018 019/** 020 * Utility object that handles input streams for reading and writing. 021 */ 022public class InputStreamTransform { 023 024 private final Transformer transformer; 025 private final ClassLoader classLoader; 026 027 public InputStreamTransform(Transformer transformer, ClassLoader classLoader){ 028 this.transformer = transformer; 029 this.classLoader = classLoader; 030 } 031 032 public void log(int level, String msg) { 033 transformer.log(level, msg); 034 } 035 036 /** 037 * Transform a file. 038 */ 039 public byte[] transform(String className, File file) throws IOException, IllegalClassFormatException { 040 try { 041 return transform(className, new FileInputStream(file)); 042 } catch (FileNotFoundException e){ 043 throw new RuntimeException(e); 044 } 045 } 046 047 /** 048 * Transform a input stream. 049 */ 050 public byte[] transform(String className, InputStream is) throws IOException, IllegalClassFormatException { 051 try { 052 byte[] classBytes = readBytes(is); 053 return transformer.transform(classLoader, className, null, null, classBytes); 054 } finally { 055 if (is != null){ 056 is.close(); 057 } 058 } 059 } 060 061 /** 062 * Helper method to write bytes to a file. 063 */ 064 public static void writeBytes(byte[] bytes, File file) throws IOException { 065 try (final FileOutputStream fos = new FileOutputStream(file)) { 066 writeBytes(bytes, fos); 067 } 068 } 069 070 /** 071 * Helper method to write bytes to a OutputStream. 072 */ 073 public static void writeBytes(byte[] bytes, OutputStream os) throws IOException { 074 try (BufferedOutputStream bos = new BufferedOutputStream(os)) { 075 try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) { 076 byte[] buf = new byte[1028]; 077 078 int len; 079 while ((len = bis.read(buf, 0, buf.length)) > -1){ 080 bos.write(buf, 0, len); 081 } 082 } 083 } 084 } 085 086 087 public static byte[] readBytes(InputStream is) throws IOException { 088 try (BufferedInputStream bis = new BufferedInputStream(is)) { 089 try (ByteArrayOutputStream baos = new ByteArrayOutputStream(4096)) { 090 byte[] buf = new byte[1028]; 091 092 int len; 093 while ((len = bis.read(buf, 0, buf.length)) > -1){ 094 baos.write(buf, 0, len); 095 } 096 return baos.toByteArray(); 097 } 098 } 099 } 100}