package com.quantum.util; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.sql.Driver; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author BC Holmes */ public class JarUtil { private static Hashtable classLoaderCache = new Hashtable(); public static Driver loadDriver(String driverFile, String className) { Driver result = null; try { Class driverClass = loadDriverClass(driverFile, className); if (driverClass != null) { try { result = (Driver) driverClass.newInstance(); } catch (ClassCastException e) { } } } catch (InstantiationException e) { } catch (IllegalAccessException e) { } return result; } public static Class loadDriverClass(String driverFile, String className) { Class result = null; if (driverFile != null && className != null) { try { File file = new File(driverFile); if (file.exists() && file.isFile()) { URLClassLoader loader = getURLClassLoader(file); Class driverClass = loader.loadClass(className); result = Driver.class.isAssignableFrom(driverClass) ? driverClass : null; } } catch (MalformedURLException e) { } catch (ClassNotFoundException e) { } } return result; } public static String[] getAllDriverNames(String driverFile) { List list = new ArrayList(); try { File file = new File(driverFile); URLClassLoader loader = getURLClassLoader(file); JarFile jar = new JarFile(file); for (Enumeration e = jar.entries(); e.hasMoreElements(); ) { JarEntry entry = (JarEntry) e.nextElement(); String className = getClassNameFromFileName(entry.getName()); if (className != null) { try { Class driverClass = loader.loadClass(className); if (Driver.class.isAssignableFrom(driverClass)) { list.add(className); } } catch (ClassNotFoundException ex) { } } } } catch (IOException e) { } return (String[]) list.toArray(new String[list.size()]); } private static String getClassNameFromFileName(String name) { String result = null; if (name.endsWith(".class")) { result = name.substring(0, name.length()-6).replace('/', '.').replace('\\', '.' ); } return result; } /** * @param file * @return * @throws MalformedURLException */ private static URLClassLoader getURLClassLoader(File file) throws MalformedURLException { String driverFile = file.getAbsolutePath(); URLClassLoader loader = (URLClassLoader) classLoaderCache.get(driverFile); if (loader == null) { URL urls[] = new URL[1]; urls[0] = file.toURL(); loader = new URLClassLoader(urls); classLoaderCache.put(driverFile, loader); } return loader; } }