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 043 } catch (FileNotFoundException e){ 044 throw new RuntimeException(e); 045 } 046 } 047 048 /** 049 * Transform a input stream. 050 */ 051 public byte[] transform(String className, InputStream is) throws IOException, IllegalClassFormatException { 052 053 try { 054 055 byte[] classBytes = readBytes(is); 056 057 return transformer.transform(classLoader, className, null, null, classBytes); 058 059 } finally { 060 if (is != null){ 061 is.close(); 062 } 063 } 064 } 065 066 /** 067 * Helper method to write bytes to a file. 068 */ 069 public static void writeBytes(byte[] bytes, File file) throws IOException { 070 try (final FileOutputStream fos = new FileOutputStream(file)) { 071 writeBytes(bytes, fos); 072 } 073 } 074 075 /** 076 * Helper method to write bytes to a OutputStream. 077 */ 078 public static void writeBytes(byte[] bytes, OutputStream os) throws IOException { 079 080 try (BufferedOutputStream bos = new BufferedOutputStream(os)) { 081 try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) { 082 byte[] buf = new byte[1028]; 083 084 int len; 085 while ((len = bis.read(buf, 0, buf.length)) > -1){ 086 bos.write(buf, 0, len); 087 } 088 } 089 } 090 } 091 092 093 public static byte[] readBytes(InputStream is) throws IOException { 094 095 try (BufferedInputStream bis = new BufferedInputStream(is)) { 096 try (ByteArrayOutputStream baos = new ByteArrayOutputStream(4096)) { 097 byte[] buf = new byte[1028]; 098 099 int len; 100 while ((len = bis.read(buf, 0, buf.length)) > -1){ 101 baos.write(buf, 0, len); 102 } 103 104 return baos.toByteArray(); 105 } 106 } 107 } 108}