00001 package gov.nasa.arc.ase.util;
00002
00003
00004
00005
00006 import java.io.*;
00007 import java.net.*;
00008 import java.util.*;
00009
00010 public class FileClassLoader extends ClassLoader {
00011
00012 private String root;
00013 public static FileClassLoader v = new FileClassLoader();
00014
00015
00016 private FileClassLoader() {
00017
00018
00019 root = null;
00020 }
00021 public FileClassLoader (String rootDir) {
00022 if (rootDir == null)
00023 throw new IllegalArgumentException ("Null root directory");
00024 root = rootDir;
00025 }
00026 public static Class load(String name) throws ClassNotFoundException {
00027 return v.loadClass(name);
00028 }
00029 protected Class loadClass (String name, boolean resolve)
00030 throws ClassNotFoundException {
00031
00032
00033
00034
00035
00036 Class c = findLoadedClass (name);
00037 if (c == null) {
00038 try {
00039 c = findSystemClass (name);
00040 } catch (Exception e) {
00041
00042 }
00043 }
00044
00045 if (c == null) {
00046
00047
00048 String filename = name.replace ('.', File.separatorChar) + ".class";
00049 try {
00050
00051 byte data[] = loadClassData(filename);
00052
00053
00054 c = defineClass (name, data, 0, data.length);
00055
00056
00057 if (c == null) throw new ClassNotFoundException (name);
00058 } catch (IOException e) {
00059 throw new ClassNotFoundException ("Error reading file: " + filename);
00060 }
00061 }
00062
00063
00064 if (resolve) resolveClass (c);
00065
00066
00067 return c ;
00068 }
00069 private byte[] loadClassData (String filename) throws IOException {
00070
00071 File f = null;
00072
00073 if (root == null) {
00074
00075 String classPath = System.getProperty("java.class.path");
00076 StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
00077 boolean found = false;
00078
00079 while (tok.hasMoreTokens()) {
00080 f = new File(tok.nextToken(), filename);
00081 if (f.exists()) { found = true; break; }
00082 }
00083 if (!found)
00084 throw new IOException(filename+
00085 " cannot be found in class path: "+classPath);
00086 } else
00087 f = new File (root, filename);
00088
00089
00090 int size = (int)f.length();
00091
00092
00093 byte buff[] = new byte[size];
00094
00095
00096 FileInputStream fis = new FileInputStream(f);
00097 DataInputStream dis = new DataInputStream (fis);
00098
00099
00100 dis.readFully (buff);
00101
00102
00103 dis.close();
00104
00105
00106 return buff;
00107 }
00108 public void setRootDirectory(String r) {
00109 if (r != null) root = r;
00110 }
00111 }