Search in sources :

Example 1 with CodeGenerationException

use of org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException in project powermock by powermock.

the class Enhancer method emitMethods.

private void emitMethods(final ClassEmitter ce, List methods, List actualMethods) {
    CallbackGenerator[] generators = CallbackInfo.getGenerators(callbackTypes);
    Map groups = new HashMap();
    final Map indexes = new HashMap();
    final Map originalModifiers = new HashMap();
    final Map positions = CollectionUtils.getIndexMap(methods);
    Iterator it1 = methods.iterator();
    Iterator it2 = (actualMethods != null) ? actualMethods.iterator() : null;
    while (it1.hasNext()) {
        MethodInfo method = (MethodInfo) it1.next();
        Method actualMethod = (it2 != null) ? (Method) it2.next() : null;
        int index = filter.accept(actualMethod, actualMethods);
        if (index >= callbackTypes.length) {
            throw new IllegalArgumentException("Callback filter returned an index that is too large: " + index);
        }
        originalModifiers.put(method, new Integer((actualMethod != null) ? actualMethod.getModifiers() : method.getModifiers()));
        indexes.put(method, new Integer(index));
        List group = (List) groups.get(generators[index]);
        if (group == null) {
            groups.put(generators[index], group = new ArrayList(methods.size()));
        }
        group.add(method);
    }
    Set seenGen = new HashSet();
    CodeEmitter se = ce.getStaticHook();
    se.new_instance(THREAD_LOCAL);
    se.dup();
    se.invoke_constructor(THREAD_LOCAL, CSTRUCT_NULL);
    se.putfield(THREAD_CALLBACKS_FIELD);
    final Object[] state = new Object[1];
    CallbackGenerator.Context context = new CallbackGenerator.Context() {

        public ClassLoader getClassLoader() {
            return Enhancer.this.getClassLoader();
        }

        public int getOriginalModifiers(MethodInfo method) {
            return ((Integer) originalModifiers.get(method)).intValue();
        }

        public int getIndex(MethodInfo method) {
            return ((Integer) indexes.get(method)).intValue();
        }

        public void emitCallback(CodeEmitter e, int index) {
            emitCurrentCallback(e, index);
        }

        public Signature getImplSignature(MethodInfo method) {
            return rename(method.getSignature(), ((Integer) positions.get(method)).intValue());
        }

        public CodeEmitter beginMethod(ClassEmitter ce, MethodInfo method) {
            CodeEmitter e = EmitUtils.begin_method(ce, method);
            if (!interceptDuringConstruction && !TypeUtils.isAbstract(method.getModifiers())) {
                Label constructed = e.make_label();
                e.load_this();
                e.getfield(CONSTRUCTED_FIELD);
                e.if_jump(e.NE, constructed);
                e.load_this();
                e.load_args();
                e.super_invoke();
                e.return_value();
                e.mark(constructed);
            }
            return e;
        }
    };
    for (int i = 0; i < callbackTypes.length; i++) {
        CallbackGenerator gen = generators[i];
        if (!seenGen.contains(gen)) {
            seenGen.add(gen);
            final List fmethods = (List) groups.get(gen);
            if (fmethods != null) {
                try {
                    gen.generate(ce, context, fmethods);
                    gen.generateStatic(se, context, fmethods);
                } catch (RuntimeException x) {
                    throw x;
                } catch (Exception x) {
                    throw new CodeGenerationException(x);
                }
            }
        }
    }
    se.return_value();
    se.end_method();
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ClassEmitter(org.powermock.api.mockito.repackaged.cglib.core.ClassEmitter) Label(org.powermock.api.mockito.repackaged.asm.Label) Method(java.lang.reflect.Method) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CodeEmitter(org.powermock.api.mockito.repackaged.cglib.core.CodeEmitter) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) Iterator(java.util.Iterator) MethodInfo(org.powermock.api.mockito.repackaged.cglib.core.MethodInfo) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 2 with CodeGenerationException

use of org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException in project powermock by powermock.

the class ClassImposterizer method createProxyClass.

public Class<Factory> createProxyClass(Class<?> mockedType, Class<?>... interfaces) {
    if (mockedType == Object.class) {
        mockedType = ClassWithSuperclassToWorkAroundCglibBug.class;
    }
    Enhancer enhancer = new Enhancer() {

        @Override
        @SuppressWarnings("unchecked")
        protected void filterConstructors(Class sc, List constructors) {
        // Don't filter
        }
    };
    Class<?>[] allMockedTypes = prepend(mockedType, interfaces);
    enhancer.setClassLoader(SearchingClassLoader.combineLoadersOf(allMockedTypes));
    enhancer.setUseFactory(true);
    if (mockedType.isInterface()) {
        enhancer.setSuperclass(Object.class);
        enhancer.setInterfaces(allMockedTypes);
    } else {
        enhancer.setSuperclass(mockedType);
        enhancer.setInterfaces(interfaces);
    }
    enhancer.setCallbackTypes(new Class[] { MethodInterceptor.class, NoOp.class });
    enhancer.setCallbackFilter(IGNORE_BRIDGE_METHODS);
    if (mockedType.getSigners() != null) {
        enhancer.setNamingPolicy(NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES);
    } else {
        enhancer.setNamingPolicy(MockitoNamingPolicy.INSTANCE);
    }
    enhancer.setSerialVersionUID(42L);
    try {
        return enhancer.createClass();
    } catch (CodeGenerationException e) {
        if (Modifier.isPrivate(mockedType.getModifiers())) {
            throw new MockitoException("\n" + "Mockito cannot mock this class: " + mockedType + ".\n" + "Most likely it is a private class that is not visible by Mockito");
        }
        throw new MockitoException("\n" + "Mockito cannot mock this class: " + mockedType + "\n" + "Mockito can only mock visible & non-final classes." + "\n" + "If you're not sure why you're getting this error, please report to the mailing list.", e);
    }
}
Also used : Enhancer(org.powermock.api.mockito.repackaged.cglib.proxy.Enhancer) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) MockitoException(org.mockito.exceptions.base.MockitoException) List(java.util.List)

