001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.commons.jcs3.jcache.proxy; 020 021import java.lang.reflect.Constructor; 022import java.lang.reflect.InvocationHandler; 023import java.lang.reflect.InvocationTargetException; 024import java.lang.reflect.Method; 025import java.lang.reflect.Proxy; 026 027public class ExceptionWrapperHandler<T> implements InvocationHandler 028{ 029 private final T delegate; 030 private final Constructor<? extends RuntimeException> wrapper; 031 032 public ExceptionWrapperHandler(final T delegate, final Class<? extends RuntimeException> exceptionType) 033 { 034 this.delegate = delegate; 035 try 036 { 037 this.wrapper = exceptionType.getConstructor(Throwable.class); 038 } 039 catch (final NoSuchMethodException e) 040 { 041 throw new IllegalStateException(e); 042 } 043 } 044 045 @Override 046 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable 047 { 048 try 049 { 050 return method.invoke(delegate, args); 051 } 052 catch (final InvocationTargetException ite) 053 { 054 final Throwable e = ite.getCause(); 055 if (RuntimeException.class.isInstance(e)) 056 { 057 final RuntimeException re; 058 try 059 { 060 re = wrapper.newInstance(e); 061 } 062 catch (final Exception e1) 063 { 064 throw new IllegalArgumentException(e1); 065 } 066 throw re; 067 } 068 throw e; 069 } 070 } 071 072 public static <T> T newProxy(final ClassLoader loader, final T delegate, final Class<? extends RuntimeException> exceptionType, 073 final Class<T> apis) 074 { 075 return (T) Proxy.newProxyInstance(loader, new Class<?>[] { apis }, new ExceptionWrapperHandler<>(delegate, exceptionType)); 076 } 077}