1 21 package com.jaspersoft.jasperserver.api.engine.jasperreports.util; 22 23 import java.io.IOException ; 24 import java.net.URL ; 25 import java.util.Enumeration ; 26 import java.util.Vector ; 27 import java.util.jar.JarEntry ; 28 import java.util.jar.JarFile ; 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 import com.jaspersoft.jasperserver.api.metadata.common.domain.util.StreamUtils; 34 35 39 public class JarsClassLoader extends ClassLoader { 40 private static final Log log = LogFactory.getLog(JarsClassLoader.class); 41 42 private final JarURLStreamHandler urlStreamHandler; 43 44 private final JarFile [] jars; 45 46 public JarsClassLoader(JarFile [] jars, ClassLoader parent) { 47 super(parent); 48 49 this.urlStreamHandler = new JarURLStreamHandler(); 50 this.jars = jars; 51 } 52 53 protected Class findClass(String name) throws ClassNotFoundException { 54 String path = name.replace('.', '/').concat(".class"); 55 56 JarFileEntry entry = findPath(path); 57 58 if (entry == null) { 59 throw new ClassNotFoundException (name); 60 } 61 62 64 byte[] classData; 65 try { 66 long size = entry.getSize(); 67 if (size >= 0) { 68 classData = StreamUtils.readData(entry.getInputStream(), 69 (int) size); 70 } else { 71 classData = StreamUtils.readData(entry.getInputStream()); 72 } 73 } catch (IOException e) { 74 log.debug(e, e); 75 throw new ClassNotFoundException (name, e); 76 } 77 78 return defineClass(name, classData, 0, classData.length, 79 JarsClassLoader.class.getProtectionDomain()); 80 } 81 82 protected JarFileEntry findPath(String path) { 83 JarFileEntry entry = null; 84 for (int i = 0; i < jars.length && entry == null; i++) { 85 entry = getJarEntry(jars[i], path); 86 } 87 return entry; 88 } 89 90 protected URL findResource(String name) { 91 JarFileEntry entry = findPath(name); 92 return entry == null ? null : urlStreamHandler.createURL(entry); 93 } 94 95 protected Enumeration findResources(String name) throws IOException { 96 Vector urls = new Vector (); 97 for (int i = 0; i < jars.length; i++) { 98 JarFileEntry entry = getJarEntry(jars[i], name); 99 if (entry != null) { 100 urls.add(urlStreamHandler.createURL(entry)); 101 } 102 } 103 return urls.elements(); 104 } 105 106 protected static JarFileEntry getJarEntry(JarFile jar, String name) { 107 if (name.startsWith("/")) { 108 name = name.substring(1); 109 } 110 111 JarFileEntry jarEntry = null; 112 JarEntry entry = jar.getJarEntry(name); 113 if (entry != null) { 114 jarEntry = new JarFileEntry(jar, entry); 115 } 116 117 return jarEntry; 118 } 119 } 120 | Popular Tags |