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

public class HttpRequestViewer {

    public static void sendNotFound( BufferedWriter out ) {
        PrintWriter pr = new PrintWriter( out );
        pr.println("HTTP/1.0 404 Not Found");
        pr.println("Connection: close");
        pr.println();
        pr.flush();
    }

    public static void sendReply( String path, BufferedWriter out ) {
        PrintWriter pr = new PrintWriter( out );
        pr.println("HTTP/1.0 200 OK");
        pr.println("Connection: close");
        pr.println("Content-Type: text/html");
        pr.println();
        pr.println("<html>");
        pr.println("<body>");
        pr.println("<pre>" + "path: " + path + "</pre>");
        pr.println("<pre>" + new Date() + "</pre>");
        pr.println("</body>");
        pr.println("</html>");
        pr.flush();
    }

    public static void main( String[] args ) {
        try {
            int port = Integer.parseInt( args[0] );
            ServerSocket listen = new ServerSocket( port );
	    System.out.println ("Accepting HTTP request from port: " + listen.getLocalPort());
            while ( true ) {
                Socket sock = listen.accept();
                BufferedReader rd = new BufferedReader(
                    new InputStreamReader( sock.getInputStream() ));
                BufferedWriter bw = new BufferedWriter(
                    new OutputStreamWriter( sock.getOutputStream() ));
                // get request
                String line = rd.readLine();
                if ( line == null ) {
                    sock.close();
                    continue;
                }
                String[] words = line.split("\\s+");
                System.out.println( line );
                do {
                    line = rd.readLine();
                    if ( line == null ) break;
                    System.out.println( line );
                } while ( line.length() > 0 );
                if ( words[1].equals("/favicon.ico") ) {
                    sendNotFound( bw );
                }
                else {
                    sendReply( words[1], bw );
                }
                rd.close();
                bw.close();
                sock.close();
            }
       }
       catch( IOException e ) {
           System.out.println("error: " + e );
       }
    }
}
