Search in sources :

Example 66 with CtClass

use of javassist.CtClass in project motech by motech.

the class EntityBuilderImpl method addProperty.

private void addProperty(CtClass declaring, String typeClassName, String propertyName, String defaultValue) {
    try {
        String name = uncapitalize(propertyName);
        JavassistUtil.removeFieldIfExists(declaring, propertyName);
        CtClass type = classPool.getOrNull(typeClassName);
        CtField field = JavassistBuilder.createField(declaring, type, propertyName, null);
        if (isBlank(defaultValue)) {
            declaring.addField(field);
        } else {
            CtField.Initializer initializer = JavassistBuilder.createInitializer(typeClassName, defaultValue);
            declaring.addField(field, initializer);
        }
        createGetter(declaring, name, field);
        createSetter(declaring, name, field);
    } catch (CannotCompileException e) {
        throw new PropertyCreationException("Error while creating property " + propertyName, e);
    }
}
Also used : CtClass(javassist.CtClass) PropertyCreationException(org.motechproject.mds.exception.object.PropertyCreationException) CtField(javassist.CtField) CannotCompileException(javassist.CannotCompileException)

Example 67 with CtClass

use of javassist.CtClass in project motech by motech.

the class EntityInfrastructureBuilderImpl method getServiceCode.

private byte[] getServiceCode(String serviceClassName, String interfaceClassName, String className, EntityDto entity, SchemaHolder schemaHolder) {
    try {
        CtClass superClass = classPool.getCtClass(TransactionalMotechDataService.class.getName());
        superClass.setGenericSignature(getGenericSignature(className));
        CtClass serviceInterface = classPool.getCtClass(interfaceClassName);
        CtClass serviceClass = createOrRetrieveClass(serviceClassName, superClass);
        // add the interface if its not already there
        if (!JavassistUtil.hasInterface(serviceClass, serviceInterface)) {
            serviceClass.addInterface(serviceInterface);
        }
        List<CtMethod> methods = new ArrayList<>();
        // a count method for the lookup
        if (null != entity) {
            List<LookupDto> lookups = schemaHolder.getLookups(entity);
            for (LookupDto lookup : lookups) {
                for (LookupType lookupType : LookupType.values()) {
                    LookupBuilder lookupBuilder = new LookupBuilder(entity, lookup, serviceClass, lookupType, schemaHolder);
                    methods.add(lookupBuilder.buildMethod());
                }
            }
        }
        // clear lookup methods before adding the new ones
        removeExistingMethods(serviceClass);
        for (CtMethod method : methods) {
            serviceClass.addMethod(method);
        }
        return serviceClass.toBytecode();
    } catch (NotFoundException | IOException | CannotCompileException e) {
        throw new EntityInfrastructureException(serviceClassName, e);
    }
}
Also used : EntityInfrastructureException(org.motechproject.mds.exception.entity.EntityInfrastructureException) LookupDto(org.motechproject.mds.dto.LookupDto) ArrayList(java.util.ArrayList) NotFoundException(javassist.NotFoundException) IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException) CtClass(javassist.CtClass) CtMethod(javassist.CtMethod) TransactionalMotechDataService(org.motechproject.mds.service.TransactionalMotechDataService)

Example 68 with CtClass

use of javassist.CtClass in project motech by motech.

the class BaseInstanceIT method setUpEntity.

