/*
   https://media.pearsoncmg.com/aw/ecs_kurose_compnetwork_7/cw/content/medialib/previous3e/2_9.pdf#page=2
*/
import java.io.*;
import java.net.*;
import java.util.*;
class WebServer
{
   public static void main(String argv[]) throws Exception
   {
      final ServerSocket listenSocket = new ServerSocket(6789);
      final Socket connectionSocket = listenSocket.accept();
      final BufferedReader inFromClient = new BufferedReader(
                                             new InputStreamReader(
                                                connectionSocket.getInputStream()));
      final DataOutputStream outToClient = new DataOutputStream(
                                                connectionSocket.getOutputStream());
      final String requestMessageLine = inFromClient.readLine();
      final StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine);
      if (tokenizedLine.nextToken().equals("GET"))
      {
         String fileName = tokenizedLine.nextToken();
         if ( fileName.startsWith("/") )
            fileName = fileName.substring(1);
         final File file = new File(fileName);
         final int numOfBytes = (int)file.length();
         final FileInputStream inFile = new FileInputStream (fileName);
         final byte[] fileInBytes = new byte[numOfBytes];
         inFile.read(fileInBytes);
         outToClient.writeBytes("HTTP/1.0 200 OK\r\n");
         if (fileName.endsWith(".jpg"))
            outToClient.writeBytes("Content-Type: image/jpeg\r\n");
         if (fileName.endsWith(".gif"))
            outToClient.writeBytes("Content-Type: image/gif\r\n");
         outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
         outToClient.writeBytes("\r\n");
         outToClient.write(fileInBytes, 0, numOfBytes);
         connectionSocket.close();
      }
      else
         System.out.println("Bad Request Message");
   }
}
