Search in sources :

Example 6 with Annotation

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

the class QueryConfigurationClassTransformer method prepareNativeQueries.

/**
 * Prepare the {@link NamedNativeQueries} declaration
 *
 * @param constantPool
 * @param pool
 * @param queryArray
 * @throws NotFoundException
 */
protected void prepareNativeQueries(ConstPool constantPool, ClassPool pool, ArrayMemberValue queryArray) throws NotFoundException {
    List<MemberValue> values;
    if (queryArray.getValue() != null) {
        values = new ArrayList<MemberValue>(Arrays.asList(queryArray.getValue()));
    } else {
        values = new ArrayList<MemberValue>();
    }
    for (NamedNativeQuery query : nativeQueries) {
        Annotation namedQuery = new Annotation(NamedNativeQuery.class.getName(), constantPool);
        StringMemberValue name = new StringMemberValue(constantPool);
        name.setValue(query.name());
        namedQuery.addMemberValue("name", name);
        StringMemberValue queryString = new StringMemberValue(constantPool);
        queryString.setValue(query.query());
        namedQuery.addMemberValue("query", queryString);
        ClassMemberValue resultClass = new ClassMemberValue(constantPool);
        resultClass.setValue(query.resultClass().getName());
        namedQuery.addMemberValue("resultClass", resultClass);
        StringMemberValue resultSetMapping = new StringMemberValue(constantPool);
        resultSetMapping.setValue(query.resultSetMapping());
        namedQuery.addMemberValue("resultSetMapping", resultSetMapping);
        List<AnnotationMemberValue> queryHints = new ArrayList<AnnotationMemberValue>();
        for (QueryHint hint : query.hints()) {
            prepareQueryHints(constantPool, queryHints, hint);
        }
        ArrayMemberValue hintArray = new ArrayMemberValue(constantPool);
        hintArray.setValue(queryHints.toArray(new AnnotationMemberValue[queryHints.size()]));
        namedQuery.addMemberValue("hints", hintArray);
        AnnotationMemberValue queryAnnotation = new AnnotationMemberValue(namedQuery, constantPool);
        values.add(queryAnnotation);
    }
    queryArray.setValue(values.toArray(new MemberValue[values.size()]));
}
Also used : MemberValue(javassist.bytecode.annotation.MemberValue) AnnotationMemberValue(javassist.bytecode.annotation.AnnotationMemberValue) ArrayMemberValue(javassist.bytecode.annotation.ArrayMemberValue) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) ClassMemberValue(javassist.bytecode.annotation.ClassMemberValue) EnumMemberValue(javassist.bytecode.annotation.EnumMemberValue) NamedNativeQuery(javax.persistence.NamedNativeQuery) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) QueryHint(javax.persistence.QueryHint) AnnotationMemberValue(javassist.bytecode.annotation.AnnotationMemberValue) ArrayList(java.util.ArrayList) Annotation(javassist.bytecode.annotation.Annotation) ClassMemberValue(javassist.bytecode.annotation.ClassMemberValue) ArrayMemberValue(javassist.bytecode.annotation.ArrayMemberValue)

Example 7 with Annotation

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

the class AlterTableNameClassTransformer method alterTableAnnotation.

/**
 * Build class-level annotations from a template class
 *
 * @param classFile
 * @param tableName
 * @param constantPool
 * @throws NotFoundException
 */
protected void alterTableAnnotation(ClassFile classFile, String tableName, ConstPool constantPool) throws NotFoundException {
    List<?> classFileAttributes = classFile.getAttributes();
    Iterator<?> classItr = classFileAttributes.iterator();
    AnnotationsAttribute attr = null;
    while (classItr.hasNext()) {
        Object object = classItr.next();
        if (AnnotationsAttribute.class.isAssignableFrom(object.getClass())) {
            attr = (AnnotationsAttribute) object;
            Annotation[] items = attr.getAnnotations();
            for (Annotation annotation : items) {
                String typeName = annotation.getTypeName();
                if (typeName.equals(Table.class.getName())) {
                    Set<String> keys = annotation.getMemberNames();
                    for (String key : keys) {
                        if (key.equalsIgnoreCase("name")) {
                            StringMemberValue value = (StringMemberValue) annotation.getMemberValue(key);
                            String oldTableName = value.getValue();
                            value.setValue(tableName);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Altering " + classFile.getName() + " table name from: " + oldTableName + "" + " to: " + value.getValue());
                            }
                            break;
                        }
                    }
                    break;
                }
            }
            attr.setAnnotations(items);
            break;
        }
    }
    if (attr != null) {
        classItr.remove();
        classFile.addAttribute(attr);
    }
}
Also used : Table(javax.persistence.Table) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) Annotation(javassist.bytecode.annotation.Annotation)

