Author: dpillot
Date: Wed Aug 16 15:48:27 2006
New Revision: 14913

URL: https://svndev.jahia.net/websvn/listing.php?sc=1&rev=14913&repname=jahia
Log:
http://www.jahia.net/jira/browse/JAHIA-55
added error specific document page for each site

Modified:
    trunk/core/src/java/org/jahia/bin/JahiaErrorDisplay.java

Modified: trunk/core/src/java/org/jahia/bin/JahiaErrorDisplay.java
URL: 
https://svndev.jahia.net/websvn/diff.php?path=/trunk/core/src/java/org/jahia/bin/JahiaErrorDisplay.java&rev=14913&repname=jahia
==============================================================================
--- trunk/core/src/java/org/jahia/bin/JahiaErrorDisplay.java (original)
+++ trunk/core/src/java/org/jahia/bin/JahiaErrorDisplay.java Wed Aug 16 
15:48:27 2006
@@ -31,6 +31,7 @@
 import org.jahia.exceptions.JahiaException;
 import org.jahia.registries.ServicesRegistry;
 import org.jahia.services.cache.Cache;
+import org.jahia.services.sites.JahiaSite;
 import org.jahia.settings.SettingsBean;
 
 import javax.mail.Message;
@@ -59,7 +60,7 @@
  * achieve by keeping it minimal. It includes a hardcoded HTML display method 
in
  * the case where a dispatching ressource is not available (such as an error in
  * the configuration of Jahia).
- *
+ * <p/>
  * When throwing a JahiaException, if its "userErrorMsg" message starts with 
an integer,
  * ie. "404 Page not found" then this class forwards the error to the 
"404.jsp" page
  * if found in the errors directory. For details about those error codes,
@@ -71,9 +72,12 @@
     private static org.apache.log4j.Logger logger =
             org.apache.log4j.Logger.getLogger(JahiaErrorDisplay.class);
 
-    private static final String DISPATCH_DESTINATION = 
"/jsp/jahia/errors/error.jsp";
-    private    static final String DISPATCH_DIRECTORY = "/jsp/jahia/errors/";
-    private static final String DISPATCH_PREFIX="error_";
+
+    private static final String DISPATCH_ROOT = "/jsp/jahia/";
+    private static final String DISPATCH_SITES_ROOT = DISPATCH_ROOT + 
"templates/";
+    private static final String DISPATCH_DIRECTORY = "errors";
+    private static final String DISPATCH_DESTINATION = DISPATCH_ROOT + 
DISPATCH_DIRECTORY + "/error.jsp";
+    private static final String DISPATCH_PREFIX = "error_";
     private static final boolean IS_STACK_INCLUDED = true;
 
     public static final String DISPLAY_JAHIA_ERROR = "displayJahiaError";
