Server Extension Example


// An example Server extension
//
// This just prints out who we are, and who is connecting
// 
// To use, compile the class and place it somewhere in your 
// CLASSPATH. Add a line:
// ClassExec /ServerInfo ServerInfo
// to your server configuration file, restart the server,
// and then the URL http://your.server/ServerInfo
// will cause this class to be run.

import uk.co.demon.cascade.http.*;

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

public class TestExtension implements HTTPServerExtension
{
    InputStream is;
    OutputStream os;
    HTTPInformation info;

    // init function sets up the environment class,
    // the input stream we can receive data on (for POST)
    // and the output stream we write our response to.

    public void init(HTTPInformation httpInfo, InputStream in, OutputStream out)
    {
	info = httpInfo;
	is = in;
	os = out;
    }


    // This is the method that does the work
    public void run()
    {
	try
	{
	    generateOutput();
	}
	catch (HTTPException e)
	{
	    // There was an error. Ignore it.
	}
    }
    

    // and all the rest are internal private methods...

    private void generateOutput() throws HTTPException
    {
	HTTPSystem.output(os, "Content-Type: text/html\n\n");
	HTTPSystem.output(os, "<html>\n");
	HTTPSystem.output(os, "<head>\n");
	HTTPSystem.output(os, "<title>Server Info</title>\n");
	HTTPSystem.output(os, "</head>\n");
	HTTPSystem.output(os, "<body>\n");
	HTTPSystem.output(os, "<h1>Server Info</h1>\n");

	printHostname();
	printConnectFrom();
	
	HTTPSystem.output(os, "</body>\n");
	HTTPSystem.output(os, "</html>\n");
    }

    private void printHostname() throws HTTPException
    {
	String hostName;
	Date today = new Date();
	
	try
	{
	    InetAddress localhost = InetAddress.getLocalHost();
	    hostName = localhost.toString();
	}
	catch (UnknownHostException e)
	{
	    hostName = "an unknown host";
	}

	HTTPSystem.output(os, "<p>Server information for " + hostName + 
			  " at " + today.toGMTString() + ".</p>\n");
    }

    private void printConnectFrom() throws HTTPException
    {
	String from;
	
	if (env.get(HTTPEnvironment.remoteHost) != null)
	{
	    from = env.get(HTTPEnvironment.remoteHost);
	}
	else
	{
	    if (env.get(HTTPEnvironment.remoteAddr) != null)
	    {
		from = env.get(HTTPEnvironment.remoteAddr);
	    }
	    else
	    {
		from = "somewhere";
	    }
	}
	HTTPSystem.output(os, "<p>You are connected from " + from + ".</p>\n");
    }
	
}