1 package org.appfuse.webapp.action; 2 3 import java.io.IOException ; 4 import java.io.PrintWriter ; 5 import java.io.StringWriter ; 6 7 import javax.servlet.ServletException ; 8 import javax.servlet.http.HttpServletRequest ; 9 import javax.servlet.http.HttpServletResponse ; 10 11 import org.acegisecurity.AccessDeniedException; 12 13 import org.apache.commons.logging.Log; 14 import org.apache.commons.logging.LogFactory; 15 import org.apache.struts.Globals; 16 import org.apache.struts.action.ActionErrors; 17 import org.apache.struts.action.ActionForm; 18 import org.apache.struts.action.ActionForward; 19 import org.apache.struts.action.ActionMapping; 20 import org.apache.struts.action.ActionMessage; 21 import org.apache.struts.action.ActionMessages; 22 import org.apache.struts.action.ExceptionHandler; 23 import org.apache.struts.config.ExceptionConfig; 24 25 26 38 public final class ActionExceptionHandler extends ExceptionHandler { 39 41 private transient final Log log = LogFactory.getLog(ActionExceptionHandler.class); 42 43 45 61 public ActionForward execute(Exception ex, ExceptionConfig ae, 62 ActionMapping mapping, 63 ActionForm formInstance, 64 HttpServletRequest request, 65 HttpServletResponse response) 66 throws ServletException { 67 ActionErrors errors = 69 (ActionErrors) request.getAttribute(Globals.ERROR_KEY); 70 71 if (errors != null) { 72 return null; 73 } 74 75 ActionForward forward = 76 super.execute(ex, ae, mapping, formInstance, request, response); 77 78 ActionMessage error = null; 79 String property = null; 80 81 if (ex instanceof AccessDeniedException && forward == null) { 82 storeException(request, "", new ActionMessage("errors.detail", ex.getMessage()), forward); 83 try { 84 response.sendError(HttpServletResponse.SC_FORBIDDEN); 85 return null; 86 } catch (IOException io) { 87 io.printStackTrace(); 88 log.error(io.getMessage()); 89 } 90 } 91 92 while (ex != null) { 95 String msg = ex.getMessage(); 96 error = new ActionMessage("errors.detail", msg); 97 property = error.getKey(); 98 ex = (Exception ) ex.getCause(); 99 100 if ((ex != null) && (ex.getMessage() != null)) { 101 if (msg.indexOf(ex.getMessage()) == -1) { 104 storeException(request, property, error, forward); 105 } 106 } else { 107 storeException(request, property, error, forward); 108 } 109 } 110 111 return forward; 112 } 113 114 124 protected void storeException(HttpServletRequest request, String property, 125 ActionMessage error, ActionForward forward) { 126 ActionMessages errors = 127 (ActionMessages) request.getAttribute(Globals.ERROR_KEY); 128 129 if (errors == null) { 130 errors = new ActionMessages(); 131 } 132 133 errors.add(property, error); 134 135 request.setAttribute(Globals.ERROR_KEY, errors); 136 } 137 138 142 protected void logException(Exception ex) { 143 StringWriter sw = new StringWriter (); 144 ex.printStackTrace(new PrintWriter (sw)); 145 log.error(sw.toString()); 146 } 147 } 148 | Popular Tags |