View Javadoc

1   /**
2    * This file Copyright (c) 2009-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.util;
35  
36  import org.apache.commons.lang.StringUtils;
37  
38  /**
39   * Util to handle exceptions.
40   *
41   * @version $Revision: $ ($Author: $)
42   */
43  public class ExceptionUtil {
44  
45      /**
46       * Given a RuntimeException, this method will:
47       * - throw its cause exception, if the cause exception is an instance of the type of the unwrapIf parameter
48       * - throw its cause exception, if the cause exception is a RuntimeException
49       * - throw the given RuntimeException otherwise.
50       */
51      public static <E extends Throwable> void unwrapIf(RuntimeException e, Class<E> unwrapIf) throws E {
52          final Throwable wrapped = e.getCause();
53          if (unwrapIf != null && unwrapIf.isInstance(wrapped)) {
54              throw (E) wrapped;
55          } else if (wrapped != null && wrapped instanceof RuntimeException) {
56              throw (RuntimeException) wrapped;
57          } else {
58              throw e;
59          }
60      }
61  
62      /**
63       * This method helps palliating the absence of multi-catch (introduced in Java 7) - catch the lower common
64       * denominator exception and let this method do the rest - <strong>Use with great care!</strong>.
65       * <strong>Warning:</strong> this method can be abused, and would let one throw undeclared exceptions, which would
66       * in turn produce unexpected and undesirable effects on calling code. Just resist the urge to use this outside
67       * "multi-catch" scenarios.
68       */
69      @SuppressWarnings("unchecked")
70      public static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions) {
71          if (RuntimeException.class.isInstance(e)) {
72              throw (RuntimeException) e;
73          }
74          for (Class<? extends Throwable> allowedException : allowedExceptions) {
75              if (allowedException.isInstance(e)) {
76                  sneakyThrow(e);
77              }
78          }
79          throw new Error("Caught the following exception, which was not allowed: ", e);
80      }
81  
82      /**
83       * Highly inspired by Lombok and the JavaPuzzlers, this method will let you throw a checked exception without declaring it.
84       * Use with GREAT care.
85       */
86      private static void sneakyThrow(Throwable t) {
87          ExceptionUtil.<RuntimeException>sneakyThrow_(t);
88      }
89  
90      @SuppressWarnings("unchecked")
91      private static <T extends Throwable> void sneakyThrow_(Throwable t) throws T {
92          throw (T) t;
93      }
94  
95      /**
96       * Returns true if the given exception or any of the nested cause exceptions is an instance of the <tt>suspectedCause</tt> exception argument, or a subclass thereof.
97       * This is equivalent to ExceptionUtils.indexOfThrowable(e, javax.jcr.AccessDeniedException.class) >= 0, only more readable, and possibly more performant.
98       */
99      public static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause) {
100         if (e != null && suspectedCause.isAssignableFrom(e.getClass())) {
101             return true;
102         } else if (e == null) {
103             return false;
104         } else {
105             return wasCausedBy(e.getCause(), suspectedCause);
106         }
107     }
108 
109     /**
110      * Translates an exception class name to an english-readable idiom. Example: an instance of AccessDeniedException will be returned as "Access denied".
111      */
112     public static String classNameToWords(Exception e) {
113         return StringUtils.capitalize(StringUtils.removeEnd(e.getClass().getSimpleName(), "Exception").replaceAll("[A-Z]", " $0").toLowerCase().trim());
114     }
115 
116     /**
117      * Translates an exception class name to an english-readable idiom, along with the exception's message.
118      * Example: an instance of AccessDeniedException("/foo/bar") will be returned as "Access denied: /foo/bar".
119      */
120     public static String exceptionToWords(Exception e) {
121         if (e.getMessage() != null) {
122             return classNameToWords(e) + ": " + e.getMessage();
123         } else {
124             return classNameToWords(e);
125         }
126     }
127 }