Search in sources :

Example 61 with CannotCompileException

use of javassist.CannotCompileException in project restfulie-java by caelum.

the class DefaultEnhancer method enhanceResource.

public <T> Class enhanceResource(Class<T> originalType) {
    ClassPool pool = ClassPool.getDefault();
    if (pool.find(DefaultEnhancer.class.getName()) == null) {
        pool.appendClassPath(new LoaderClassPath(getClass().getClassLoader()));
    }
    try {
        // TODO extract this enhancement to an interface and test it appart
        CtClass newType = pool.makeClass(generateNewUniqueClassName(originalType));
        newType.setSuperclass(pool.get(originalType.getName()));
        newType.addInterface(pool.get(Resource.class.getName()));
        enhanceLinks(newType);
        return newType.toClass();
    } catch (NotFoundException e) {
        throw new IllegalStateException("Unable to extend type " + originalType.getName(), e);
    } catch (CannotCompileException e) {
        throw new IllegalStateException("Unable to extend type " + originalType.getName(), e);
    }
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException)

Example 62 with CannotCompileException

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

Example 63 with CannotCompileException

use of javassist.CannotCompileException 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 64 with CannotCompileException

use of javassist.CannotCompileException in project afterburner by stephanenicolas.

the class AfterBurner method addOrInsertMethod.

/**
 * Add/Inserts java instructions into a given method of a given class.
 * @param insertableMethod contains all information to perform byte code injection.
 * @throws CannotCompileException if the source contained in insertableMethod can't be compiled.
 * @throws AfterBurnerImpossibleException if something else goes wrong, wraps other exceptions.
 */
public void addOrInsertMethod(InsertableMethod insertableMethod) throws CannotCompileException, AfterBurnerImpossibleException {
    log.info("InsertableMethod : " + insertableMethod);
    // create or complete onViewCreated
    String targetMethodName = insertableMethod.getTargetMethodName();
    CtClass classToTransform = insertableMethod.getClassToInsertInto();
    CtMethod targetMethod = extractExistingMethod(classToTransform, targetMethodName);
    log.info("Method : " + targetMethod);
    if (targetMethod != null) {
        InsertableMethodInjectorEditor injectorEditor = new InsertableMethodInjectorEditor(classToTransform, insertableMethod);
        targetMethod.instrument(injectorEditor);
        if (!injectorEditor.isSuccessful) {
            throw new CannotCompileException("Transformation failed. Insertion method not found.: " + targetMethodName);
        }
    } else {
        classToTransform.addMethod(CtNewMethod.make(insertableMethod.getFullMethod(), classToTransform));
    }
}
Also used : CtClass(javassist.CtClass) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Example 65 with CannotCompileException

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

the class MethodCallClassTransformer method applyTransformations.

@Override
public void applyTransformations(final CtClass classToTransform) throws JavassistBuildException {
    if (null == classToTransform) {
        return;
    }
    try {
        classToTransform.instrument(new ExprEditor() {

            @Override
            public void edit(final MethodCall method) throws CannotCompileException {
                final String statement = getStatement(method.getClassName(), method.getMethodName());
                if (statement != null) {
                    try {
                        method.replace(statement);
                    } catch (final CannotCompileException e) {
                        throw new CannotCompileException(String.format("Compile statement '%1$s' FAILED with: %2$s", statement, e.getMessage()), e);
                    }
                }
            }
        });
        // insert internal introspection state field
        final CtField introspectedField = new CtField(CtClass.booleanType, ALREADY_INTROSPECTED_FIELD_NAME, classToTransform);
        introspectedField.setModifiers(AccessFlag.PUBLIC | AccessFlag.STATIC | AccessFlag.FINAL);
        classToTransform.addField(introspectedField, Initializer.constant(true));
    } catch (CannotCompileException e) {
        throw new JavassistBuildException(e);
    }
}
Also used : CtField(javassist.CtField) ExprEditor(javassist.expr.ExprEditor) JavassistBuildException(javassist.build.JavassistBuildException) CannotCompileException(javassist.CannotCompileException) MethodCall(javassist.expr.MethodCall)

Aggregations

CannotCompileException (javassist.CannotCompileException)65 CtClass (javassist.CtClass)45 NotFoundException (javassist.NotFoundException)42 CtMethod (javassist.CtMethod)30 IOException (java.io.IOException)22 ClassPool (javassist.ClassPool)22 CtField (javassist.CtField)15 CtConstructor (javassist.CtConstructor)10 FileNotFoundException (java.io.FileNotFoundException)8 File (java.io.File)6 Method (java.lang.reflect.Method)5 ArrayList (java.util.ArrayList)5 EnhancementException (org.hibernate.bytecode.enhance.spi.EnhancementException)5 FileFilter (java.io.FileFilter)4 BadBytecode (javassist.bytecode.BadBytecode)3 Bytecode (javassist.bytecode.Bytecode)3 CodeAttribute (javassist.bytecode.CodeAttribute)3 CodeIterator (javassist.bytecode.CodeIterator)3 CompileError (javassist.compiler.CompileError)3 Javac (javassist.compiler.Javac)3