Search in sources :

Example 76 with NotFoundException

use of javassist.NotFoundException in project hibernate-orm by hibernate.

the class EntityEnhancer method collectInheritCollectionFields.

private Collection<CtField> collectInheritCollectionFields(CtClass managedCtClass) {
    if (managedCtClass == null || Object.class.getName().equals(managedCtClass.getName())) {
        return Collections.emptyList();
    }
    try {
        CtClass managedCtSuperclass = managedCtClass.getSuperclass();
        if (!enhancementContext.isMappedSuperclassClass(managedCtSuperclass)) {
            return collectInheritCollectionFields(managedCtSuperclass);
        }
        List<CtField> collectionList = new ArrayList<CtField>();
        for (CtField ctField : managedCtSuperclass.getDeclaredFields()) {
            if (!Modifier.isStatic(ctField.getModifiers())) {
                if (enhancementContext.isPersistentField(ctField) && !enhancementContext.isMappedCollection(ctField)) {
                    if (PersistentAttributesHelper.isAssignable(ctField, Collection.class.getName()) || PersistentAttributesHelper.isAssignable(ctField, Map.class.getName())) {
                        collectionList.add(ctField);
                    }
                }
            }
        }
        collectionList.addAll(collectInheritCollectionFields(managedCtSuperclass));
        return collectionList;
    } catch (NotFoundException nfe) {
        return Collections.emptyList();
    }
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ArrayList(java.util.ArrayList) NotFoundException(javassist.NotFoundException)

Example 77 with NotFoundException

use of javassist.NotFoundException in project core-ng-project by neowu.

the class DynamicInstanceBuilder method constructor.

public void constructor(Class<?>[] constructorParamClasses, String body) {
    if (this.constructorParamClasses != null)
        throw new Error("dynamic class must have no more than one custom constructor");
    sourceCode.constructorParamClasses = constructorParamClasses;
    sourceCode.constructorBody = body;
    try {
        this.constructorParamClasses = constructorParamClasses;
        CtClass[] params = new CtClass[constructorParamClasses.length];
        for (int i = 0; i < constructorParamClasses.length; i++) {
            Class<?> paramClass = constructorParamClasses[i];
            params[i] = classPool.getCtClass(paramClass.getCanonicalName());
        }
        CtConstructor constructor = new CtConstructor(params, classBuilder);
        constructor.setBody(body);
        classBuilder.addConstructor(constructor);
    } catch (CannotCompileException | NotFoundException e) {
        logger.error("constructor body failed to compile:\n{}", body);
        throw new CodeCompileException(e);
    }
}
Also used : CtClass(javassist.CtClass) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtConstructor(javassist.CtConstructor)

Example 78 with NotFoundException

use of javassist.NotFoundException in project BroadleafCommerce by BroadleafCommerce.

the class DirectCopyClassTransformer method transform.

@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    // Lambdas and anonymous methods in Java 8 do not have a class name defined and so no transformation should be done
    if (className == null) {
        return null;
    }
    // Be careful with Apache library usage in this class (e.g. ArrayUtils). Usage will likely cause a ClassCircularityError
    // under JRebel. Favor not including outside libraries and unnecessary classes.
    CtClass clazz = null;
    try {
        boolean mySkipOverlaps = skipOverlaps;
        boolean myRenameMethodOverlaps = renameMethodOverlaps;
        String convertedClassName = className.replace('/', '.');
        ClassPool classPool = null;
        String xformKey = convertedClassName;
        Set<String> buildXFormVals = new HashSet<>();
        Boolean[] xformSkipOverlaps = null;
        Boolean[] xformRenameMethodOverlaps = null;
        if (!xformTemplates.isEmpty()) {
            if (xformTemplates.containsKey(xformKey)) {
                buildXFormVals.addAll(Arrays.asList(xformTemplates.get(xformKey).split(",")));
                classPool = ClassPool.getDefault();
                clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
            }
        } else {
            if (annotationTransformedClasses.contains(convertedClassName)) {
                logger.warn(convertedClassName + " has already been transformed by a previous instance of DirectCopyTransfomer. " + "Skipping this annotation based transformation. Generally, annotation-based transformation is handled " + "by bean id blAnnotationDirectCopyClassTransformer with template tokens being added to " + "blDirectCopyTransformTokenMap via EarlyStageMergeBeanPostProcessor.");
            }
            boolean isValidPattern = true;
            List<DirectCopyIgnorePattern> matchedPatterns = new ArrayList<>();
            for (DirectCopyIgnorePattern pattern : ignorePatterns) {
                boolean isPatternMatch = false;
                for (String patternString : pattern.getPatterns()) {
                    isPatternMatch = convertedClassName.matches(patternString);
                    if (isPatternMatch) {
                        break;
                    }
                }
                if (isPatternMatch) {
                    matchedPatterns.add(pattern);
                }
                isValidPattern = !(isPatternMatch && pattern.getTemplateTokenPatterns() == null);
                if (!isValidPattern) {
                    return null;
                }
            }
            if (isValidPattern) {
                classPool = ClassPool.getDefault();
                clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
                XFormParams params = reviewDirectCopyTransformAnnotations(clazz, mySkipOverlaps, myRenameMethodOverlaps, matchedPatterns);
                XFormParams conditionalParams = reviewConditionalDirectCopyTransforms(convertedClassName, matchedPatterns);
                if (conditionalParams != null && !conditionalParams.isEmpty()) {
                    params = combineXFormParams(params, conditionalParams);
                }
                if (params.getXformVals() != null && params.getXformVals().length > 0) {
                    buildXFormVals.addAll(Arrays.asList(params.getXformVals()));
                }
                xformSkipOverlaps = params.getXformSkipOverlaps();
                xformRenameMethodOverlaps = params.getXformRenameMethodOverlaps();
            }
        }
        if (buildXFormVals.size() > 0) {
            String[] xformVals = buildXFormVals.toArray(new String[buildXFormVals.size()]);
            logger.debug(String.format("[%s] - Transform - Copying into [%s] from [%s]", LifeCycleEvent.END, xformKey, StringUtils.join(xformVals, ",")));
            // Load the destination class and defrost it so it is eligible for modifications
            clazz.defrost();
            int index = 0;
            for (String xformVal : xformVals) {
                // Load the source class
                String trimmed = xformVal.trim();
                classPool.appendClassPath(new LoaderClassPath(Class.forName(trimmed).getClassLoader()));
                CtClass template = classPool.get(trimmed);
                // Add in extra interfaces
                CtClass[] interfacesToCopy = template.getInterfaces();
                for (CtClass i : interfacesToCopy) {
                    checkInterfaces: {
                        CtClass[] myInterfaces = clazz.getInterfaces();
                        for (CtClass myInterface : myInterfaces) {
                            if (myInterface.getName().equals(i.getName())) {
                                if (xformSkipOverlaps != null && xformSkipOverlaps[index]) {
                                    break checkInterfaces;
                                } else {
                                    throw new RuntimeException("Duplicate interface detected " + myInterface.getName());
                                }
                            }
                        }
                        logger.debug(String.format("Adding interface [%s]", i.getName()));
                        clazz.addInterface(i);
                    }
                }
                // copy over any EntityListeners
                ClassFile classFile = clazz.getClassFile();
                ClassFile templateFile = template.getClassFile();
                ConstPool constantPool = classFile.getConstPool();
                buildClassLevelAnnotations(classFile, templateFile, constantPool);
                // Copy over all declared fields from the template class
                // Note that we do not copy over fields with the @NonCopiedField annotation
                CtField[] fieldsToCopy = template.getDeclaredFields();
                for (CtField field : fieldsToCopy) {
                    if (field.hasAnnotation(NonCopied.class)) {
                        logger.debug(String.format("Not adding field [%s]", field.getName()));
                    } else {
                        try {
                            CtField ctField = clazz.getDeclaredField(field.getName());
                            String originalSignature = ctField.getSignature();
                            String mySignature = field.getSignature();
                            if (!originalSignature.equals(mySignature)) {
                                throw new IllegalArgumentException("Field with name (" + field.getName() + ") and signature " + "(" + field.getSignature() + ") is targeted for weaving into (" + clazz.getName() + "). " + "An incompatible field of the same name and signature of (" + ctField.getSignature() + ") " + "already exists. The field in the target class should be updated to a different name, " + "or made to have a matching type.");
                            }
                            if (xformSkipOverlaps != null && xformSkipOverlaps[index]) {
                                logger.debug(String.format("Skipping overlapped field [%s]", field.getName()));
                                continue;
                            }
                            clazz.removeField(ctField);
                        } catch (NotFoundException e) {
                        // do nothing -- field does not exist
                        }
                        logger.debug(String.format("Adding field [%s]", field.getName()));
                        CtField copiedField = new CtField(field, clazz);
                        boolean defaultConstructorFound = false;
                        String implClass = getImplementationType(field.getType().getName());
                        // if there is one that takes zero parameters
                        try {
                            CtConstructor[] implConstructors = classPool.get(implClass).getConstructors();
                            if (implConstructors != null) {
                                for (CtConstructor cons : implConstructors) {
                                    if (cons.getParameterTypes().length == 0) {
                                        defaultConstructorFound = true;
                                        break;
                                    }
                                }
                            }
                        } catch (NotFoundException e) {
                        // Do nothing -- if we don't find this implementation, it's probably because it's
                        // an array. In this case, we will not initialize the field.
                        }
                        if (defaultConstructorFound) {
                            clazz.addField(copiedField, "new " + implClass + "()");
                        } else {
                            clazz.addField(copiedField);
                        }
                    }
                }
                // Copy over all declared methods from the template class
                CtMethod[] methodsToCopy = template.getDeclaredMethods();
                for (CtMethod method : methodsToCopy) {
                    if (method.hasAnnotation(NonCopied.class)) {
                        logger.debug(String.format("Not adding method [%s]", method.getName()));
                    } else {
                        try {
                            CtClass[] paramTypes = method.getParameterTypes();
                            CtMethod originalMethod = clazz.getDeclaredMethod(method.getName(), paramTypes);
                            if (xformSkipOverlaps != null && xformSkipOverlaps[index]) {
                                logger.debug(String.format("Skipping overlapped method [%s]", methodDescription(originalMethod)));
                                continue;
                            }
                            if (transformedMethods.contains(methodDescription(originalMethod))) {
                                throw new RuntimeException("Method already replaced " + methodDescription(originalMethod));
                            } else {
                                logger.debug(String.format("Marking as replaced [%s]", methodDescription(originalMethod)));
                                transformedMethods.add(methodDescription(originalMethod));
                            }
                            logger.debug(String.format("Removing method [%s]", method.getName()));
                            if (xformRenameMethodOverlaps != null && xformRenameMethodOverlaps[index]) {
                                originalMethod.setName(renameMethodPrefix + method.getName());
                            } else {
                                clazz.removeMethod(originalMethod);
                            }
                        } catch (NotFoundException e) {
                        // Do nothing -- we don't need to remove a method because it doesn't exist
                        }
                        logger.debug(String.format("Adding method [%s]", method.getName()));
                        CtMethod copiedMethod = new CtMethod(method, clazz, null);
                        clazz.addMethod(copiedMethod);
                    }
                }
                index++;
            }
            if (xformTemplates.isEmpty()) {
                annotationTransformedClasses.add(convertedClassName);
            }
            logger.debug(String.format("[%s] - Transform - Copying into [%s] from [%s]", LifeCycleEvent.END, xformKey, StringUtils.join(xformVals, ",")));
            return clazz.toBytecode();
        }
    } catch (ClassCircularityError error) {
        error.printStackTrace();
        throw error;
    } catch (Exception e) {
        throw new RuntimeException("Unable to transform class", e);
    } finally {
        if (clazz != null) {
            try {
                clazz.detach();
            } catch (Exception e) {
            // do nothing
            }
        }
    }
    return null;
}
Also used : ConstPool(javassist.bytecode.ConstPool) ClassPool(javassist.ClassPool) ArrayList(java.util.ArrayList) NotFoundException(javassist.NotFoundException) CtField(javassist.CtField) HashSet(java.util.HashSet) ClassFile(javassist.bytecode.ClassFile) LoaderClassPath(javassist.LoaderClassPath) NotFoundException(javassist.NotFoundException) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) CtMethod(javassist.CtMethod)

