/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/


package sun.awt.im.iiimp;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.jar.*;
import java.security.*;
import javax.swing.ImageIcon;

public class ODClassLoader extends SecureClassLoader {


    private HashMap byteTable = new HashMap();

    ODClassLoader() {
	super(ClassLoader.getSystemClassLoader());
    }

    void addJar(JarInputStream jis) {
	JarEntry je;
	boolean defc;
	
	for (;;) {
	    try {
		je = jis.getNextJarEntry();
	    } catch(Exception e) {
		continue;
	    }
	    
	    if (je == null) {
		break;
	    }

	    String name = je.getName();
	    //
	    // should use ByteArrayOutputStream and getByteArray()!!!
	    //
	    byte[] buf = new byte[1024];
	    int bufLen = 2048;
	    byte[] buffer = new byte[bufLen];
	    int total = 0, len;
	    try {
		for (;(len = jis.read(buf, 0, buf.length)) != -1;) {
		    if (bufLen < total + len) {
			byte[] tmp = new byte[bufLen * 2];
			System.arraycopy(buffer, 0, tmp, 0, total);
			buffer = tmp;
			bufLen *= 2;
		    }
		    System.arraycopy(buf, 0, buffer, total, len);
		    total += len;
		}
	    } catch(Exception e) {
		if (Manager.DEBUG) {
		    e.printStackTrace();
		}
		continue;
	    }
	    //
	    // store byte array for findClass() of ODClassLoader
	    //
	    byte[] realBuf = new byte[total];
	    System.arraycopy(buffer, 0, realBuf, 0, total);
	    byteTable.put(name, realBuf);
	}
    }

    /**
     * findClass from class byte array strage made from JarInputStream.
     */
    public Class findClass(String name) {
	
	byte[] ba = (byte[])byteTable.get(name.replace('.', '/') + ".class");

	if (ba == null) {
	    debug(" ODClassLoader: Unknown class " + name);
	    return null;
	}
	Class cls = null;
	try {
	    // CodeSource object will be added later.
	    //
	    cls = defineClass(name, ba, 0, ba.length, (CodeSource)null);
	} catch(Throwable e) {
	    debug(" E = " + e);
	    return null;
	}

	return cls;
    }

    public ImageIcon getImageIcon(String name) {

	byte[] ba = (byte[])byteTable.get(name);
	if (ba == null) {
	    debug(" ODClassLoader: " + name + " not found.");
	    return null;
	}

	return new ImageIcon(ba);
    }

    public String getString(String name) {

	byte[] ba = (byte[])byteTable.get(name);
	if (ba == null) {
	    debug(" ODClassLoader: " + name + " not found.");
	    return null;
	}
	String ret = null;
	try {
	    ret = new String(ba, "UTF-8");
	} catch(Exception e) {
	    if (Manager.DEBUG) {
		e.printStackTrace();
	    }
	}

	return ret;
    }

    

    public URL getURL(String name) {

	byte[] ba = (byte[])byteTable.get(name);

	if (ba == null) {
	    debug(" ODClassLoader: " + name + " not found.");
	}
	URL url = null;
	String anchor = null;
	try {
	    File f = File.createTempFile("iiim", "iiim");
	    String tempName = f.getAbsolutePath();
	    f.delete();
	    f = new File(tempName);
	    f.mkdir();

	    int anchorID = name.indexOf('#');
	    if (anchorID > 0) {
		anchor = name.substring(anchorID);
		name = name.substring(0, anchorID);
	    }

	    int fileid = name.lastIndexOf("/");
	    String dirname = name.substring(0, fileid);
	    Object[] writeList = getWriteList(dirname);

	    for (int i = 0; i < writeList.length; i++) { 
		String filename = ((String)writeList[i]).substring
		    (fileid, ((String)writeList[i]).length());
		if (filename.equals("") || filename.equals("/")) {
		    continue;
		}
		File f2 = new File(f, filename);
		byte[] ba2 = (byte[])byteTable.get((String)writeList[i]);
		if (ba2 == null) {
		    continue;
		}
		FileOutputStream fos = new FileOutputStream(f2);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		bos.write(ba2);
		bos.close();
		if (name.equals((String)writeList[i])) {
		    url = f2.toURL();
		    if (anchor != null) {
			String s = url.toExternalForm();
			url = new URL(s + anchor);
		    }
		}
	    }
	} catch(Exception e) {
	    debug(" getURL faied");
	}

	return url;
    }

    private Object[] getWriteList(String dirname) {
	HashSet strSet = new HashSet();
	Iterator iterator = byteTable.keySet().iterator();
	for (; iterator.hasNext();) {
	    String key = (String)iterator.next();
	    if (key.startsWith(dirname)) {
		strSet.add(key);
	    }
	}

	return strSet.toArray();
    }
	
    private void debug(String str) {
	if (Manager.DEBUG) {
	    System.err.println(str);
	}
    }
}