Example 3 with CodeGenerationException

use of org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException in project powermock by powermock.

the class Enhancer method setCallbacksHelper.

private static void setCallbacksHelper(Class type, Callback[] callbacks, String methodName) {
    // TODO: optimize
    try {
        Method setter = getCallbacksSetter(type, methodName);
        setter.invoke(null, new Object[] { callbacks });
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(type + " is not an enhanced class");
    } catch (IllegalAccessException e) {
        throw new CodeGenerationException(e);
    } catch (InvocationTargetException e) {
        throw new CodeGenerationException(e);
    }
}
Also used : CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with CodeGenerationException

use of org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException in project powermock by powermock.

the class AbstractClassLoader method loadClass.

public Class loadClass(String name) throws ClassNotFoundException {
    Class loaded = findLoadedClass(name);
    if (loaded != null) {
        if (loaded.getClassLoader() == this) {
            return loaded;
        }
    //else reload with this class loader
    }
    if (!filter.accept(name)) {
        return super.loadClass(name);
    }
    ClassReader r;
    try {
        java.io.InputStream is = classPath.getResourceAsStream(name.replace('.', '/') + ".class");
        if (is == null) {
            throw new ClassNotFoundException(name);
        }
        try {
            r = new ClassReader(is);
        } finally {
            is.close();
        }
    } catch (IOException e) {
        throw new ClassNotFoundException(name + ":" + e.getMessage());
    }
    try {
        ClassWriter w = new DebuggingClassWriter(ClassWriter.COMPUTE_MAXS);
        getGenerator(r).generateClass(w);
        byte[] b = w.toByteArray();
        Class c = super.defineClass(name, b, 0, b.length, DOMAIN);
        postProcess(c);
        return c;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new CodeGenerationException(e);
    }
}
Also used : DebuggingClassWriter(org.powermock.api.mockito.repackaged.cglib.core.DebuggingClassWriter) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) ClassReader(org.powermock.api.mockito.repackaged.asm.ClassReader) IOException(java.io.IOException) ClassWriter(org.powermock.api.mockito.repackaged.asm.ClassWriter) DebuggingClassWriter(org.powermock.api.mockito.repackaged.cglib.core.DebuggingClassWriter) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) IOException(java.io.IOException)

Example 5 with CodeGenerationException

use of org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException in project powermock by powermock.

the class AddDelegateTransformer method addDelegate.

private void addDelegate(Method m) {
    Method delegate;
    try {
        delegate = delegateImpl.getMethod(m.getName(), m.getParameterTypes());
        if (!delegate.getReturnType().getName().equals(m.getReturnType().getName())) {
            throw new IllegalArgumentException("Invalid delegate signature " + delegate);
        }
    } catch (NoSuchMethodException e) {
        throw new CodeGenerationException(e);
    }
    final Signature sig = ReflectUtils.getSignature(m);
    Type[] exceptions = TypeUtils.getTypes(m.getExceptionTypes());
    CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, sig, exceptions);
    e.load_this();
    e.getfield(DELEGATE);
    e.load_args();
    e.invoke_virtual(delegateType, sig);
    e.return_value();
    e.end_method();
}
Also used : CodeEmitter(org.powermock.api.mockito.repackaged.cglib.core.CodeEmitter) Type(org.powermock.api.mockito.repackaged.asm.Type) CodeGenerationException(org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException) Signature(org.powermock.api.mockito.repackaged.cglib.core.Signature) Method(java.lang.reflect.Method)

Aggregations

CodeGenerationException (org.powermock.api.mockito.repackaged.cglib.core.CodeGenerationException)5 Method (java.lang.reflect.Method)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 List (java.util.List)2 CodeEmitter (org.powermock.api.mockito.repackaged.cglib.core.CodeEmitter)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 Set (java.util.Set)1 MockitoException (org.mockito.exceptions.base.MockitoException)1 ClassReader (org.powermock.api.mockito.repackaged.asm.ClassReader)1 ClassWriter (org.powermock.api.mockito.repackaged.asm.ClassWriter)1 Label (org.powermock.api.mockito.repackaged.asm.Label)1 Type (org.powermock.api.mockito.repackaged.asm.Type)1 ClassEmitter (org.powermock.api.mockito.repackaged.cglib.core.ClassEmitter)1 DebuggingClassWriter (org.powermock.api.mockito.repackaged.cglib.core.DebuggingClassWriter)1 MethodInfo (org.powermock.api.mockito.repackaged.cglib.core.MethodInfo)1