@@ -83,7 +87,7 @@
 
     static {
         logger.debug("Initialized with destination = [" +
-                     DISPATCH_DESTINATION + "]");
+                DISPATCH_DESTINATION + "]");
     }
 
     public JahiaErrorDisplay() {
@@ -102,7 +106,7 @@
             return false;
         }
         if (out != null) {
-            /** @todo : fixme : this is not update to date with the lastest
+            /** todo : fixme : this is not update to date with the lastest
              *  chaining stuff
              */
             out.println("<html>");
@@ -158,7 +162,6 @@
      * Displays an exception on a HTML browser using either JSP pages or
      * static hardcoded HTML output. Also sends out an email to the 
administrator
      * is this feature was activated.
-     *
      */
     public static boolean DisplayException(HttpServletRequest request,
                                            HttpServletResponse response,
@@ -169,15 +172,15 @@
                                            Throwable t) {
         try {
 
-            Boolean displayJahiaError = 
(Boolean)request.getAttribute(DISPLAY_JAHIA_ERROR);
-            if ( displayJahiaError != null && 
!displayJahiaError.booleanValue() ){
+            Boolean displayJahiaError = (Boolean) 
request.getAttribute(DISPLAY_JAHIA_ERROR);
+            if (displayJahiaError != null && 
!displayJahiaError.booleanValue()) {
                 return false;
             }
 
             if ((request == null) ||
-                (response == null) ||
-                (context == null) ||
-                (t == null)) {
+                    (response == null) ||
+                    (context == null) ||
+                    (t == null)) {
                 logger.debug("Can't display exception, not enough information 
available...");
                 return false;
             }
@@ -192,28 +195,51 @@
                 context.log(throwableToString(t, request, response));
                 if (t instanceof JahiaException) {
                     JahiaException je = (JahiaException) t;
-                    logger.error ( "ERROR : " + je.getUserErrorMsg() +
-                                   ", " + je.getJahiaErrorMsg(), 
getNestedException(t));
-                } else if ( t != null ){
-                    logger.error ( "ERROR : "+t.getMessage(), 
getNestedException(t));
+                    logger.error("ERROR : " + je.getUserErrorMsg() +
+                            ", " + je.getJahiaErrorMsg(), 
getNestedException(t));
+                } else if (t != null) {
+                    logger.error("ERROR : " + t.getMessage(), 
getNestedException(t));
                 }
             }
 
             // By default, uses the standard error message
+            boolean isSiteErrorEnabled = jSettings.getSiteErrorEnabled();
+
             String fullPathToDestination = 
context.getRealPath(DISPATCH_DESTINATION);
             String contextPathToDestination = DISPATCH_DESTINATION;
 
+            //grab the sitekey from the request
+            JahiaSite site = (JahiaSite) 
request.getSession().getAttribute("org.jahia.services.sites.jahiasite");
+
+            if (isSiteErrorEnabled) {
+                //check for site-specific error pages directory (errors dir)
+                logger.debug("site error enabled: checking the availability of 
errors directory");
+                contextPathToDestination = 
context.getRealPath(DISPATCH_SITES_ROOT + site.getSiteKey() + "/" + 
DISPATCH_DIRECTORY);
+                if (contextPathToDestination != null) {
+                    File dir = new File(contextPathToDestination);//check on 
directory
+                    if (!dir.exists()) {
+                        logger.debug("not found errors directory for the site 
" + site.getSiteKey());
+                        isSiteErrorEnabled = false;
+                        contextPathToDestination = DISPATCH_DESTINATION;
+                    }
+                } else {
+                    isSiteErrorEnabled = false;
+                    contextPathToDestination = DISPATCH_DESTINATION;
+                }
+            }
+
             File jspFile = new File(fullPathToDestination);
             File jspFileErrorCode = null;
 
             // check if error contains a standard HTTP/1.1 error code, if so, 
tries to forward to
             // the corresponding JSP
-            String     errorstring = "";
+            String errorstring = "";
             try {
                 errorstring = t.getMessage().trim();
-            } catch (Throwable tho) {}
+            } catch (Throwable tho) {
+            }
 
-            int                errorint = 0;
+            int errorint = 0;
 
             // 2005/05/20 :: uses regexp to extract html error code.
             Pattern p = Pattern.compile("\\d\\d\\d");
@@ -223,50 +249,67 @@
             }
             try {
                 errorint = Integer.parseInt(errorstring);
-            } catch (NumberFormatException nfe) {}
-              catch (Throwable th) {}
+            } catch (NumberFormatException nfe) {
+            }
+            catch (Throwable th) {
+            }
 
             // yes the error string contains an error code! let's specify the 
special jsp!
-            if (errorint!=0)
-            {
+            if (errorint != 0) {
                 response.setStatus(errorint);  // sets response status
-                fullPathToDestination = context.getRealPath 
(DISPATCH_DIRECTORY + DISPATCH_PREFIX + errorint + ".jsp");
+                String filepath = DISPATCH_DIRECTORY + "/" + DISPATCH_PREFIX + 
errorint + ".jsp";
+                String filerootpath = DISPATCH_ROOT;
+                String msg = "site error unenabled:";
+
+                if (isSiteErrorEnabled) {
+                    filerootpath = DISPATCH_SITES_ROOT + site.getSiteKey() + 
"/";
+                    msg = "site error enabled:";
+                }
+
+                fullPathToDestination = context.getRealPath(filerootpath + 
filepath);
+                logger.debug(msg + " using path to " + fullPathToDestination);
                 jspFileErrorCode = new File(fullPathToDestination);
-                if (jspFileErrorCode.exists())
-                    {   jspFile = jspFileErrorCode;
-                        contextPathToDestination = DISPATCH_DIRECTORY + 
DISPATCH_PREFIX + errorint + ".jsp";
-                        logger.debug("Forwarding error to 
"+fullPathToDestination);
-                    } else     {
-                        logger.debug("Dispatcher not found at 
"+fullPathToDestination+ " - using standard error");
-                    }
-            }
-            //no error code available, so just default to a HTTP 500
-            else {
+
+                if (jspFileErrorCode.exists()) {
+                    logger.debug("using existing specific error jsp page:" + 
errorint + ".jsp");
+                    jspFile = jspFileErrorCode;
+
+                    contextPathToDestination = filerootpath + filepath;
+                    logger.debug("contextpath is:" + contextPathToDestination);
+                    logger.debug("Forwarding error to " + 
fullPathToDestination);
+                } else {
+                    logger.debug("error jsp file not found at " + 
fullPathToDestination + " - using standard error");
+                }
+            } else {
+                //no error code available, so just default to a HTTP 500
                 
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             }
 
             if (jSettings != null) {
-                logger.debug("Jahia Settings available, mailing...");
+
                 if (sendEmail) {
+                    logger.debug("Jahia Settings available, mailing...");
                     MailException(t, request, response, jSettings, errorint);
                 }
             } else {
                 logger.debug("No Jahia Settings, can't mail...");
             }
 
-            logger.debug("context is : "+contextPathToDestination);
+            logger.debug("context is : " + contextPathToDestination);
             // forwards to the jsp
             if (jspFile.exists()) {
-                RequestDispatcher dispatcher = context.getRequestDispatcher( 
contextPathToDestination );
+                RequestDispatcher dispatcher = 
context.getRequestDispatcher(contextPathToDestination);
                 if (dispatcher != null) {
                     request.setAttribute("org.jahia.exception.Message", 
t.getMessage());
                     if (IS_STACK_INCLUDED) {
                         String stackTraceStr = stackTraceToString(t);
                         request.setAttribute("org.jahia.exception.StackTrace", 
stackTraceStr);
                     }
+                    logger.debug("forwarding to " + contextPathToDestination);
                     dispatcher.forward(request, response);
                     return true;
                 } else {
+                    logger.debug("dispatcher not found at " + 
contextPathToDestination);
                     return HTMLFallBackDisplay(request, response, t);
                 }
             } else {
@@ -301,12 +344,12 @@
                                         SettingsBean jSettings,
                                         int errorInt) {
         try {
-            String  to = null, subject = null, from = null,
-                cc = null, bcc = null, url = null;
+            String to = null, subject = null, from = null,
+                    cc = null, bcc = null, url = null;
             String mailhost = null;
             String mailer = "Jahia Server 1.0";
             String protocol = null, host = null, user = null, password = null;
-            String record = null;      // name of folder in which to record 
mail
+            String record = null;    // name of folder in which to record mail
 
             to = jSettings.mail_administrator;
             from = jSettings.mail_from;
@@ -323,9 +366,9 @@
             }
 
             logger.debug("Using settings mailhost=[" + mailhost +
-                         "] to=[" + to + "] from=[" + from +
-                         "] paranoia=" +
-                         Integer.toString(jSettings.mail_paranoia));
+                    "] to=[" + to + "] from=[" + from +
+                    "] paranoia=" +
+                    Integer.toString(jSettings.mail_paranoia));
 
             if (jSettings.mail_paranoia == 0) {
                 // mailing is disabled, we never send anything.
@@ -367,12 +410,12 @@
                 msg.setFrom();
 
             msg.setRecipients(Message.RecipientType.TO,
-                        InternetAddress.parse(to, false));
+                    InternetAddress.parse(to, false));
             if (cc != null)
-            msg.setRecipients(Message.RecipientType.CC,
+                msg.setRecipients(Message.RecipientType.CC,
                         InternetAddress.parse(cc, false));
             if (bcc != null)
-            msg.setRecipients(Message.RecipientType.BCC,
+                msg.setRecipients(Message.RecipientType.BCC,
                         InternetAddress.parse(bcc, false));
 
             subject = "[JAHIA] Jahia Error : " + t.getMessage();
@@ -393,10 +436,18 @@
                 JahiaException nje = (JahiaException) t;
                 String severityMsg = "Undefined";
                 switch (nje.getSeverity()) {
-                    case JahiaException.WARNING_SEVERITY : severityMsg = 
"WARNING"; break;
-                    case JahiaException.ERROR_SEVERITY : severityMsg = 
"ERROR"; break;
-                    case JahiaException.CRITICAL_SEVERITY : severityMsg = 
"CRITICAL"; break;
-                    case JahiaException.KISSYOURASSGOODBYE_SEVERITY : 
severityMsg = "FATAL"; break;
+                    case JahiaException.WARNING_SEVERITY :
+                        severityMsg = "WARNING";
+                        break;
+                    case JahiaException.ERROR_SEVERITY :
+                        severityMsg = "ERROR";
+                        break;
+                    case JahiaException.CRITICAL_SEVERITY :
+                        severityMsg = "CRITICAL";
+                        break;
+                    case JahiaException.KISSYOURASSGOODBYE_SEVERITY :
+                        severityMsg = "FATAL";
+                        break;
                 }
                 strOut.println("Severity : " + severityMsg);
             }
@@ -419,7 +470,7 @@
                 String headerValue = request.getHeader(headerName);
                 strOut.println("   " + headerName + " : " + headerValue);
             }
-            
+
             strOut.println("");
             strOut.println("Stack trace :");
             strOut.println("-------------");
@@ -460,8 +511,8 @@
             strOut.println("Memory status :");
             strOut.println("---------------");
             strOut.println("Max memory   : " + 
Runtime.getRuntime().maxMemory() + " bytes");
-            strOut.println("Free memory  : " + 
Runtime.getRuntime().freeMemory()+ " bytes");
-            strOut.println("Total memory : " + 
Runtime.getRuntime().totalMemory()+ " bytes");
+            strOut.println("Free memory  : " + 
Runtime.getRuntime().freeMemory() + " bytes");
+            strOut.println("Total memory : " + 
Runtime.getRuntime().totalMemory() + " bytes");
 
             strOut.println("");
             strOut.println("Cache status :");
@@ -472,7 +523,7 @@
             DecimalFormat percentFormat = new DecimalFormat("###.##");
             while (cacheNameIte.hasNext()) {
                 String curCacheName = (String) cacheNameIte.next();
-                Object objectCache = 
ServicesRegistry.getInstance().getCacheService().getCache (curCacheName);
+                Object objectCache = 
ServicesRegistry.getInstance().getCacheService().getCache(curCacheName);
                 if (objectCache instanceof Cache) {
                     Cache curCache = (Cache) objectCache;
                     long cacheLimit = curCache.getCacheLimit();
@@ -482,10 +533,10 @@
                     }
                     strOut.println("name=" + curCacheName +
                             " size=" + curCache.size() +
-                            " limit=" + cacheLimit/(1024*1024)+ "MB" +
+                            " limit=" + cacheLimit / (1024 * 1024) + "MB" +
                             " successful hits=" + curCache.getSuccessHits() +
                             " total hits=" + curCache.getTotalHits() +
-                            " efficiency=" + efficiencyStr +"%");
+                            " efficiency=" + efficiencyStr + "%");
                 }
             }
 
@@ -525,12 +576,11 @@
      * can contain other exception.
      * Warning : the result String contains return chars.
      *
-     * @param t the exception to be converted to a String
-     * @param request the http request object
+     * @param t        the exception to be converted to a String
+     * @param request  the http request object
      * @param response the http response object
-     *
      * @return A string containing the full dump with stack trace of the
-     * exception. Return chars are inserted to make it more readable...
+     *         exception. Return chars are inserted to make it more readable...
      */
     private static String throwableToString(Throwable t,
                                             HttpServletRequest request,
@@ -542,10 +592,18 @@
             JahiaException nje = (JahiaException) t;
             String severityMsg = "Undefined";
             switch (nje.getSeverity()) {
-                case JahiaException.WARNING_SEVERITY : severityMsg = 
"WARNING"; break;
-                case JahiaException.ERROR_SEVERITY : severityMsg = "ERROR"; 
break;
-                case JahiaException.CRITICAL_SEVERITY : severityMsg = 
"CRITICAL"; break;
-                case JahiaException.KISSYOURASSGOODBYE_SEVERITY : severityMsg 
= "FATAL"; break;
+                case JahiaException.WARNING_SEVERITY :
+                    severityMsg = "WARNING";
+                    break;
+                case JahiaException.ERROR_SEVERITY :
+                    severityMsg = "ERROR";
+                    break;
+                case JahiaException.CRITICAL_SEVERITY :
+                    severityMsg = "CRITICAL";
+                    break;
+                case JahiaException.KISSYOURASSGOODBYE_SEVERITY :
+                    severityMsg = "FATAL";
+                    break;
             }
             strOut.println("Severity : " + severityMsg);
         }
@@ -575,11 +633,10 @@
      * causes of the error.
      *
      * @param t the exception (eventually that contains other exceptions) for
-     * which we want to convert the stack trace into a string.
-     *
+     *          which we want to convert the stack trace into a string.
      * @return a string containing all the stack traces of all the exceptions
-     * contained inside this exception, or an empty string if passed an
-     * empty string.
+     *         contained inside this exception, or an empty string if passed an
+     *         empty string.
      */
     public static String stackTraceToString(Throwable t) {
         int nestingDepth = getNestedExceptionDepth(t, 0);
@@ -604,7 +661,7 @@
             innerThrowable = ite.getTargetException();
         }
         if (innerThrowable != null) {
-            String innerExceptionTrace = 
recursiveStackTraceToString(innerThrowable, curDepth-1);
+            String innerExceptionTrace = 
recursiveStackTraceToString(innerThrowable, curDepth - 1);
             msgBodyWriter.write(innerExceptionTrace);
         }
         if (curDepth == 0) {
@@ -634,7 +691,7 @@
             innerThrowable = ite.getTargetException();
         }
         if (innerThrowable != null) {
-            newDepth = getNestedExceptionDepth(innerThrowable, curDepth+1);
+            newDepth = getNestedExceptionDepth(innerThrowable, curDepth + 1);
         }
         return newDepth;
     }
@@ -642,9 +699,10 @@
     /**
      * Returns the nested exception if there is one, otherwise returns the
      * current exception.
+     *
      * @param t Throwable
      * @return Throwable this method never returns null so don't put it in a
-     * loop !
+     *         loop !
      */
     public static Throwable getNestedException(Throwable t) {
         if (t == null) {

Reply via email to