Example 8 with Annotation

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

the class MaterializedClobTypeClassTransformer method transform.

@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (className == null) {
        return null;
    }
    String convertedClassName = className.replace('/', '.');
    if (isIgnored(convertedClassName)) {
        return null;
    }
    try {
        boolean transformed = false;
        ClassFile classFile = new ClassFile(new DataInputStream(new ByteArrayInputStream(classfileBuffer)));
        boolean containsTypeLevelAnnotation = false;
        {
            List<?> attributes = classFile.getAttributes();
            Iterator<?> itr = attributes.iterator();
            while (itr.hasNext()) {
                Object object = itr.next();
                if (AnnotationsAttribute.class.isAssignableFrom(object.getClass())) {
                    containsTypeLevelAnnotation = containsTypeLevelPersistenceAnnotation(((AnnotationsAttribute) object).getAnnotations());
                }
            }
        }
        if (containsTypeLevelAnnotation) {
            List<FieldInfo> fieldInfos = classFile.getFields();
            ConstPool constantPool = classFile.getConstPool();
            for (FieldInfo myField : fieldInfos) {
                List<?> attributes = myField.getAttributes();
                Iterator<?> itr = attributes.iterator();
                AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constantPool, AnnotationsAttribute.visibleTag);
                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(Type.class.getName())) {
                                StringMemberValue annot = (StringMemberValue) annotation.getMemberValue("type");
                                if (annot != null && annot.getValue().equals(StringClobType.class.getName())) {
                                    Annotation clobType = new Annotation(Type.class.getName(), constantPool);
                                    StringMemberValue type = new StringMemberValue(constantPool);
                                    type.setValue(MaterializedClobType.class.getName());
                                    clobType.addMemberValue("type", type);
                                    annotationsAttribute.addAnnotation(clobType);
                                    transformed = true;
                                } else {
                                    annotationsAttribute.addAnnotation(annotation);
                                }
                            } else {
                                annotationsAttribute.addAnnotation(annotation);
                            }
                        }
                        if (transformed) {
                            itr.remove();
                        }
                    }
                }
                if (transformed) {
                    myField.addAttribute(annotationsAttribute);
                }
            }
        }
        if (transformed) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream os = new DataOutputStream(bos);
            classFile.write(os);
            os.close();
            return bos.toByteArray();
        } else {
            return null;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new IllegalClassFormatException("Unable to convert " + convertedClassName + " to sandbox: " + ex.getMessage());
    }
}
Also used : ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) DataOutputStream(java.io.DataOutputStream) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataInputStream(java.io.DataInputStream) Annotation(javassist.bytecode.annotation.Annotation) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) MaterializedClobType(org.hibernate.type.MaterializedClobType) Type(org.hibernate.annotations.Type) StringClobType(org.hibernate.type.StringClobType) ByteArrayInputStream(java.io.ByteArrayInputStream) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) Iterator(java.util.Iterator) MaterializedClobType(org.hibernate.type.MaterializedClobType) ArrayList(java.util.ArrayList) List(java.util.List) FieldInfo(javassist.bytecode.FieldInfo)

Example 9 with Annotation

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

