import java.io.*;
import java.net.*;

class CookieExpireDateHandlingTester extends Thread
{
 BufferedInputStream clientIS;
 BufferedOutputStream clientOS;
 Socket socketToClient;
 CookieExpireDateHandlingTester(Socket soc) throws Exception
 {
	clientIS = new BufferedInputStream (soc.getInputStream());
	clientOS = new BufferedOutputStream (soc.getOutputStream());
	socketToClient = soc;
 }
 public void run()
 {
   try{
 	BufferedReader clientDIS = new BufferedReader (new InputStreamReader(clientIS));
 	String line = clientDIS.readLine();
 	PrintWriter ps = new PrintWriter(new OutputStreamWriter(clientOS));
 	if (line.indexOf("redirected") == -1) // GET
	{
	 	ps.println("HTTP/1.0 302 Redirect");
	 	ps.println("Content-Type: text/html");
	 	ps.println("Cache-Control: no-cache, no-store, must-revalidate");
 	
 		java.text.SimpleDateFormat outputHTTPDateFormat = new java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", java.util.Locale.US);
 		outputHTTPDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
 		int indexOfQMark = line.indexOf("?");
 		int minutesToSetClockBackwards = 0;
 		if (indexOfQMark!=-1)
 		{
 		 try { minutesToSetClockBackwards = Integer.parseInt(line.substring(indexOfQMark+1, line.indexOf(" ", indexOfQMark))); }
 		 catch (Exception e) {}
 		} 		 
 		java.util.Date timestamp = new java.util.Date(System.currentTimeMillis() - 1000*60*minutesToSetClockBackwards);
 		String serverSideFiledateSTR  = outputHTTPDateFormat.format(timestamp);
 		System.out.println(serverSideFiledateSTR);
 		ps.println("Set-Cookie: testi1=testi2; expires="+serverSideFiledateSTR+"; path=/");
 		ps.println("Location: http:/"+socketToClient.getLocalAddress().toString().
 			substring(socketToClient.getLocalAddress().toString().lastIndexOf("/"))
 			+":8081"
 			+"?redirected&"+((long)(100000000000*Math.random()))); // I add the random number to avoid caching
	 	ps.println();
	}
	else
	{
	 	ps.println("HTTP/1.0 200 OK");
 		ps.println("Content-Type: text/html");
 		ps.println("Cache-Control: no-cache, no-store, must-revalidate");

	 	ps.println();
	 	while (!(line = clientDIS.readLine()).equals("")) 
 			if (line.indexOf("testi1") != -1) ps.println("<b>COOKIE FOUND: "+line+"</b><br>");
 			else ps.println(line+"<br>");
 	} // else
 	ps.close();
 	clientDIS.close(); 	
	socketToClient.close();
	}
 	catch (Exception e) {System.out.println("error: "+e);}
 }
 
public static void main(java.lang.String[] args) throws Exception
  {
  	ServerSocket ss = new ServerSocket (8081);
  	while(true)
		new CookieExpireDateHandlingTester(ss.accept()).start();
 	}
}

