package org.plenix.jsp.language.java;

import  java.io.*;
import  java.util.*;

import org.plenix.jsp.*;

public class JspClassLoader extends ClassLoader
{
  private File stageDirectory;
  private Hashtable classCache;

  public JspClassLoader(File stageDirectory)
  {
    this.stageDirectory = stageDirectory;
    this.classCache = new Hashtable();
  }

  protected Class loadClass(String className, boolean resolve)
    throws ClassNotFoundException
  {
    Class c = (Class) classCache.get(className);

    if(c == null)
    {
      byte[] classData = loadClassData(className);

      if(classData != null)
      {
        c = defineClass(className, classData, 0, classData.length);
      } else
      {
        c = findSystemClass(className);

        if(c == null)
        {
          return null;
        }
      }

      classCache.put(className, c);
    }

    if(resolve)
    {
      resolveClass(c);
    }

    return c;
  }

  private byte[] loadClassData(String className)
  {
    File classFile;
    byte[] classData;
    DataInputStream in;

    classFile = new File(stageDirectory, className.replace('.', File.separatorChar) + ".class");

    try
    {
      in = new DataInputStream(new FileInputStream(classFile));

      try
      {
        classData = new byte[(int) classFile.length()];
        in.readFully(classData, 0, classData.length);

        return classData;
      } finally
      {
        in.close();
      }
    } catch(IOException e) { }

    return null;
  }
}