the class SingleTableInheritanceClassTransformer 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;
    }
    if (infos.isEmpty()) {
        return null;
    }
    String convertedClassName = className.replace('/', '.');
    SingleTableInheritanceInfo key = new SingleTableInheritanceInfo();
    key.setClassName(convertedClassName);
    int pos = infos.indexOf(key);
    if (pos >= 0) {
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Converting " + convertedClassName + " to a SingleTable inheritance strategy.");
            }
            SingleTableInheritanceInfo myInfo = infos.get(pos);
            ClassFile classFile = new ClassFile(new DataInputStream(new ByteArrayInputStream(classfileBuffer)));
            ConstPool constantPool = classFile.getConstPool();
            AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constantPool, AnnotationsAttribute.visibleTag);
            List<?> attributes = classFile.getAttributes();
            Iterator<?> itr = attributes.iterator();
            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(Inheritance.class.getName())) {
                            annotationsAttribute.addAnnotation(annotation);
                        }
                    }
                    itr.remove();
                }
            }
            Annotation inheritance = new Annotation(Inheritance.class.getName(), constantPool);
            ClassPool pool = ClassPool.getDefault();
            pool.importPackage("javax.persistence");
            pool.importPackage("java.lang");
            EnumMemberValue strategy = (EnumMemberValue) Annotation.createMemberValue(constantPool, pool.makeClass("InheritanceType"));
            strategy.setType(InheritanceType.class.getName());
            strategy.setValue(InheritanceType.SINGLE_TABLE.name());
            inheritance.addMemberValue("strategy", strategy);
            annotationsAttribute.addAnnotation(inheritance);
            if (myInfo.getDiscriminatorName() != null) {
                Annotation discriminator = new Annotation(DiscriminatorColumn.class.getName(), constantPool);
                StringMemberValue name = new StringMemberValue(constantPool);
                name.setValue(myInfo.getDiscriminatorName());
                discriminator.addMemberValue("name", name);
                EnumMemberValue discriminatorType = (EnumMemberValue) Annotation.createMemberValue(constantPool, pool.makeClass("DiscriminatorType"));
                discriminatorType.setType(DiscriminatorType.class.getName());
                discriminatorType.setValue(myInfo.getDiscriminatorType().name());
                discriminator.addMemberValue("discriminatorType", discriminatorType);
                IntegerMemberValue length = new IntegerMemberValue(constantPool);
                length.setValue(myInfo.getDiscriminatorLength());
                discriminator.addMemberValue("length", length);
                annotationsAttribute.addAnnotation(discriminator);
            }
            classFile.addAttribute(annotationsAttribute);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream os = new DataOutputStream(bos);
            classFile.write(os);
            os.close();
            return bos.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new IllegalClassFormatException("Unable to convert " + convertedClassName + " to a SingleTable inheritance strategy: " + ex.getMessage());
        }
    } else {
        return null;
    }
}
Also used : EnumMemberValue(javassist.bytecode.annotation.EnumMemberValue) ConstPool(javassist.bytecode.ConstPool) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) DataOutputStream(java.io.DataOutputStream) Inheritance(javax.persistence.Inheritance) ClassPool(javassist.ClassPool) InheritanceType(javax.persistence.InheritanceType) IntegerMemberValue(javassist.bytecode.annotation.IntegerMemberValue) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataInputStream(java.io.DataInputStream) Annotation(javassist.bytecode.annotation.Annotation) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) DiscriminatorType(javax.persistence.DiscriminatorType) ByteArrayInputStream(java.io.ByteArrayInputStream) DiscriminatorColumn(javax.persistence.DiscriminatorColumn)

Example 10 with Annotation

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

the class AnnotationsCopyClassTransformer 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;
    }
    String convertedClassName = className.replace('/', '.');
    if (xformTemplates.containsKey(convertedClassName)) {
        String xformKey = convertedClassName;
        String[] xformVals = xformTemplates.get(xformKey).split(",");
        logger.lifecycle(LifeCycleEvent.START, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey, StringUtils.join(xformVals, ",")));
        CtClass clazz = null;
        try {
            // 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);
                // Copy over all declared annotations from 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 copying annotation from field [%s]", field.getName()));
                    } else {
                        logger.debug(String.format("Copying annotation from field [%s]", field.getName()));
                        ConstPool constPool = clazz.getClassFile().getConstPool();
                        CtField fieldFromMainClass = clazz.getField(field.getName());
                        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
                                AnnotationsAttribute copied = (AnnotationsAttribute) templateAnnotations.copy(constPool, null);
                                // add all the copied annotations into the target class's field.
                                for (Object attribute : fieldFromMainClass.getFieldInfo().getAttributes()) {
                                    if (attribute instanceof AnnotationsAttribute) {
                                        for (Annotation annotation : copied.getAnnotations()) {
                                            ((AnnotationsAttribute) attribute).addAnnotation(annotation);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            logger.lifecycle(LifeCycleEvent.END, String.format("Transform - Copying annotations into [%s] from [%s]", xformKey, StringUtils.join(xformVals, ",")));
            return clazz.toBytecode();
        } catch (Exception e) {
            throw new RuntimeException("Unable to transform class", e);
        } finally {
            if (clazz != null) {
                clazz.detach();
            }
        }
    }
    return null;
}
Also used : ConstPool(javassist.bytecode.ConstPool) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath) Annotation(javassist.bytecode.annotation.Annotation) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) CtField(javassist.CtField)

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