Search in sources :

Example 71 with NotFoundException

use of javassist.NotFoundException in project motech by motech.

the class EntityBuilderImpl method build.

private ClassData build(EntityDto entity, List<FieldDto> fields, EntityType type, Bundle bundle) {
    try {
        CtClass declaring = makeClass(entity, fields, type, bundle);
        switch(type) {
            case HISTORY:
                String className = type.getClassName(entity.getClassName());
                String simpleName = ClassName.getSimpleName(className);
                TypeDto idType = TypeDto.LONG;
                // add 4 extra fields to history class definition
                // this field is related with id field in entity
                addProperty(declaring, idType.getTypeClass(), simpleName + Constants.Util.CURRENT_VERSION, null);
                // this field contains information about the schema version of an entity
                addProperty(declaring, Long.class.getName(), simpleName + StringUtils.capitalize(Constants.Util.SCHEMA_VERSION_FIELD_NAME), null);
                break;
            case TRASH:
                // this field contains information about the schema version of an entity
                addProperty(declaring, Long.class.getName(), Constants.Util.SCHEMA_VERSION_FIELD_NAME, null);
                break;
            default:
        }
        return new ClassData(declaring.getName(), entity.getModule(), entity.getNamespace(), declaring.toBytecode(), type);
    } catch (ReflectiveOperationException | CannotCompileException | IOException | NotFoundException e) {
        throw new EntityCreationException("Unable to create entity " + entity.getName(), e);
    }
}
Also used : CtClass(javassist.CtClass) ClassData(org.motechproject.mds.domain.ClassData) NotFoundException(javassist.NotFoundException) TypeDto(org.motechproject.mds.dto.TypeDto) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) EntityCreationException(org.motechproject.mds.exception.entity.EntityCreationException)

Example 72 with NotFoundException

use of javassist.NotFoundException in project motech by motech.

the class EntityMetadataBuilderImpl method addIdField.

private void addIdField(ClassMetadata cmd, String className, Class<?> definition) {
    boolean containsID;
    boolean isBaseClass;
    try {
        CtClass ctClass = MotechClassPool.getDefault().getOrNull(className);
        containsID = null != ctClass && null != ctClass.getField(ID_FIELD_NAME);
        isBaseClass = null != ctClass && (null == ctClass.getSuperclass() || Object.class.getName().equalsIgnoreCase(ctClass.getSuperclass().getName()));
    } catch (NotFoundException e) {
        containsID = false;
        isBaseClass = false;
    }
    if (containsID && isBaseClass) {
        FieldMetadata metadata = cmd.newFieldMetadata(ID_FIELD_NAME);
        metadata.setValueStrategy(getIdGeneratorStrategy(metadata, definition));
        metadata.setPrimaryKey(true);
    }
}
Also used : CtClass(javassist.CtClass) FieldMetadata(javax.jdo.metadata.FieldMetadata) NotFoundException(javassist.NotFoundException)

Example 73 with NotFoundException

use of javassist.NotFoundException in project motech by motech.

the class EntityInfrastructureBuilderImpl method getRepositoryCode.

private byte[] getRepositoryCode(String repositoryClassName, String typeName, Integer fetchDepth) {
    try {
        CtClass superClass = classPool.getCtClass(MotechDataRepository.class.getName());
        superClass.setGenericSignature(getGenericSignature(typeName));
        CtClass subClass = createOrRetrieveClass(repositoryClassName, superClass);
        String repositoryName = ClassName.getSimpleName(repositoryClassName);
        removeDefaultConstructor(subClass);
        String constructorAsString;
        // the fetch depth parameter is optional
        if (fetchDepth == null) {
            constructorAsString = String.format("public %s(){super(%s.class);}", repositoryName, typeName);
        } else {
            constructorAsString = String.format("public %s(){super(%s.class, %d);}", repositoryName, typeName, fetchDepth);
        }
        CtConstructor constructor = CtNewConstructor.make(constructorAsString, subClass);
        subClass.addConstructor(constructor);
        return subClass.toBytecode();
    } catch (NotFoundException | CannotCompileException | IOException e) {
        throw new EntityInfrastructureException(repositoryClassName, e);
    }
}
Also used : CtClass(javassist.CtClass) EntityInfrastructureException(org.motechproject.mds.exception.entity.EntityInfrastructureException) NotFoundException(javassist.NotFoundException) MotechDataRepository(org.motechproject.mds.repository.MotechDataRepository) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtConstructor(javassist.CtConstructor)

