Search in sources :

Example 16 with Annotation

use of javassist.bytecode.annotation.Annotation in project ignite by apache.

the class IgniteExamplesMLTestSuite method makeTestClass.

/**
 * Creates test class for given example.
 *
 * @param exampleCls Class of the example to be tested.
 * @return Test class.
 */
private static Class<?> makeTestClass(Class<?> exampleCls) {
    ClassPool cp = ClassPool.getDefault();
    cp.insertClassPath(new ClassClassPath(IgniteExamplesMLTestSuite.class));
    CtClass cl = cp.makeClass(basePkgForTests + "." + exampleCls.getSimpleName() + "SelfTest");
    try {
        cl.setSuperclass(cp.get(GridAbstractExamplesTest.class.getName()));
        CtMethod mtd = CtNewMethod.make("public void testExample() { " + exampleCls.getCanonicalName() + ".main(" + MLExamplesCommonArgs.class.getName() + ".EMPTY_ARGS_ML); }", cl);
        // Create and add annotation.
        ClassFile ccFile = cl.getClassFile();
        ConstPool constpool = ccFile.getConstPool();
        AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        Annotation annot = new Annotation("org.junit.Test", constpool);
        attr.addAnnotation(annot);
        mtd.getMethodInfo().addAttribute(attr);
        cl.addMethod(mtd);
        return cl.toClass();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : CtClass(javassist.CtClass) ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) MLExamplesCommonArgs(org.apache.ignite.examples.ml.util.MLExamplesCommonArgs) ClassClassPath(javassist.ClassClassPath) CtMethod(javassist.CtMethod) Annotation(javassist.bytecode.annotation.Annotation) IOException(java.io.IOException)

Example 17 with Annotation

use of javassist.bytecode.annotation.Annotation in project audit4j-core by audit4j.

the class AnnotationDB method scanMethods.

/**
 * Scanns both the method and its parameters for annotations.
 *
 * @param cf
 */
protected void scanMethods(ClassFile cf) {
    List<ClassFile> methods = cf.getMethods();
    if (methods == null)
        return;
    for (Object obj : methods) {
        MethodInfo method = (MethodInfo) obj;
        if (scanMethodAnnotations) {
            AnnotationsAttribute visible = (AnnotationsAttribute) method.getAttribute(AnnotationsAttribute.visibleTag);
            AnnotationsAttribute invisible = (AnnotationsAttribute) method.getAttribute(AnnotationsAttribute.invisibleTag);
            if (visible != null)
                populate(visible.getAnnotations(), cf.getName());
            if (invisible != null)
                populate(invisible.getAnnotations(), cf.getName());
        }
        if (scanParameterAnnotations) {
            ParameterAnnotationsAttribute paramsVisible = (ParameterAnnotationsAttribute) method.getAttribute(ParameterAnnotationsAttribute.visibleTag);
            ParameterAnnotationsAttribute paramsInvisible = (ParameterAnnotationsAttribute) method.getAttribute(ParameterAnnotationsAttribute.invisibleTag);
            if (paramsVisible != null && paramsVisible.getAnnotations() != null) {
                for (Annotation[] anns : paramsVisible.getAnnotations()) {
                    populate(anns, cf.getName());
                }
            }
            if (paramsInvisible != null && paramsInvisible.getAnnotations() != null) {
                for (Annotation[] anns : paramsInvisible.getAnnotations()) {
                    populate(anns, cf.getName());
                }
            }
        }
    }
}
Also used : ClassFile(javassist.bytecode.ClassFile) ParameterAnnotationsAttribute(javassist.bytecode.ParameterAnnotationsAttribute) ParameterAnnotationsAttribute(javassist.bytecode.ParameterAnnotationsAttribute) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) MethodInfo(javassist.bytecode.MethodInfo) Annotation(javassist.bytecode.annotation.Annotation)

Example 18 with Annotation

use of javassist.bytecode.annotation.Annotation in project coprhd-controller by CoprHD.

the class DbSchemaChanger method removeAnnotation.

