001package io.ebean.enhance.entity;
002
003import java.io.ByteArrayOutputStream;
004import java.io.File;
005import java.io.IOException;
006import java.io.InputStream;
007import java.net.URL;
008import java.net.URLClassLoader;
009
010/**
011 * This class loader is used to load any classes (typically super classes)
012 * during enhancement process (avoiding the application class loaders).
013 */
014public class LocalClassLoader extends URLClassLoader {
015
016        public LocalClassLoader(URL[] urls, ClassLoader loader) {
017                super(urls, loader);
018        }
019
020        protected synchronized Class<?> loadClass(String name, boolean resolve)
021                        throws ClassNotFoundException {
022                
023                if (name.startsWith("java.")) {
024                        // we cannot reload these classes due to security constraints
025                        return super.loadClass(name, resolve);
026                }
027                Class<?> c = super.findLoadedClass(name);
028                if (c != null) {
029                        return c;
030                }
031                String resource = name.replace('.', '/') + ".class";
032
033                
034                try {
035                        // read the class bytes, and define the class
036                        URL url = super.getResource(resource);
037                        if (url == null) {
038                                throw new ClassNotFoundException(name);
039                        }
040                        
041                        File f = new File("build/bin/"+resource);
042                        System.out.println("FileLen:"+f.length()+"  "+f.getName());
043                        
044                        try (InputStream is = url.openStream()) {
045                                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
046                                        byte[] b = new byte[2048];
047
048                                        int count;
049                                        while ((count = is.read(b, 0, 2048)) != -1) {
050                                                os.write(b, 0, count);
051                                        }
052                                        byte[] bytes = os.toByteArray();
053
054                                        System.err.println("bytes: "+bytes.length+" "+resource);
055                                        return defineClass(name, bytes, 0, bytes.length);
056                                }
057                        }
058                } catch (SecurityException e) {
059                        return super.loadClass(name, resolve);
060                } catch (IOException e) {
061                        throw new ClassNotFoundException(name, e);
062                }
063        }
064
065}