001/**
002 * Copyright (C) 2011 rwoo@gmx.de
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *         http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.googlecode.catchexception.throwable.internal;
017
018import java.lang.reflect.Method;
019
020import org.mockito.cglib.proxy.MethodInterceptor;
021import org.mockito.cglib.proxy.MethodProxy;
022import org.mockito.internal.creation.DelegatingMockitoMethodProxy;
023import org.mockito.internal.creation.cglib.CGLIBHacker;
024
025/**
026 * This {@link AbstractThrowableProcessingInvocationHandler} implements {@link MethodInterceptor} for Mockito's cglib
027 * variant.
028 * 
029 * @author rwoo, federico.gaule at gmail.com
030 * @param <E>
031 *            The type of the throwable that shall be caught and (optionally) verified
032 */
033public class ThrowableProcessingInterceptor<E extends Throwable> extends
034        AbstractThrowableProcessingInvocationHandler<E> implements MethodInterceptor {
035
036    /**
037     * We use this object to change the naming policy that is used by {@link MethodProxy#helper}. The new naming policy
038     * avoids duplicate class definitions.
039     */
040    private CGLIBHacker cglibHacker = new CGLIBHacker();
041
042    @SuppressWarnings("javadoc")
043    public ThrowableProcessingInterceptor(Object target, Class<E> clazz, boolean assertThrowable) {
044        super(target, clazz, assertThrowable);
045    }
046
047    /*
048     * (non-Javadoc)
049     * 
050     * @see org.mockito.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method,
051     * java.lang.Object[], org.mockito.cglib.proxy.MethodProxy)
052     */
053    @Override
054    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
055
056        beforeInvocation();
057
058        cglibHacker.setMockitoNamingPolicy(new DelegatingMockitoMethodProxy(proxy));
059
060        try {
061
062            method.setAccessible(true);
063
064            Object retval = method.invoke(target, args);
065
066            return afterInvocation(retval);
067
068        } catch (Throwable e) {
069
070            return afterInvocationThrowsThrowable(e, method);
071
072        } finally {
073
074            method.setAccessible(false);
075
076        }
077    }
078}