/**
 * remove an annotation from a method
 *
 * @param methodName the method to which the annotation to be removed
 * @param annotationName the annotation name, it should be a full name
 */
public DbSchemaChanger removeAnnotation(String methodName, String annotationName) throws Exception {
    // looking for the method to apply the annotation on
    CtMethod methodDescriptor = cc.getDeclaredMethod(methodName);
    // create the annotation
    ClassFile ccFile = cc.getClassFile();
    ccFile.setVersionToJava5();
    ConstPool constpool = ccFile.getConstPool();
    MethodInfo minfo = methodDescriptor.getMethodInfo();
    AnnotationsAttribute attr = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag);
    Annotation[] annotations = attr.getAnnotations();
    List<Annotation> list = new ArrayList();
    for (Annotation annotation : annotations) {
        if (!annotation.getTypeName().equals(annotationName)) {
            list.add(annotation);
        }
    }
    Annotation[] newAnnotations = list.toArray(new Annotation[0]);
    attr.setAnnotations(newAnnotations);
    minfo.addAttribute(attr);
    return this;
}
Also used : ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ArrayList(java.util.ArrayList) MethodInfo(javassist.bytecode.MethodInfo) CtMethod(javassist.CtMethod) Annotation(javassist.bytecode.annotation.Annotation)

Example 19 with Annotation

use of javassist.bytecode.annotation.Annotation in project BroadleafCommerce by BroadleafCommerce.

the class ConditionalFieldAnnotationsClassTransformer method transform.

/**
 * Will return null if the Spring property value defined in {@link #propertyName} resolves to false, or if
 * an exception occurs while trying to determine the value for the property.
 *
 * @param loader
 * @param className
 * @param classBeingRedefined
 * @param protectionDomain
 * @param classfileBuffer
 * @return
 * @throws IllegalClassFormatException
 */
@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;
    }
    String convertedClassName = className.replace('/', '.');
    ConditionalFieldAnnotationCopyTransformMemberDTO dto = manager.getTransformMember(convertedClassName);
    if (dto == null || dto.getTemplateNames() == null || dto.getTemplateNames().length < 1) {
        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 {
        String[] xformVals = dto.getTemplateNames();
        // Load the destination class and defrost it so it is eligible for modifications
        ClassPool classPool = ClassPool.getDefault();
        clazz = classPool.makeClass(new ByteArrayInputStream(classfileBuffer), false);
        clazz.defrost();
        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);
            CtField[] fieldsToCopy = template.getDeclaredFields();
            // template annotations.  Otherwise, remove all annotations from the target.
            for (CtField field : fieldsToCopy) {
                ConstPool constPool = clazz.getClassFile().getConstPool();
                CtField fieldFromMainClass = clazz.getField(field.getName());
                AnnotationsAttribute copied = null;
                for (Object o : field.getFieldInfo().getAttributes()) {
                    if (o instanceof AnnotationsAttribute) {
                        AnnotationsAttribute templateAnnotations = (AnnotationsAttribute) o;
                        // have to make a copy of the annotations from the target
                        copied = (AnnotationsAttribute) templateAnnotations.copy(constPool, null);
                        break;
                    }
                }
                // add all the copied annotations into the target class's field.
                for (Object attribute : fieldFromMainClass.getFieldInfo().getAttributes()) {
                    if (attribute instanceof AnnotationsAttribute) {
                        Annotation[] annotations = null;
                        if (copied != null) {
                            // If we found annotations to copy, then use all of them
                            ArrayList<Annotation> annotationsList = new ArrayList<Annotation>();
                            for (Annotation annotation : copied.getAnnotations()) {
                                annotationsList.add(annotation);
                            }
                            annotations = new Annotation[annotationsList.size()];
                            int count = 0;
                            for (Annotation annotation : annotationsList) {
                                annotations[count] = annotation;
                                count++;
                            }
                            ((AnnotationsAttribute) attribute).setAnnotations(annotations);
                        } else {
                            // If no annotations were found on the template, then remove them entirely from the target.
                            ((AnnotationsAttribute) attribute).setAnnotations(new Annotation[] {});
                        }
                        break;
                    }
                }
            }
        }
        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
            }
        }
    }
}
Also used : ConstPool(javassist.bytecode.ConstPool) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) ArrayList(java.util.ArrayList) LoaderClassPath(javassist.LoaderClassPath) Annotation(javassist.bytecode.annotation.Annotation) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) CtField(javassist.CtField) ConditionalFieldAnnotationCopyTransformMemberDTO(org.broadleafcommerce.common.weave.ConditionalFieldAnnotationCopyTransformMemberDTO)

