1 package com.quantum.util;
4 import java.io.IOException;
5 import java.net.MalformedURLException;
7 import java.net.URLClassLoader;
8 import java.sql.Driver;
9 import java.util.ArrayList;
10 import java.util.Enumeration;
11 import java.util.Hashtable;
12 import java.util.List;
13 import java.util.jar.JarEntry;
14 import java.util.jar.JarFile;
20 public class JarUtil {
22 private static Hashtable classLoaderCache = new Hashtable();
24 public static Driver loadDriver(String driverFile, String className) {
27 Class driverClass = loadDriverClass(driverFile, className);
28 if (driverClass != null) {
30 result = (Driver) driverClass.newInstance();
31 } catch (ClassCastException e) {
34 } catch (InstantiationException e) {
35 } catch (IllegalAccessException e) {
40 public static Class loadDriverClass(String driverFile, String className) {
42 if (driverFile != null && className != null) {
44 File file = new File(driverFile);
45 if (file.exists() && file.isFile()) {
46 URLClassLoader loader = getURLClassLoader(file);
47 Class driverClass = loader.loadClass(className);
48 result = Driver.class.isAssignableFrom(driverClass) ? driverClass : null;
50 } catch (MalformedURLException e) {
51 } catch (ClassNotFoundException e) {
57 public static String[] getAllDriverNames(String driverFile) {
58 List list = new ArrayList();
60 File file = new File(driverFile);
61 URLClassLoader loader = getURLClassLoader(file);
62 JarFile jar = new JarFile(file);
63 for (Enumeration e = jar.entries(); e.hasMoreElements(); ) {
64 JarEntry entry = (JarEntry) e.nextElement();
65 String className = getClassNameFromFileName(entry.getName());
66 if (className != null) {
68 Class driverClass = loader.loadClass(className);
69 if (Driver.class.isAssignableFrom(driverClass)) {
72 } catch (ClassNotFoundException ex) {
76 } catch (IOException e) {
78 return (String[]) list.toArray(new String[list.size()]);
81 private static String getClassNameFromFileName(String name) {
83 if (name.endsWith(".class")) {
84 result = name.substring(0, name.length()-6).replace('/', '.').replace('\\', '.' );
92 * @throws MalformedURLException
94 private static URLClassLoader getURLClassLoader(File file) throws MalformedURLException {
95 String driverFile = file.getAbsolutePath();
96 URLClassLoader loader =
97 (URLClassLoader) classLoaderCache.get(driverFile);
99 URL urls[] = new URL[1];
100 urls[0] = file.toURL();
101 loader = new URLClassLoader(urls);
102 classLoaderCache.put(driverFile, loader);