/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package anyframe.sample.struts.web.common;

import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ExceptionConfig;

import anyframe.web.struts.util.AuthenticationException;
import anyframe.web.struts.util.AuthorizationException;
import anyframe.web.struts.util.DefaultBaseExceptionHandler;
public class SampleExceptionHandler extends DefaultBaseExceptionHandler {

	public SampleExceptionHandler() {
		this.defaultBundle = "anyframe.sample.struts.web.common.SampleResources";
	}

	public ActionForward execute(Exception exception, ExceptionConfig config,
			ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServletException {

		
		ActionForward forward = mapping.getInputForward();
		
		if (exception instanceof AuthenticationException) {
			String loginPageURI = "/loginView.do";
			forward.setPath(loginPageURI);
			request.setAttribute("authenticateFail", "true");
		} else if (exception instanceof AuthorizationException) {
			String homePageURI = "/authrizationView.do";
			forward.setPath(homePageURI);
			request.setAttribute("authFail", "true");
		} else {
			String forwardPath = forward.getPath();
			if (forwardPath == null || forwardPath.equals("")) {
				forwardPath = "/loginView.do";
				request.setAttribute("authFail", "true");
			}
			String url = forwardPath + "?";
			Enumeration enumrequest = request.getParameterNames();
			while (enumrequest.hasMoreElements()) {
				String parameterName = (String) enumrequest.nextElement();
				String parameterValue = request.getParameter(parameterName);
				url += parameterName + "=" + parameterValue + "&";
			}
			forward.setPath(url);
		}
		request.getSession().setAttribute("afterErrorPage", forward);
		return super.execute(exception, config, mapping, form, request,
				response);
	
	}
}