Example 74 with NotFoundException

use of javassist.NotFoundException in project motech by motech.

the class EntityInfrastructureBuilderImpl method getInterfaceCode.

private byte[] getInterfaceCode(String interfaceClassName, String className, EntityDto entity, SchemaHolder schemaHolder) {
    try {
        // the interface can come from the developer for DDE, but it doesn't have to
        // in which case it will be generated from scratch
        CtClass superInterface = null;
        if (null != entity && MotechClassPool.isServiceInterfaceRegistered(className)) {
            String ddeInterfaceName = MotechClassPool.getInterfaceName(className);
            Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
            if (declaringBundle == null) {
                LOGGER.error("Unable to find bundle declaring the DDE interface for {}", className);
            } else {
                superInterface = JavassistUtil.loadClass(declaringBundle, ddeInterfaceName, classPool);
            }
        }
        // standard super interface - MotechDataService, for EUDE or DDE without an interface
        if (superInterface == null) {
            superInterface = classPool.getCtClass(MotechDataService.class.getName());
            superInterface.setGenericSignature(getGenericSignature(className));
        }
        CtClass interfaceClass = createOrRetrieveInterface(interfaceClassName, superInterface);
        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, interfaceClass, lookupType, schemaHolder);
                    methods.add(lookupBuilder.buildSignature());
                }
            }
        }
        // clear lookup methods before adding the new ones
        removeExistingMethods(interfaceClass);
        for (CtMethod method : methods) {
            interfaceClass.addMethod(method);
        }
        return interfaceClass.toBytecode();
    } catch (NotFoundException | IOException | CannotCompileException e) {
        throw new EntityInfrastructureException(interfaceClassName, e);
    }
}
Also used : EntityInfrastructureException(org.motechproject.mds.exception.entity.EntityInfrastructureException) Bundle(org.osgi.framework.Bundle) 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)

Example 75 with NotFoundException

use of javassist.NotFoundException in project coprhd-controller by CoprHD.

the class DataObjectType method instrumentModelClasses.

/**
 * instrument model classes to override getter and setter methods to enable lazy loading
 */