Example 20 with Annotation

use of javassist.bytecode.annotation.Annotation in project BroadleafCommerce by BroadleafCommerce.

the class DirectCopyClassTransformer method buildClassLevelAnnotations.

protected void buildClassLevelAnnotations(ClassFile classFile, ClassFile templateClassFile, ConstPool constantPool) throws NotFoundException {
    List<?> templateAttributes = templateClassFile.getAttributes();
    Iterator<?> templateItr = templateAttributes.iterator();
    Annotation templateEntityListeners = null;
    while (templateItr.hasNext()) {
        Object object = templateItr.next();
        if (AnnotationsAttribute.class.isAssignableFrom(object.getClass())) {
            AnnotationsAttribute attr = (AnnotationsAttribute) object;
            Annotation[] items = attr.getAnnotations();
            for (Annotation annotation : items) {
                String typeName = annotation.getTypeName();
                if (typeName.equals(EntityListeners.class.getName())) {
                    templateEntityListeners = annotation;
                }
            }
        }
    }
    if (templateEntityListeners != null) {
        AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constantPool, AnnotationsAttribute.visibleTag);
        List<?> attributes = classFile.getAttributes();
        Iterator<?> itr = attributes.iterator();
        Annotation existingEntityListeners = null;
        while (itr.hasNext()) {
            Object object = itr.next();
            if (AnnotationsAttribute.class.isAssignableFrom(object.getClass())) {
                AnnotationsAttribute attr = (AnnotationsAttribute) object;
                Annotation[] items = attr.getAnnotations();
                for (Annotation annotation : items) {
                    String typeName = annotation.getTypeName();
                    if (typeName.equals(EntityListeners.class.getName())) {
                        logger.debug("Stripping out previous EntityListeners annotation at the class level - will merge into new EntityListeners");
                        existingEntityListeners = annotation;
                        continue;
                    }
                    annotationsAttribute.addAnnotation(annotation);
                }
                itr.remove();
            }
        }
        Annotation entityListeners = getEntityListeners(constantPool, existingEntityListeners, templateEntityListeners);
        annotationsAttribute.addAnnotation(entityListeners);
        classFile.addAttribute(annotationsAttribute);
    }
}
Also used : AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) EntityListeners(javax.persistence.EntityListeners) Annotation(javassist.bytecode.annotation.Annotation)

Aggregations

Annotation (javassist.bytecode.annotation.Annotation)26 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)19 StringMemberValue (javassist.bytecode.annotation.StringMemberValue)12 ConstPool (javassist.bytecode.ConstPool)11 ClassFile (javassist.bytecode.ClassFile)9 ArrayList (java.util.ArrayList)7 CtClass (javassist.CtClass)7 ClassPool (javassist.ClassPool)6 CtMethod (javassist.CtMethod)5 AnnotationMemberValue (javassist.bytecode.annotation.AnnotationMemberValue)5 ArrayMemberValue (javassist.bytecode.annotation.ArrayMemberValue)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)4 MethodInfo (javassist.bytecode.MethodInfo)4 EnumMemberValue (javassist.bytecode.annotation.EnumMemberValue)4 MemberValue (javassist.bytecode.annotation.MemberValue)4 DataInputStream (java.io.DataInputStream)3 HashSet (java.util.HashSet)3 CtField (javassist.CtField)3 ClassMemberValue (javassist.bytecode.annotation.ClassMemberValue)3