/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.dispatcher;

import nuts.core.servlet.HttpServletUtils;
import nuts.exts.exception.NoPermitException;
import nuts.exts.exception.UnknownHandlerException;
import nuts.exts.struts2.util.StrutsContextUtils;

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

import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionInvocation;


/**
 */
@SuppressWarnings("serial")
public class ExceptionResult extends StrutsResultSupport {

	/**
	 * Constructor.
	 */
	public ExceptionResult() {
		super();
	}

	/**
	 * @see org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(java.lang.String, com.opensymphony.xwork2.ActionInvocation)
	 */
	protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
		HttpServletRequest request = StrutsContextUtils.getServletRequest();
		HttpServletResponse response = StrutsContextUtils.getServletResponse();
		
		Throwable e = (Throwable)invocation.getStack().findValue("exception");
		
		if (e != null) {
			if (e instanceof UnknownHandlerException) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
			}
			else if (e instanceof NoPermitException) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
			}
			else {
				HttpServletUtils.logException(e, request);
				
				// send a http error response to use the servlet defined error handler
				// make the exception availible to the web.xml defined error page
				request.setAttribute("javax.servlet.error.exception", e);
				
				// for compatibility
				request.setAttribute("javax.servlet.jsp.jspException", e);
				
				response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
			}
		}
	}
}
