/*
 * Created on Jul 21, 2003
 *
 */
package ca.uvic.gild.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ca.uvic.gild.activeHTML.GildCommandInterpreter;
import ca.uvic.gild.activeHTML.IGildCommand;

/**
 * A servlet that responds to an HTTP "get" by performing some command on the Eclipse workspace.
 * The command name and its arguments are specified in the request.
 * 
 * @author Adrian, Rob Lintern
 *
 */
public class GildCommandServlet extends HttpServlet {

	/** 
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		if (!(request.getServerName().equals("localhost") || request.getServerName().equals("127.0.0.1"))) {
			try {
				response.getOutputStream().println("Sorry, you can only access this Gild servlet through the local host!");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return;
		}
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("UTF-8");
		
		
		String commandName= request.getParameter("name");
		String args = request.getParameter("args");
		try {
			IGildCommand gildCmd = new GildCommandInterpreter ();
			if (args != null) {
				gildCmd.setCommandArguments(args);
			} else {
				gildCmd.setCommandArguments("");
			}
			
			if (commandName != null) {
				gildCmd.setCommandName(commandName);
			} else {
				gildCmd.setCommandName("");
			}
			Thread runnableGildCmd = new Thread(gildCmd);
			runnableGildCmd.setDaemon(true);
			runnableGildCmd.start();
		} catch (ThreadDeath td) {
			out.write(td.getMessage());
			throw td;
		} catch (Exception e) {
			out.write(e.getMessage());
		}
		out.close();
	}

	/** 
	 * Handles the HTTP <code>GET</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		processRequest(request, response);
	}

	/** 
	 * Handles the HTTP <code>POST</code> method.
	 * @param request servlet request
	 * @param response servlet response
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
		processRequest(request, response);
	}

	/** 
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo() {
		return "A servlet that responds to an HTTP 'get' by performing some command on the Eclipse workspace.";
	}

}
