package tropo.applet;

import java.util.*;
import java.applet.*;

/**
 * We preload java class files for use by a subsequent applet -
 * if properly configured and if everything works as planned
 * then the class files needed will be cached after we run as
 * we load in class descriptors.
 *
 * <p>
 *
 * We only take one parameter: <code>classes</code>, and the
 * value is a comma-separated list of fully qualified class names
 * to load.
 *
 * @see Class#forName
 */
public class TRPreloaderApplet
    extends Applet
    implements Runnable
{
    /**
	 *
	 */
	public TRPreloaderApplet()
	{
		// empty ctr needed by browser
	}

	/**
	 *
	 */
	public void start()
	{
		// get the only parameter we take - 'classes'
		// it's a comma-separated list of fully qualified class names
		String s = getParameter( "classes");

		// partially parse
		st = new StringTokenizer( s, ",");
		nTokens = st.countTokens();

		// kick of subthread
		t = new Thread( this);
		t.setDaemon( true);
		t.start();
	}

	/**
	 * Try to be a good citizen and cleanup.
	 */
	public void stop()
	{
		if ( t != null)
		{
			t.stop();
			t = null;
		}
	}

	/**
	 * Subthread that loads classes.
	 */
	public void run()
	{
		// load every class
		for ( int i = 0; i < nTokens; i++)
		{
			// get next class
			String curClassName = st.nextToken();
			// make sure it does not end in .class
			if ( curClassName.endsWith( ".class"))
				curClassName = curClassName.substring( 0,
												   curClassName.length() - 6);
			
			try
			{
				// load class descriptor which should go into browser
				// and proxy class
				Class.forName( curClassName);
			}
			catch( Exception e)
			{
				// if something fails complain and continue
				System.err.println( "ERROR: " + e);
			}
		}
		t = null; // remove thread ref - slight timing race w/ stop()
	}

	private StringTokenizer st;
	private int nTokens;
	private Thread t;
}

