package org.eclipse.tigerstripe.workbench.internal.core.plugin.pluggable; | |
import java.io.File; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.net.URLClassLoader; | |
import java.util.Enumeration; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.jar.JarEntry; | |
import java.util.jar.JarFile; | |
import org.eclipse.tigerstripe.workbench.TigerstripeException; | |
import org.eclipse.tigerstripe.workbench.internal.api.ITigerstripeRuntime; | |
@SuppressWarnings("deprecation") | |
public class JarInJarClassLoader extends URLClassLoader { | |
private ITigerstripeRuntime runtime; | |
public JarInJarClassLoader(ITigerstripeRuntime runtime, URL[] urls, ClassLoader parent) { | |
super(urls, parent); | |
this.runtime = runtime; | |
try { | |
for (URL url : urls) { | |
if (isJar(url.getFile())) { | |
addJarResource(new File(url.getPath())); | |
} | |
} | |
} catch (TigerstripeException e) { | |
runtime.logErrorMessage( | |
"Error adding Jar entries to classpath", | |
e); | |
} | |
} | |
private void addJarResource(File file) throws TigerstripeException { | |
try (JarFile jarFile = new JarFile(file)) { | |
addURL(file.toURL()); | |
Enumeration<JarEntry> jarEntries = jarFile.entries(); | |
while (jarEntries.hasMoreElements()) { | |
JarEntry jarEntry = jarEntries.nextElement(); | |
if (!jarEntry.isDirectory() && isJar(jarEntry.getName())) { | |
addJarResource(TigerstripeJarUtils.jarEntryAsFile(jarFile, jarEntry)); | |
} | |
} | |
} catch (IOException e) { | |
runtime.logErrorMessage("Error adding Jar resource to classpath", e); | |
} | |
} | |
@Override | |
protected Class<?> loadClass(String name, boolean resolve) | |
throws ClassNotFoundException { | |
synchronized (getClassLoadingLock(name)) { | |
try { | |
Class<?> clazz = findLoadedClass(name); | |
if (clazz == null) { | |
clazz = findClass(name); | |
} | |
if (resolve) { | |
resolveClass(clazz); | |
} | |
return clazz; | |
} catch (ClassNotFoundException e) { | |
return super.loadClass(name, resolve); | |
} | |
} | |
} | |
private static boolean isJar(String fileName) { | |
return fileName != null && (fileName.toLowerCase().endsWith(".jar")); | |
} | |
@Override | |
public void close() throws IOException { | |
this.runtime = null; | |
super.close(); | |
} | |
} |