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.Modifier;
019
020import org.mockito.cglib.proxy.MethodInterceptor;
021import org.mockito.exceptions.base.MockitoException;
022import org.mockito.internal.creation.jmock.ClassImposterizer;
023
024/**
025 * This {@link ProxyFactory} uses Mockito's jmock package to create proxies that
026 * subclass from the target's class.
027 *
028 * @author rwoo
029 */
030public class SubclassProxyFactory implements ProxyFactory {
031
032    /**
033     * That proxy factory is used if this factory cannot be used.
034     */
035    private ProxyFactory fallbackProxyFactory = new InterfaceOnlyProxyFactory();
036
037    /*
038     * (non-Javadoc)
039     * 
040     * @see
041     * com.googlecode.catchexception.internal.ProxyFactory#createProxy(java.
042     * lang.Object, java.lang.Class, boolean)
043     */
044    @SuppressWarnings("unchecked")
045    public <T> T createProxy(Class<?> targetClass, MethodInterceptor interceptor) {
046
047        // can we subclass the class of the target?
048        if (!isTypeMockable(targetClass)) {
049
050            // delegate
051            return fallbackProxyFactory.<T>createProxy(targetClass,
052                    interceptor);
053        }
054
055        // create proxy
056        T proxy;
057        try {
058
059            proxy = (T) ClassImposterizer.INSTANCE.imposterise(interceptor,
060                    targetClass);
061
062        } catch (MockitoException e) {
063
064            // delegate
065            return fallbackProxyFactory.<T>createProxy(targetClass,
066                    interceptor);
067        }
068
069        return proxy;
070    }
071
072    public boolean isTypeMockable(Class<?> type) {
073        return !type.isPrimitive() && !Modifier.isFinal(type.getModifiers());
074    }
075}