private void setUpEntity() throws Exception {
    String entityClass = getEntityClassName();
    entity = new EntityDto(entityClass);
    entity.setRecordHistory(true);
    entity = entityService.createEntity(entity);
    entityService.addFields(entity, getEntityFields());
    TrackingDto tracking = entityService.getAdvancedSettings(entity.getId(), true).getTracking();
    tracking.setAllowCreateEvent(false);
    tracking.setAllowUpdateEvent(false);
    tracking.setAllowDeleteEvent(false);
    entityService.updateTracking(entity.getId(), tracking);
    SchemaHolder schemaHolder = entityService.getSchema();
    mdsConstructor.constructEntities(schemaHolder);
    PersistenceManagerFactory factory = getDataPersistenceManagerFactory();
    if (null == factory.getMetadata(entityClass)) {
        factory.registerMetadata(metadataHolder.getJdoMetadata());
    }
    CtClass ctClass = MotechClassPool.getDefault().get(getRepositoryClass());
    MDSClassLoader.getInstance().safeDefineClass(getRepositoryClass(), ctClass.toBytecode());
    ctClass = MotechClassPool.getDefault().get(getInterfaceClass());
    MDSClassLoader.getInstance().safeDefineClass(getInterfaceClass(), ctClass.toBytecode());
    ctClass = MotechClassPool.getDefault().get(getServiceClass());
    MDSClassLoader.getInstance().safeDefineClass(getServiceClass(), ctClass.toBytecode());
}
Also used : EntityDto(org.motechproject.mds.dto.EntityDto) CtClass(javassist.CtClass) SchemaHolder(org.motechproject.mds.dto.SchemaHolder) PersistenceManagerFactory(javax.jdo.PersistenceManagerFactory) TrackingDto(org.motechproject.mds.dto.TrackingDto)

Example 69 with CtClass

use of javassist.CtClass in project javaparser by javaparser.

the class JavassistEnumDeclaration method solveMethod.

public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly) {
    List<ResolvedMethodDeclaration> candidates = new ArrayList<>();
    Predicate<CtMethod> staticOnlyCheck = m -> !staticOnly || (staticOnly && Modifier.isStatic(m.getModifiers()));
    for (CtMethod method : ctClass.getDeclaredMethods()) {
        boolean isSynthetic = method.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null;
        boolean isNotBridge = (method.getMethodInfo().getAccessFlags() & AccessFlag.BRIDGE) == 0;
        if (method.getName().equals(name) && !isSynthetic && isNotBridge && staticOnlyCheck.test(method)) {
            candidates.add(new JavassistMethodDeclaration(method, typeSolver));
        }
    }
    try {
        CtClass superClass = ctClass.getSuperclass();
        if (superClass != null) {
            SymbolReference<ResolvedMethodDeclaration> ref = new JavassistClassDeclaration(superClass, typeSolver).solveMethod(name, argumentsTypes, staticOnly);
            if (ref.isSolved()) {
                candidates.add(ref.getCorrespondingDeclaration());
            }
        }
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }
    return MethodResolutionLogic.findMostApplicable(candidates, name, argumentsTypes, typeSolver);
}
Also used : CtMethod(javassist.CtMethod) java.util(java.util) AccessFlag(javassist.bytecode.AccessFlag) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) Predicate(java.util.function.Predicate) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) MethodUsage(com.github.javaparser.resolution.MethodUsage) AccessSpecifier(com.github.javaparser.ast.AccessSpecifier) CtClass(javassist.CtClass) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) com.github.javaparser.resolution.declarations(com.github.javaparser.resolution.declarations) Collectors(java.util.stream.Collectors) CtField(javassist.CtField) AbstractTypeDeclaration(com.github.javaparser.symbolsolver.logic.AbstractTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) Context(com.github.javaparser.symbolsolver.core.resolution.Context) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) Modifier(java.lang.reflect.Modifier) SyntheticAttribute(javassist.bytecode.SyntheticAttribute) NotFoundException(javassist.NotFoundException) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) NotFoundException(javassist.NotFoundException) CtClass(javassist.CtClass) CtMethod(javassist.CtMethod)

Example 70 with CtClass

use of javassist.CtClass 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

CtClass (javassist.CtClass)271 CtMethod (javassist.CtMethod)96 ClassPool (javassist.ClassPool)93 NotFoundException (javassist.NotFoundException)85 Test (org.junit.Test)63 CannotCompileException (javassist.CannotCompileException)62 CtField (javassist.CtField)53 IOException (java.io.IOException)35 CtConstructor (javassist.CtConstructor)26 Method (java.lang.reflect.Method)17 LoaderClassPath (javassist.LoaderClassPath)16 ClassFile (javassist.bytecode.ClassFile)14 ArrayList (java.util.ArrayList)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)11 ConstPool (javassist.bytecode.ConstPool)11 File (java.io.File)8 FileNotFoundException (java.io.FileNotFoundException)8 Collectors (java.util.stream.Collectors)8 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)7