package com.eactive.eai.agent.web;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

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

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.util.Logger;

public class WebAgent extends HttpServlet
{
	private static final long serialVersionUID = 1L;
    ObjectInputStream is = null;

    Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    protected Object execute(Command command) throws CommandException {
        try{
            return command.execute();

        }catch (CommandException ce){
        	logger.error( ce.getMessage(), ce);
			throw ce;
        }catch (Exception e){
        	logger.error( e.getMessage(), e);
            String errorMsg = ExceptionUtil.getErrorCode(e, "BECEAICAG010");
            if (logger.isError()) logger.error(errorMsg);
            throw new CommandException(errorMsg);
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response) {

        try {

            ObjectInputStream is = new ObjectInputStream(request.getInputStream());
            ObjectOutputStream os = new ObjectOutputStream(response.getOutputStream());

            Command command =   (Command)is.readObject();
            Object obj;
            try{
            	obj = execute(command);
            }catch (Exception e){
                obj = e.getMessage();
            }finally{
                is.close();
                os.close();
            }

            os.writeObject((Serializable)obj);

            is.close();
            os.close();

        } catch (Exception e) {
        	logger.error( e.getMessage(), e);
            response.setStatus(500);
            try {
                response.getWriter().println(e.getMessage());
                throw e;
            } catch (Exception ex) {
            	logger.error( ex.getMessage(), ex);
            }

        }

    }
}