Example 79 with NotFoundException

use of javassist.NotFoundException in project javassist-maven-plugin by icon-Systemhaus-GmbH.

the class TestJavassistTransformerExecuter method removeStamp_ignores_internal_NotFoundException.

@Test
public void removeStamp_ignores_internal_NotFoundException() throws CannotCompileException, NotFoundException {
    // given
    final String className = "test.TestClass";
    final NotFoundException internalException = new NotFoundException("expected exception");
    final CtClass candidateClass = mock("candidateClass", CtClass.class);
    // createStampField
    expect(candidateClass.isInterface()).andReturn(false);
    expect(candidateClass.getClassPool()).andReturn(classPool).anyTimes();
    expect(candidateClass.getClassFile2()).andReturn(new ClassFile(false, className, null));
    expect(candidateClass.isFrozen()).andReturn(false);
    expect(candidateClass.getName()).andReturn(className).anyTimes();
    final Capture<CtField> fieldCaptures = newInstance();
    candidateClass.removeField(capture(fieldCaptures));
    EasyMock.expectLastCall().andThrow(internalException);
    replay(candidateClass, classPool);
    // when
    sut.removeStamp(candidateClass);
    // then
    verify(candidateClass, classPool);
    assertThat("generated stamp field starts with the constant prefix.", fieldCaptures.getValue().getName(), org.hamcrest.core.StringStartsWith.startsWith(JavassistTransformerExecutor.STAMP_FIELD_NAME));
    assertThat("generated stamp field must have the right modifiers.", fieldCaptures.getValue().getModifiers(), is(STATIC | FINAL | PRIVATE));
    assertThat("generated stamp field is a boolean.", fieldCaptures.getValue().getType(), is(booleanType));
}
Also used : CtClass(javassist.CtClass) ClassFile(javassist.bytecode.ClassFile) CtField(javassist.CtField) NotFoundException(javassist.NotFoundException) Test(org.junit.Test)

