View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.commons.jcs.jcache.proxy;
20  
21  import java.lang.reflect.Constructor;
22  import java.lang.reflect.InvocationHandler;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Method;
25  import java.lang.reflect.Proxy;
26  
27  public class ExceptionWrapperHandler<T> implements InvocationHandler
28  {
29      private final T delegate;
30      private final Constructor<? extends RuntimeException> wrapper;
31  
32      public ExceptionWrapperHandler(final T delegate, final Class<? extends RuntimeException> exceptionType)
33      {
34          this.delegate = delegate;
35          try
36          {
37              this.wrapper = exceptionType.getConstructor(Throwable.class);
38          }
39          catch (final NoSuchMethodException e)
40          {
41              throw new IllegalStateException(e);
42          }
43      }
44  
45      @Override
46      public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
47      {
48          try
49          {
50              return method.invoke(delegate, args);
51          }
52          catch (final InvocationTargetException ite)
53          {
54              final Throwable e = ite.getCause();
55              if (RuntimeException.class.isInstance(e))
56              {
57                  final RuntimeException re;
58                  try
59                  {
60                      re = wrapper.newInstance(e);
61                  }
62                  catch (final Exception e1)
63                  {
64                      throw new IllegalArgumentException(e1);
65                  }
66                  throw re;
67              }
68              throw e;
69          }
70      }
71  
72      public static <T> T newProxy(final ClassLoader loader, final T delegate, final Class<? extends RuntimeException> exceptionType,
73              final Class<T> apis)
74      {
75          return (T) Proxy.newProxyInstance(loader, new Class<?>[] { apis }, new ExceptionWrapperHandler<T>(delegate, exceptionType));
76      }
77  }