001package io.ebean.enhance.entity;
002
003import io.ebean.enhance.common.ClassBytesReader;
004import io.ebean.enhance.common.InputStreamTransform;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.net.URL;
009import java.net.URLClassLoader;
010
011/**
012 * Implementation of ClassBytesReader based on URLClassLoader.
013 */
014public class ClassPathClassBytesReader implements ClassBytesReader {
015        
016
017        private final URL[] urls;
018
019        public ClassPathClassBytesReader(URL[] urls) {
020                this.urls = urls == null ? new URL[0]: urls;
021        }
022        
023        public byte[] getClassBytes(String className, ClassLoader classLoader) {
024
025                try (URLClassLoader cl = new URLClassLoader(urls, classLoader)) {
026
027                        InputStream is = null;
028                        try {
029
030                                String resource = className.replace('.', '/') + ".class";
031                                
032                                // read the class bytes, and define the class
033                                URL url = cl.getResource(resource);
034                                if (url == null) {
035                                        return null;
036                                }
037
038                                is = url.openStream();
039                                return InputStreamTransform.readBytes(is);
040
041                        } catch (IOException e){
042                                throw new RuntimeException("IOException reading bytes for "+className, e);
043
044                        } finally {
045                                if (is != null){
046                                        try {
047                                                is.close();
048                                        } catch (IOException e) {
049                                                throw new RuntimeException("Error closing InputStream for "+className, e);
050                                        }
051                                }
052                        }
053                } catch (IOException e) {
054                        throw new RuntimeException("Error closing URLClassLoader for "+className, e);
055                }
056        }
057        
058}