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.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 AbstractExceptionProcessingInvocationHandler} implements
027 * {@link MethodInterceptor} for Mockito's cglib variant.
028 * 
029 * @author rwoo, federico.gaule at gmail.com
030 * @param <E>
031 *            The type of the exception that shall be caught and (optionally)
032 *            verified
033 */
034public class ExceptionProcessingInterceptor<E extends Exception> extends
035        AbstractExceptionProcessingInvocationHandler<E> implements
036        MethodInterceptor {
037
038    /**
039     * We use this object to change the naming policy that is used by
040     * {@link MethodProxy#helper}. The new naming policy avoids duplicate class
041     * definitions.
042     */
043    private CGLIBHacker cglibHacker = new CGLIBHacker();
044
045    @SuppressWarnings("javadoc")
046    public ExceptionProcessingInterceptor(Object target, Class<E> clazz,
047            boolean assertException) {
048        super(target, clazz, assertException);
049    }
050
051    /*
052     * (non-Javadoc)
053     * 
054     * @see
055     * org.mockito.cglib.proxy.MethodInterceptor#intercept(java.lang.Object,
056     * java.lang.reflect.Method, java.lang.Object[],
057     * org.mockito.cglib.proxy.MethodProxy)
058     */
059    @Override
060    public Object intercept(Object obj, Method method, Object[] args,
061            MethodProxy proxy) throws Throwable {
062
063        beforeInvocation();
064
065        cglibHacker.setMockitoNamingPolicy(new DelegatingMockitoMethodProxy(
066                proxy));
067
068        try {
069
070            method.setAccessible(true);
071
072            Object retval = method.invoke(target, args);
073
074            return afterInvocation(retval);
075
076        } catch (Exception e) {
077
078            return afterInvocationThrowsException(e, method);
079
080        } finally {
081
082            method.setAccessible(false);
083
084        }
085    }
086}