package osa.attribute.atgrammar.grammar.symbols;

import java.io.*;

class FunkyClassLoader
  extends java.lang.ClassLoader
  {
  protected String class_path="";

  public void setClassPath(String class_path)
    {
    this.class_path=class_path;
    }


  public synchronized Class loadClass(String name)
    throws ClassNotFoundException
    {
     System.out.println(name);
     System.out.println("in FunkyClassLoader.loadClass()");
     Class c = null;
     c = findLoadedClass(name);
     if(c!=null)
       {
       return c;
       }

     byte data[] = loadClassData(name);

     try
       {
       c = defineClass(null,data, 0, data.length);
       resolveClass(c);
       }
     catch(Throwable e)
          {
          try
            {
            c=findSystemClass(name);
            if(c!=null)
              {
              return c;
              }
            }
          catch(Exception ex)
               {
               ex.printStackTrace();
               }
          }

     if(c==null)
       {
       throw new ClassNotFoundException(name);
       }
     System.out.println("successfully defined class");
     return c;
     }

  private byte[] loadClassData(String name)
    throws ClassNotFoundException
    {
    byte[] buf = null;
    File f = new File(class_path+name+".class");
    if (!f.exists())
       {
       System.err.println("file does not exists!");
       return null;
       }
    try{
       InputStream in = new BufferedInputStream(new FileInputStream(class_path+name+".class"));
       buf = new byte[in.available()];
       in.read(buf);
       }
    catch(Exception e)
       {
       e.printStackTrace();
       throw new ClassNotFoundException(name);
       }
    return buf;
    }
}
