| 1 19 20 package za.org.coefficient.interceptors; 21 22 import net.sf.hibernate.HibernateException; 23 import net.sf.hibernate.StaleObjectStateException; 24 import net.sf.hibernate.util.HibernateUtil; 25 26 import za.org.coefficient.core.CoefficientInterceptor; 27 import za.org.coefficient.interfaces.CoefficientContext; 28 29 import org.apache.commons.beanutils.PropertyUtils; 30 31 import java.io.PrintWriter ; 32 import java.io.StringWriter ; 33 34 import java.lang.reflect.InvocationTargetException ; 35 36 import java.util.StringTokenizer ; 37 38 43 public class ExceptionInterceptor extends CoefficientInterceptor { 44 45 public static final String LAST_UNHANDLED_EXCEPTION = "__last_unhandled_exception__"; 46 47 49 public int invoke(CoefficientContext ctx) throws Exception { 50 int retVal = INVOKE_PROCESS_CHILD; 51 boolean dont = false; 52 53 try { 54 retVal = super.invoke(ctx); 55 HibernateUtil.finalizeSession(); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 Throwable t = null; 60 if (e instanceof InvocationTargetException ) { 61 t = ((InvocationTargetException ) e).getTargetException(); 62 if (t instanceof StaleObjectStateException) { 63 ctx.setError( 64 "Another site user updated the data you are changing since you have last read it. Please try your manipulation again, but make sure that your change is still relevant."); 65 dont = true; 66 } 67 } 68 69 if (!dont) { 70 setErrorForException(ctx, e, t); 71 } 72 if(t == null) { 73 ctx.setSessionAttribute(LAST_UNHANDLED_EXCEPTION, e); 74 } else { 75 ctx.setSessionAttribute(LAST_UNHANDLED_EXCEPTION, t); 76 } 77 try { 78 HibernateUtil.finalizeSession(); 82 } catch(Exception ex) { 84 setErrorForException(ctx, ex, null); 85 } 86 } 87 88 return retVal; 89 } 90 91 private void setErrorForException(CoefficientContext ctx, Exception e, 92 Throwable t) { 93 StringWriter sw = new StringWriter (); 94 PrintWriter pw = new PrintWriter (sw); 95 if (t == null) { 96 e.printStackTrace(pw); 97 } else { 98 t.printStackTrace(pw); 99 } 100 StringTokenizer st = new StringTokenizer (sw.toString(), "\n"); 101 StringBuffer sb = new StringBuffer (); 102 103 sb.append("<b><font color='red'>There has been a system exception</font></b><br><br>"); 104 105 while (st.hasMoreElements()) { 106 sb.append(st.nextToken()) 107 .append("<br>"); 108 } 109 110 ctx.setError(sb.toString()); 111 } 112 } 113 | Popular Tags |