View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.util;
8   
9   import java.util.List;
10  import java.util.ListIterator;
11  
12  /**
13   * Mule exception utilities.
14   */
15  public class ExceptionUtils extends org.apache.commons.lang.exception.ExceptionUtils
16  {
17  
18      /**
19       * This method returns true if the throwable contains a {@link Throwable} that
20       * matches the specified class or subclass in the exception chain. Subclasses of
21       * the specified class do match.
22       * 
23       * @param throwable the throwable to inspect, may be null
24       * @param type the type to search for, subclasses match, null returns false
25       * @return the index into the throwable chain, false if no match or null input
26       */
27      public static boolean containsType(Throwable throwable, Class<?> type)
28      {
29          return indexOfType(throwable, type) > -1;
30      }
31  
32      /**
33       * This method returns the throwable closest to the root cause that matches the
34       * specified class or subclass. Any null argument will make the method return
35       * null.
36       * 
37       * @param throwable the throwable to inspect, may be null
38       * @param type the type to search for, subclasses match, null returns null
39       * @return the throwablethat is closest to the root in the throwable chain that
40       *         matches the type or subclass of that type.
41       */
42      public static Throwable getDeepestOccurenceOfType(Throwable throwable, Class<?> type)
43      {
44          if (throwable == null || type == null)
45          {
46              return null;
47          }
48          @SuppressWarnings("unchecked")
49          List<Throwable> throwableList = getThrowableList(throwable);
50          ListIterator<Throwable> listIterator = throwableList.listIterator(throwableList.size());
51          while (listIterator.hasPrevious())
52          {
53              Throwable candidate = listIterator.previous();
54              if (type.isAssignableFrom(candidate.getClass()))
55              {
56                  return candidate;
57              }
58          }
59          return null;
60      }
61  }