Coverage Report - org.mule.config.ExceptionHelper
 
Classes in this File Line Coverage Branch Coverage Complexity
ExceptionHelper
35%
67/193
28%
28/100
3.857
 
 1  
 /*
 2  
  * $Id: ExceptionHelper.java 10415 2008-01-21 10:46:37Z dirk.olmes $
 3  
  * --------------------------------------------------------------------------------------
 4  
  * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
 5  
  *
 6  
  * The software in this package is published under the terms of the CPAL v1.0
 7  
  * license, a copy of which has been included with this distribution in the
 8  
  * LICENSE.txt file.
 9  
  */
 10  
 
 11  
 package org.mule.config;
 12  
 
 13  
 import org.mule.MuleRuntimeException;
 14  
 import org.mule.config.i18n.MessageFactory;
 15  
 import org.mule.umo.UMOException;
 16  
 import org.mule.util.ClassUtils;
 17  
 import org.mule.util.SpiUtils;
 18  
 import org.mule.util.StringUtils;
 19  
 
 20  
 import java.io.IOException;
 21  
 import java.io.InputStream;
 22  
 import java.util.ArrayList;
 23  
 import java.util.HashMap;
 24  
 import java.util.Iterator;
 25  
 import java.util.List;
 26  
 import java.util.Map;
 27  
 import java.util.Properties;
 28  
 
 29  
 import org.apache.commons.collections.MapUtils;
 30  
 import org.apache.commons.logging.Log;
 31  
 import org.apache.commons.logging.LogFactory;
 32  
 
 33  
 /**
 34  
  * <code>ExceptionHelper</code> provides a number of helper functions that can be
 35  
  * useful for dealing with Mule exceptions. This class has 3 core functions - <p/>
 36  
  * 1. ErrorCode lookup. A corresponding Mule error code can be found using for a
 37  
  * given Mule exception 2. Addtional Error information such as Java doc url for a
 38  
  * given exception can be resolved using this class 3. Error code mappings can be
 39  
  * looked up by providing the the protocol to map to and the Mule exception.
 40  
  */
 41  
 
 42  
 public final class ExceptionHelper
 43  
 {
 44  
     /**
 45  
      * This is the property to set the error code to no the message it is the
 46  
      * property name the Transport provider uses set the set the error code on the
 47  
      * underlying message
 48  
      */
 49  
     public static final String ERROR_CODE_PROPERTY = "error.code.property";
 50  
 
 51  
     /**
 52  
      * a comma-separated list of other protocols the mappings in a file can be
 53  
      * applied to
 54  
      */
 55  
     public static final String APPLY_TO_PROPERTY = "apply.to";
 56  
 
 57  
     /**
 58  
      * logger used by this class
 59  
      */
 60  4
     protected static final Log logger = LogFactory.getLog(ExceptionHelper.class);
 61  
 
 62  2
     private static String J2SE_VERSION = "";
 63  
 
 64  
     /** todo How do you get the j2ee version?? */
 65  
     private static final String J2EE_VERSION = "1.3ee";
 66  
 
 67  2
     private static Properties errorDocs = new Properties();
 68  2
     private static Properties errorCodes = new Properties();
 69  2
     private static Map reverseErrorCodes = null;
 70  2
     private static Map errorMappings = new HashMap();
 71  
 
 72  2
     private static int exceptionThreshold = 0;
 73  2
     private static boolean verbose = true;
 74  
 
 75  2
     private static boolean initialised = false;
 76  
 
 77  
     /**
 78  
      * A list of the exception readers to use for different types of exceptions
 79  
      */
 80  2
     private static List exceptionReaders = new ArrayList();
 81  
 
 82  
     /**
 83  
      * The default ExceptionReader which will be used for most types of exceptions
 84  
      */
 85  2
     private static ExceptionReader defaultExceptionReader = new DefaultExceptionReader();
 86  
 
 87  
     static
 88  
     {
 89  2
         initialise();
 90  2
     }
 91  
 
 92  
     /** Do not instanciate. */
 93  
     private ExceptionHelper ()
 94  0
     {
 95  
         // no-op
 96  0
     }
 97  
 
 98  
     public static void initialise()
 99  
     {
 100  
         try
 101  
         {
 102  2
             if (initialised)
 103  
             {
 104  0
                 return;
 105  
             }
 106  
 
 107  2
             registerExceptionReader(new UMOExceptionReader());
 108  2
             registerExceptionReader(new NamingExceptionReader());
 109  2
             J2SE_VERSION = System.getProperty("java.specification.version");
 110  
 
 111  2
             InputStream is = SpiUtils.findServiceDescriptor("org/mule/config",
 112  
                 "mule-exception-codes.properties", ExceptionHelper.class);
 113  2
             if (is == null)
 114  
             {
 115  0
                 throw new IllegalArgumentException(
 116  
                     "Failed to load resource: META_INF/services/org/mule/config/mule-exception-codes.properties");
 117  
             }
 118  2
             errorCodes.load(is);
 119  2
             reverseErrorCodes = MapUtils.invertMap(errorCodes);
 120  2
             is = SpiUtils.findServiceDescriptor("org/mule/config", "mule-exception-config.properties",
 121  
                 ExceptionHelper.class);
 122  2
             if (is == null)
 123  
             {
 124  0
                 throw new IllegalArgumentException(
 125  
                     "Failed to load resource: META_INF/services/org/mule/config/mule-exception-config.properties");
 126  
             }
 127  2
             errorDocs.load(is);
 128  
 
 129  2
             initialised = true;
 130  
         }
 131  0
         catch (IOException e)
 132  
         {
 133  0
             throw new MuleRuntimeException(
 134  
                 MessageFactory.createStaticMessage("Failed to load Exception resources"),
 135  
                 e);
 136  2
         }
 137  2
     }
 138  
 
 139  
     public static int getErrorCode(Class exception)
 140  
     {
 141  270
         String code = errorCodes.getProperty(exception.getName(), "-1");
 142  270
         return Integer.parseInt(code);
 143  
     }
 144  
 
 145  
     public static Class getErrorClass(int code)
 146  
     {
 147  0
         String key = String.valueOf(code);
 148  0
         Object clazz = reverseErrorCodes.get(key);
 149  0
         if (clazz == null)
 150  
         {
 151  0
             return null;
 152  
         }
 153  0
         else if (clazz instanceof Class)
 154  
         {
 155  0
             return (Class) clazz;
 156  
         }
 157  
         else
 158  
         {
 159  
             try
 160  
             {
 161  0
                 clazz = ClassUtils.loadClass(clazz.toString(), ExceptionHelper.class);
 162  
             }
 163  0
             catch (ClassNotFoundException e)
 164  
             {
 165  0
                 logger.error(e.getMessage(), e);
 166  0
                 return null;
 167  0
             }
 168  0
             reverseErrorCodes.put(key, clazz);
 169  0
             return (Class) clazz;
 170  
         }
 171  
     }
 172  
 
 173  
     public static String getErrorMapping(String protocol, int code)
 174  
     {
 175  0
         Class c = getErrorClass(code);
 176  0
         if (c != null)
 177  
         {
 178  0
             return getErrorMapping(protocol, c);
 179  
         }
 180  
         else
 181  
         {
 182  0
             logger.error("Class not known for code: " + code);
 183  0
             return "-1";
 184  
         }
 185  
     }
 186  
 
 187  
     private static Properties getErrorMappings(String protocol)
 188  
     {
 189  0
         Object m = errorMappings.get(protocol);
 190  0
         if (m != null)
 191  
         {
 192  0
             if (m instanceof Properties)
 193  
             {
 194  0
                 return (Properties) m;
 195  
             }
 196  
             else
 197  
             {
 198  0
                 return null;
 199  
             }
 200  
         }
 201  
         else
 202  
         {
 203  0
             InputStream is = SpiUtils.findServiceDescriptor("org/mule/config",
 204  
                 protocol + "-exception-mappings.properties", ExceptionHelper.class);
 205  0
             if (is == null)
 206  
             {
 207  0
                 errorMappings.put(protocol, "not found");
 208  0
                 logger.warn("Failed to load error mappings from: META-INF/services/org/mule/config/"
 209  
                             + protocol
 210  
                             + "-exception-mappings.properties. This may be because there are no error code mappings for protocol: "
 211  
                             + protocol);
 212  0
                 return null;
 213  
             }
 214  0
             Properties p = new Properties();
 215  
             try
 216  
             {
 217  0
                 p.load(is);
 218  
             }
 219  0
             catch (IOException e)
 220  
             {
 221  0
                 throw new MuleRuntimeException(
 222  
                     MessageFactory.createStaticMessage("Failed to load Exception resources"), e);
 223  0
             }
 224  0
             errorMappings.put(protocol, p);
 225  0
             String applyTo = p.getProperty(APPLY_TO_PROPERTY, null);
 226  0
             if (applyTo != null)
 227  
             {
 228  0
                 String[] protocols = StringUtils.splitAndTrim(applyTo, ",");
 229  0
                 for (int i = 0; i < protocols.length; i++)
 230  
                 {
 231  0
                     errorMappings.put(protocols[i], p);
 232  
                 }
 233  
             }
 234  0
             return p;
 235  
         }
 236  
     }
 237  
 
 238  
     public static String getErrorCodePropertyName(String protocol)
 239  
     {
 240  0
         protocol = protocol.toLowerCase();
 241  0
         Properties mappings = getErrorMappings(protocol);
 242  0
         if (mappings == null)
 243  
         {
 244  0
             return null;
 245  
         }
 246  0
         return mappings.getProperty(ERROR_CODE_PROPERTY);
 247  
     }
 248  
 
 249  
     public static String getErrorMapping(String protocol, Class exception)
 250  
     {
 251  0
         protocol = protocol.toLowerCase();
 252  0
         Properties mappings = getErrorMappings(protocol);
 253  0
         if (mappings == null)
 254  
         {
 255  0
             logger.info("No mappings found for protocol: " + protocol);
 256  0
             return String.valueOf(getErrorCode(exception));
 257  
         }
 258  
 
 259  0
         Class clazz = exception;
 260  0
         String code = null;
 261  0
         while (!clazz.equals(Object.class))
 262  
         {
 263  0
             code = mappings.getProperty(clazz.getName());
 264  0
             if (code == null)
 265  
             {
 266  0
                 clazz = clazz.getSuperclass();
 267  
             }
 268  
             else
 269  
             {
 270  0
                 return code;
 271  
             }
 272  
         }
 273  0
         code = String.valueOf(getErrorCode(exception));
 274  
         // Finally lookup mapping based on error code and return the Mule error
 275  
         // code if a match is not found
 276  0
         return mappings.getProperty(code, code);
 277  
     }
 278  
 
 279  
     public static String getJavaDocUrl(Class exception)
 280  
     {
 281  270
         return getDocUrl("javadoc.", exception.getName());
 282  
     }
 283  
 
 284  
     public static String getDocUrl(Class exception)
 285  
     {
 286  270
         return getDocUrl("doc.", exception.getName());
 287  
     }
 288  
 
 289  
     private static String getDocUrl(String prefix, String packageName)
 290  
     {
 291  540
         String key = prefix;
 292  540
         if (packageName.startsWith("java.") || packageName.startsWith("javax."))
 293  
         {
 294  0
             key += J2SE_VERSION;
 295  
         }
 296  540
         String url = getUrl(key, packageName);
 297  540
         if (url == null && (packageName.startsWith("java.") || packageName.startsWith("javax.")))
 298  
         {
 299  0
             key = prefix + J2EE_VERSION;
 300  0
             url = getUrl(key, packageName);
 301  
         }
 302  540
         if (url != null)
 303  
         {
 304  270
             if (!url.endsWith("/"))
 305  
             {
 306  270
                 url += "/";
 307  
             }
 308  270
             String s = packageName.replaceAll("[.]", "/");
 309  270
             s += ".html";
 310  270
             url += s;
 311  
         }
 312  
 
 313  
         /*
 314  
          * If the exception is actually expected to occur by the calling code, the
 315  
          * following output becomes misleading when reading the logs. if
 316  
          * (logger.isDebugEnabled()) { if ("javadoc".equalsIgnoreCase(prefix)) {
 317  
          * logger.debug("Javadoc Url for package '" + packageName + "' is: " + url); }
 318  
          * else if ("doc".equalsIgnoreCase(prefix)) { logger.debug("Online Doc Url
 319  
          * for package '" + packageName + "' is: " + url); } else {
 320  
          * logger.debug(prefix + " Url for package '" + packageName + "' is: " +
 321  
          * url); } }
 322  
          */
 323  540
         return url;
 324  
     }
 325  
 
 326  
     private static String getUrl(String key, String packageName)
 327  
     {
 328  540
         String url = null;
 329  540
         if (!key.endsWith("."))
 330  
         {
 331  0
             key += ".";
 332  
         }
 333  2652
         while (packageName.length() > 0)
 334  
         {
 335  2382
             url = errorDocs.getProperty(key + packageName, null);
 336  2382
             if (url == null)
 337  
             {
 338  2112
                 int i = packageName.lastIndexOf(".");
 339  2112
                 if (i == -1)
 340  
                 {
 341  270
                     packageName = "";
 342  
                 }
 343  
                 else
 344  
                 {
 345  1842
                     packageName = packageName.substring(0, i);
 346  
                 }
 347  2112
             }
 348  
             else
 349  
             {
 350  
                 break;
 351  
             }
 352  
         }
 353  540
         return url;
 354  
     }
 355  
 
 356  
     public static Throwable getRootException(Throwable t)
 357  
     {
 358  0
         Throwable cause = t;
 359  0
         Throwable root = null;
 360  0
         while (cause != null)
 361  
         {
 362  0
             root = cause;
 363  0
             cause = getExceptionReader(cause).getCause(cause);
 364  
             // address some misbehaving exceptions, avoid endless loop
 365  0
             if (t == cause)
 366  
             {
 367  0
                 break;
 368  
             }
 369  
         }
 370  0
         return root;
 371  
     }
 372  
 
 373  
     public static Throwable getRootParentException(Throwable t)
 374  
     {
 375  0
         Throwable cause = t;
 376  0
         Throwable parent = t;
 377  0
         while (cause != null)
 378  
         {
 379  0
             if (cause.getCause() == null)
 380  
             {
 381  0
                 return parent;
 382  
             }
 383  0
             parent = cause;
 384  0
             cause = getExceptionReader(cause).getCause(cause);
 385  
             // address some misbehaving exceptions, avoid endless loop
 386  0
             if (t == cause)
 387  
             {
 388  0
                 break;
 389  
             }
 390  
         }
 391  0
         return t;
 392  
     }
 393  
 
 394  
     public static UMOException getRootMuleException(Throwable t)
 395  
     {
 396  10
         Throwable cause = t;
 397  10
         UMOException umoException = null;
 398  20
         while (cause != null)
 399  
         {
 400  10
             if (cause instanceof UMOException)
 401  
             {
 402  0
                 umoException = (UMOException) cause;
 403  
             }
 404  10
             cause = getExceptionReader(cause).getCause(cause);
 405  
             // address some misbehaving exceptions, avoid endless loop
 406  10
             if (t == cause)
 407  
             {
 408  0
                 break;
 409  
             }
 410  
         }
 411  10
         return umoException;
 412  
     }
 413  
 
 414  
     public static List getExceptionsAsList(Throwable t)
 415  
     {
 416  0
         List exceptions = new ArrayList();
 417  0
         Throwable cause = t;
 418  0
         while (cause != null)
 419  
         {
 420  0
             exceptions.add(0, cause);
 421  0
             cause = getExceptionReader(cause).getCause(cause);
 422  
             // address some misbehaving exceptions, avoid endless loop
 423  0
             if (t == cause)
 424  
             {
 425  0
                 break;
 426  
             }
 427  
         }
 428  0
         return exceptions;
 429  
     }
 430  
 
 431  
     public static Map getExceptionInfo(Throwable t)
 432  
     {
 433  0
         Map info = new HashMap();
 434  0
         Throwable cause = t;
 435  0
         while (cause != null)
 436  
         {
 437  0
             info.putAll(getExceptionReader(cause).getInfo(cause));
 438  0
             cause = getExceptionReader(cause).getCause(cause);
 439  
             // address some misbehaving exceptions, avoid endless loop
 440  0
             if (t == cause)
 441  
             {
 442  0
                 break;
 443  
             }
 444  
         }
 445  0
         return info;
 446  
     }
 447  
 
 448  
     public static String getExceptionStack(Throwable t)
 449  
     {
 450  0
         StringBuffer buf = new StringBuffer();
 451  
         // get exception stack
 452  0
         List exceptions = getExceptionsAsList(t);
 453  
 
 454  0
         int i = 1;
 455  0
         for (Iterator iterator = exceptions.iterator(); iterator.hasNext(); i++)
 456  
         {
 457  0
             if (i > exceptionThreshold && exceptionThreshold > 0)
 458  
             {
 459  0
                 buf.append("(").append(exceptions.size() - i + 1).append(" more...)");
 460  0
                 break;
 461  
             }
 462  0
             Throwable throwable = (Throwable) iterator.next();
 463  0
             ExceptionReader er = getExceptionReader(throwable);
 464  0
             buf.append(i).append(". ").append(er.getMessage(throwable)).append(" (");
 465  0
             buf.append(throwable.getClass().getName()).append(")\n");
 466  0
             if (verbose && throwable.getStackTrace().length > 0)
 467  
             {
 468  0
                 StackTraceElement e = throwable.getStackTrace()[0];
 469  0
                 buf.append("  ")
 470  
                     .append(e.getClassName())
 471  
                     .append(":")
 472  
                     .append(e.getLineNumber())
 473  
                     .append(" (")
 474  
                     .append(getJavaDocUrl(throwable.getClass()))
 475  
                     .append(")\n");
 476  
             }
 477  
         }
 478  0
         return buf.toString();
 479  
     }
 480  
 
 481  
     /**
 482  
      * Registers an exception reader with Mule
 483  
      *
 484  
      * @param reader the reader to register.
 485  
      */
 486  
     public static void registerExceptionReader(ExceptionReader reader)
 487  
     {
 488  4
         exceptionReaders.add(reader);
 489  4
     }
 490  
 
 491  
     /**
 492  
      * Gets an exception reader for the exception
 493  
      *
 494  
      * @param t the exception to get a reader for
 495  
      * @return either a specific reader or an instance of DefaultExceptionReader.
 496  
      *         This method never returns null;
 497  
      */
 498  
     public static ExceptionReader getExceptionReader(Throwable t)
 499  
     {
 500  10
         for (Iterator iterator = exceptionReaders.iterator(); iterator.hasNext();)
 501  
         {
 502  20
             ExceptionReader exceptionReader = (ExceptionReader) iterator.next();
 503  20
             if (exceptionReader.getExceptionType().isInstance(t))
 504  
             {
 505  0
                 return exceptionReader;
 506  
             }
 507  20
         }
 508  10
         return defaultExceptionReader;
 509  
     }
 510  
 
 511  
     public static String writeException(Throwable t)
 512  
     {
 513  0
         ExceptionReader er = getExceptionReader(t);
 514  0
         StringBuffer msg = new StringBuffer();
 515  0
         msg.append(er.getMessage(t)).append(". Type: ").append(t.getClass());
 516  0
         return msg.toString();
 517  
     }
 518  
 }