

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.URLDecoder;
import bsh.Interpreter;

import com.sun.xml.internal.fastinfoset.Decoder;

public class ProcessingUnit extends Thread {
	Socket client;

	public ProcessingUnit(Socket client) {
		this.client = client;
	}

	@Override
	public void run() {
		try {
			processClient(client);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Connection close.");
		}
	}

	private void processClient(Socket client) throws IOException {
		InputStream in = client.getInputStream();
		OutputStream out = client.getOutputStream();
		BufferedReader bIn = new BufferedReader(new InputStreamReader(in));
		BufferedOutputStream bOut = new BufferedOutputStream(out);
		//bOut.write("HTTP/1.1 200 OK\nServer: YoshiServer\n\n".getBytes());
		PrintStream origin = new PrintStream(System.out);
		PrintStream pOut = new PrintStream(out);
		String line = "";
		while ((line = bIn.readLine()) != null) {
			// System.out.println(line);
			String[] cmd = line.split(" ");//split a line into cmd[] 
			if (cmd[0].equalsIgnoreCase("GET")) {
				System.out.println(line); // we skip all other lines except
											// those starting with "GET"
				try {
					FileInputStream toSendFile = new FileInputStream("WWW/"
							+ cmd[1].substring(1));
					BufferedInputStream fileToSend = new BufferedInputStream(
							toSendFile);
					int data = 0;
					while ((data = fileToSend.read()) != -1) {
						bOut.write(data);
					}
					bOut.flush();
					break;
				} catch (FileNotFoundException e) {
					bOut.write("Page no found.\n\n".getBytes());
					break;
				}
			}
			if (cmd[0].equalsIgnoreCase("POST")){
				/*read*/
				int temp=0;
				int i, len;
				BufferedOutputStream save = new BufferedOutputStream(new FileOutputStream("UPLOAD/"/*file name*/));
				String src = "";
				//char[] Len = new char[10];
				while(temp = bIn.read()!=-1){
					src = src + (char)temp;
					if(src.equalsIgnoreCase("Content-Length:"))break;
				}
				
				
				for(i=0; i<2; i++){
					temp = bIn.read();
					src = src +(char)temp;
				}
				char[] Len = src.toCharArray(); 
				len = ((int)Len[0]-48)*10 + Len[1]-48;
				//
				src = "";
				for(i=0; i<len; i++){
					src = src + bIn.read();
				}
				Interpreter bsh = new Interpreter();
				System.setOut(pOut);
				System.setErr(pOut);
				
				String decoded = URLDecoder.decode(src);
				bsh.eval(decoded);
				
				
				System.setOut(origin);
				System.setErr(origin);
			}
		
			//break;
		}
		client.close();
	}

}