Example 80 with NotFoundException

use of javassist.NotFoundException in project gwt-test-utils by gwt-test-utils.

the class ClassesScanner method visitClass.

private void visitClass(String classFileName, ClassVisitor classVisitor) {
    try {
        CtClass current = GwtClassPool.getClass(classFileName.substring(0, classFileName.length() - ".class".length()));
        classVisitor.visit(current);
        for (CtClass innerClass : current.getNestedClasses()) {
            classVisitor.visit(innerClass);
        }
    } catch (NotFoundException e) {
    // do nothing
    }
}
Also used : CtClass(javassist.CtClass) NotFoundException(javassist.NotFoundException)

Aggregations

NotFoundException (javassist.NotFoundException)88 CtClass (javassist.CtClass)64 CannotCompileException (javassist.CannotCompileException)42 CtMethod (javassist.CtMethod)36 ClassPool (javassist.ClassPool)32 IOException (java.io.IOException)19 CtField (javassist.CtField)16 FileNotFoundException (java.io.FileNotFoundException)9 CtConstructor (javassist.CtConstructor)9 File (java.io.File)7 Method (java.lang.reflect.Method)7 ClassFile (javassist.bytecode.ClassFile)7 ArrayList (java.util.ArrayList)6 Collectors (java.util.stream.Collectors)6 BadBytecode (javassist.bytecode.BadBytecode)6 EnhancementException (org.hibernate.bytecode.enhance.spi.EnhancementException)5 MethodUsage (com.github.javaparser.resolution.MethodUsage)4 UnsolvedSymbolException (com.github.javaparser.resolution.UnsolvedSymbolException)4 ResolvedReferenceType (com.github.javaparser.resolution.types.ResolvedReferenceType)4 Context (com.github.javaparser.symbolsolver.core.resolution.Context)4