/**
 * The RunURLConnection class provides for customized construction
 * of a specialized input stream, which contains synthesized contents.
 * 
 * Basically, it creates a synthetic HTML document containing an APPLET
 * tag referring to the applet that has passed in via the URL, and will
 * hand out an input stream that HotJava will treat like any other
 * URLConnection: it will examine the content type (in this case, text/html)
 * and perform the appropriate action (in this case, load it into the browser
 * as with all HTML pages).
 */

package COM.foo.protocol.run;

import java.net.URL;
import java.net.URLConnection;
import java.io.*;

class RunURLConnection extends URLConnection {
    /**
     * Our cached input stream -- this is what is handed out when
     * requested via getInputStream(), and produces the content of the
     * document.  Note that for the purposes of this example, we don't
     * deal with having multiple requests for input streams from a
     * given instance of this class.
     */
    InputStream is;

    RunURLConnection(URL u) {
	super(u);
    }

    /**
     * The connect method is the actual workhorse function.  It creates,
     * by writing to a PipedOutputStream, the HTML content that will be
     * read via the input stream "is" (which is connected to the other
     * side of the pipe).
     */
    public void connect() throws IOException {

	PipedOutputStream ps = new PipedOutputStream();
	is = new PipedInputStream(ps);
	PrintWriter pw = new PrintWriter(new OutputStreamWriter(ps));

	// Do some simple canonicalization of the applet class name
	// from the URL that was passed into the constructor.
	String className = url.getFile();
	String args;
	className = className.substring(className.lastIndexOf("/")+1);

	if (className.indexOf("?") != 0) {
	    className.replace(':', ' ');
	}

	// Create the content of the "page".   Allow 500x500 pixels
	// for the applet in case it's a large one.
	pw.println("<HTML>");
	pw.print("<TITLE> Running Class: ");
	pw.print(className);
	pw.println(" </TITLE>");
	pw.println("<BODY>");
	pw.print("<APPLET CODE=");
	pw.print(className);
	pw.println(" WIDTH=500 HEIGHT=500>");
	pw.println("</APPLET>\n</BODY>\n</HTML>\n");

	pw.close();

	// Record that we're now in the connected state, and we no longer
	// need to create the input stream.
	connected = true;
    }

    /**
     * Tell interested parties (like HotJava) what our content type is,
     * which in this case is HTML.
     */
    public String getContentType() {
      
	return "text/html";
    }


    /**
     * The "main" function -- this will be called by HotJava to get the
     * content of the URLConnection, in this case, our synthetic document.
     */
    public synchronized InputStream getInputStream()
	throws IOException
    {
	if (!connected) {
	    connect();
	}
	return is;
    }
}