private void instrumentModelClasses() {
    long start = Calendar.getInstance().getTime().getTime();
    if (_lazyLoadedFields.isEmpty()) {
        // no error here; just means there are no lazy loaded fields in this model class
        return;
    }
    CtClass instrumentedClass = null;
    try {
        ClassPool pool = ClassPool.getDefault();
        CtClass modelClass = pool.get(_clazz.getCanonicalName());
        String instrumentedClassName = _clazz.getPackage().getName() + ".vipr-dbmodel$$" + _clazz.getSimpleName();
        instrumentedClass = pool.getAndRename(LazyLoadedDataObject.class.getName(), instrumentedClassName);
        if (instrumentedClass != null) {
            instrumentedClass.setSuperclass(modelClass);
        }
    } catch (CannotCompileException e) {
        _log.error(String.format("Compile error instrumenting data model class %s", _clazz.getCanonicalName()));
        _log.error(e.getMessage(), e);
        throw DatabaseException.fatals.serializationFailedClass(_clazz, e);
    } catch (NotFoundException e) {
        _log.error(String.format("Javassist could not find data model class %s", _clazz.getCanonicalName()));
        _log.error(e.getMessage(), e);
        throw DatabaseException.fatals.serializationFailedClass(_clazz, e);
    }
    long totalClassTime = Calendar.getInstance().getTime().getTime() - start;
    long startFieldTime = Calendar.getInstance().getTime().getTime();
    for (ColumnField field : _lazyLoadedFields) {
        PropertyDescriptor pd = field.getPropertyDescriptor();
        String fieldName = field.getName();
        try {
            CtClass modelClass = ClassPool.getDefault().get(pd.getReadMethod().getDeclaringClass().getCanonicalName());
            String quotedFieldName = "\"" + fieldName + "\"";
            if (DataObject.class.isAssignableFrom(pd.getPropertyType())) {
                // override the getter for the lazy loaded object and add code to load the object
                CtMethod readMethod = modelClass.getDeclaredMethod(pd.getReadMethod().getName());
                // read method checks for isLoaded and loads if not loaded
                CtMethod instReadMethod = CtNewMethod.delegator(readMethod, instrumentedClass);
                String before = String.format("load(%s, this);", quotedFieldName);
                _log.debug(String.format("creating new method %s for instrumented class %s: %s", instReadMethod.getName(), instrumentedClass.getName(), before));
                instReadMethod.insertBefore(before);
                instrumentedClass.addMethod(instReadMethod);
                // override the setter for the mapped by field and add code to invalidate the
                // lazy loaded object (so that it will be re-loaded the next time it's accessed)
                String mappedByFieldName = field.getMappedByField();
                ColumnField mappedByField = getColumnField(mappedByFieldName);
                if (mappedByField != null) {
                    CtMethod mappedByWriteMethod = modelClass.getDeclaredMethod(mappedByField.getPropertyDescriptor().getWriteMethod().getName());
                    CtMethod instMappedByWriteMethod = CtNewMethod.delegator(mappedByWriteMethod, instrumentedClass);
                    String mappedByCode = String.format("invalidate(%s);", quotedFieldName);
                    _log.debug(String.format("creating new method %s for instrumented class %s: %s", instMappedByWriteMethod.getName(), instrumentedClass.getName(), mappedByCode));
                    instMappedByWriteMethod.insertAfter(mappedByCode);
                    instrumentedClass.addMethod(instMappedByWriteMethod);
                }
            }
            CtMethod writeMethod = modelClass.getDeclaredMethod(pd.getWriteMethod().getName());
            CtMethod instWriteMethod = CtNewMethod.delegator(writeMethod, instrumentedClass);
            String writeMethodDef = String.format("refreshMappedByField(%s, this);", quotedFieldName);
            _log.debug(String.format("creating new method %s for instrumented class %s: %s", instWriteMethod.getName(), instrumentedClass.getName(), writeMethodDef));
            instWriteMethod.insertAfter(writeMethodDef);
            instrumentedClass.addMethod(instWriteMethod);
        } catch (CannotCompileException e) {
            _log.error(String.format("Compile error instrumenting data model class %s", _clazz.getCanonicalName()));
            _log.error(e.getMessage(), e);
            throw DatabaseException.fatals.serializationFailedClass(_clazz, e);
        } catch (NotFoundException e) {
            _log.error(String.format("Field %s in data model class %s must have both a write method and a read method", fieldName, _clazz.getCanonicalName()));
            _log.error(e.getMessage(), e);
            throw DatabaseException.fatals.serializationFailedClass(_clazz, e);
        }
    }
    long totalFieldTime = Calendar.getInstance().getTime().getTime() - startFieldTime;
    start = Calendar.getInstance().getTime().getTime();
    if (instrumentedClass != null) {
        try {
            _instrumentedClazz = instrumentedClass.toClass();
            // detach isn't necessary to get it to work, but it releases memory
            instrumentedClass.detach();
        } catch (CannotCompileException e) {
            _log.error(e.getMessage(), e);
        }
    }
    totalClassTime += Calendar.getInstance().getTime().getTime() - start;
    _log.info(String.format("Class instrumentation for %s: total time: %d; class time: %d; field time: %d; avg per field: %f", _clazz.getName(), totalClassTime + totalFieldTime, totalClassTime, totalFieldTime, (float) totalFieldTime / (float) _lazyLoadedFields.size()));
}
Also used : CtClass(javassist.CtClass) PropertyDescriptor(java.beans.PropertyDescriptor) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

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