Search in sources :

Example 56 with NotFoundException

use of javassist.NotFoundException in project systemml by apache.

the class GenerateClassesForMLContext method addPackageConvenienceMethodsToMLContext.

/**
 * Add methods to MLContext to allow tab-completion to packages contained
 * within the source directory (such as {@code ml.nn()}).
 *
 * @param dirPath
 *            path to source directory (typically, the scripts directory)
 * @param ctMLContext
 *            javassist compile-time class representation of MLContext
 */
public static void addPackageConvenienceMethodsToMLContext(String dirPath, CtClass ctMLContext) {
    try {
        if (!SOURCE.equalsIgnoreCase(dirPath)) {
            return;
        }
        File dir = new File(dirPath);
        File[] subdirs = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });
        for (File subdir : subdirs) {
            String subDirPath = dirPath + File.separator + subdir.getName();
            if (skipDir(subdir, false)) {
                continue;
            }
            String fullSubDirClassName = dirPathToFullDirClassName(subDirPath);
            ClassPool pool = ClassPool.getDefault();
            CtClass subDirClass = pool.get(fullSubDirClassName);
            String subDirName = subdir.getName();
            subDirName = subDirName.replaceAll("-", "_");
            subDirName = subDirName.toLowerCase();
            System.out.println("Adding " + subDirName + "() to " + ctMLContext.getName());
            String methodBody = "{ " + fullSubDirClassName + " z = new " + fullSubDirClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, subDirClass, subDirName, null, null, methodBody, ctMLContext);
            ctMLContext.addMethod(ctMethod);
        }
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) CannotCompileException(javassist.CannotCompileException) FileFilter(java.io.FileFilter) File(java.io.File) CtMethod(javassist.CtMethod)

Example 57 with NotFoundException

use of javassist.NotFoundException in project turbo-rpc by hank-whu.

the class MethodParamClassFactory method doCreateClass.

@SuppressWarnings("unchecked")
private static Class<? extends MethodParam> doCreateClass(Method method) throws CannotCompileException, NotFoundException {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Parameter[] parameters = method.getParameters();
    if (!parameters[0].isNamePresent()) {
        throw new RuntimeException(NOT_SUPPORT_PARAMETER_NAME_MSG);
    }
    String paramTypes = // 
    Stream.of(parameterTypes).map(// 
    clazz -> clazz.getName()).collect(Collectors.joining(",", "(", ")"));
    String hash = Hashing.murmur3_128().hashString(paramTypes, StandardCharsets.UTF_8).toString();
    final String methodParamClassName = // 
    method.getDeclaringClass().getName() + // 
    "$MethodParam" + "$" + // 
    method.getName() + "$" + // 
    parameterTypes.length + "$" + // 防止同名方法冲突
    hash;
    try {
        Class<?> clazz = MethodParamClassFactory.class.getClassLoader().loadClass(methodParamClassName);
        if (clazz != null) {
            return (Class<? extends MethodParam>) clazz;
        }
    } catch (ClassNotFoundException e) {
    }
    // 创建类
    ClassPool pool = ClassPool.getDefault();
    CtClass methodParamCtClass = pool.makeClass(methodParamClassName);
    CtClass[] interfaces = { pool.getCtClass(MethodParam.class.getName()) };
    methodParamCtClass.setInterfaces(interfaces);
    for (int i = 0; i < parameterTypes.length; i++) {
        Parameter parameter = parameters[i];
        String paramName = parameter.getName();
        Class<?> paramType = parameterTypes[i];
        String capitalize = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
        String getter = "get" + capitalize;
        String setter = "set" + capitalize;
        CtField ctField = new CtField(pool.get(paramType.getName()), paramName, methodParamCtClass);
        ctField.setModifiers(Modifier.PRIVATE);
        methodParamCtClass.addField(ctField);
        methodParamCtClass.addMethod(CtNewMethod.getter("$param" + i, ctField));
        methodParamCtClass.addMethod(CtNewMethod.getter(getter, ctField));
        methodParamCtClass.addMethod(CtNewMethod.setter(setter, ctField));
    }
    // 添加无参的构造函数
    CtConstructor constructor0 = new CtConstructor(null, methodParamCtClass);
    constructor0.setModifiers(Modifier.PUBLIC);
    constructor0.setBody("{}");
    methodParamCtClass.addConstructor(constructor0);
    // 添加有参的构造函数
    CtClass[] paramCtClassArray = new CtClass[method.getParameterCount()];
    for (int i = 0; i < method.getParameterCount(); i++) {
        Class<?> paramType = parameterTypes[i];
        CtClass paramCtClass = pool.get(paramType.getName());
        paramCtClassArray[i] = paramCtClass;
    }
    StringBuilder bodyBuilder = ThreadLocalStringBuilder.current();
    bodyBuilder.append("{\r\n");
    for (int i = 0; i < method.getParameterCount(); i++) {
        String paramName = parameters[i].getName();
        bodyBuilder.append("$0.");
        bodyBuilder.append(paramName);
        bodyBuilder.append(" = $");
        bodyBuilder.append(i + 1);
        bodyBuilder.append(";\r\n");
    }
    bodyBuilder.append("}");
    CtConstructor constructor1 = new CtConstructor(paramCtClassArray, methodParamCtClass);
    constructor1.setBody(bodyBuilder.toString());
    methodParamCtClass.addConstructor(constructor1);
    return (Class<? extends MethodParam>) methodParamCtClass.toClass();
}
Also used : CannotCompileException(javassist.CannotCompileException) Modifier(javassist.Modifier) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Hashing(com.google.common.hash.Hashing) CtClass(javassist.CtClass) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ConcurrentMap(java.util.concurrent.ConcurrentMap) Objects(java.util.Objects) CtField(javassist.CtField) CtNewMethod(javassist.CtNewMethod) Stream(java.util.stream.Stream) Parameter(java.lang.reflect.Parameter) CtConstructor(javassist.CtConstructor) NotFoundException(javassist.NotFoundException) ThreadLocalStringBuilder(rpc.turbo.util.concurrent.ThreadLocalStringBuilder) Method(java.lang.reflect.Method) ClassPool(javassist.ClassPool) ThreadLocalStringBuilder(rpc.turbo.util.concurrent.ThreadLocalStringBuilder) ClassPool(javassist.ClassPool) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) Parameter(java.lang.reflect.Parameter) CtClass(javassist.CtClass)

Example 58 with NotFoundException

use of javassist.NotFoundException in project incubator-servicecomb-java-chassis by apache.

the class JavassistUtils method detach.

// for test
public static void detach(String clsName) {
    try {
        ClassPool classPool = getOrCreateClassPool(Thread.currentThread().getContextClassLoader());
        classPool.getCtClass(clsName).detach();
    } catch (NotFoundException e) {
    // do nothing.
    }
}
Also used : ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException)

Example 59 with NotFoundException

use of javassist.NotFoundException in project compss by bsc-wdc.

the class ITAppEditor method edit.

/**
 * Replaces calls to remote methods by calls to executeTask or black-boxes methods
 */
public void edit(MethodCall mc) throws CannotCompileException {
    LOGGER.debug("---- BEGIN EDIT METHOD CALL " + mc.getMethodName() + " ----");
    Method declaredMethod = null;
    CtMethod calledMethod = null;
    try {
        calledMethod = mc.getMethod();
        declaredMethod = LoaderUtils.checkRemote(calledMethod, remoteMethods);
    } catch (NotFoundException e) {
        throw new CannotCompileException(e);
    }
    if (declaredMethod != null) {
        // Current method must be executed remotely, change the call
        if (DEBUG) {
            LOGGER.debug("Replacing task method call " + mc.getMethodName());
        }
        // Replace the call to the method by the call to executeTask
        String executeTask = replaceTaskMethodCall(mc.getMethodName(), mc.getClassName(), declaredMethod, calledMethod);
        if (DEBUG) {
            LOGGER.debug("Replacing task method call by " + executeTask);
        }
        mc.replace(executeTask);
    } else if (LoaderUtils.isStreamClose(mc)) {
        if (DEBUG) {
            LOGGER.debug("Replacing close on a stream of class " + mc.getClassName());
        }
        // Close call on a stream
        // No need to instrument the stream object, assuming it will always be local
        String streamClose = replaceCloseStream();
        if (DEBUG) {
            LOGGER.debug("Replacing stream close by " + streamClose);
        }
        mc.replace(streamClose);
    } else if (LoaderUtils.isFileDelete(mc)) {
        if (DEBUG) {
            LOGGER.debug("Replacing delete file");
        }
        String deleteFile = replaceDeleteFile();
        if (DEBUG) {
            LOGGER.debug("Replacing delete file by " + deleteFile);
        }
        mc.replace(deleteFile);
    } else if (mc.getClassName().equals(LoaderConstants.CLASS_COMPSS_API)) {
        // The method is an API call
        if (DEBUG) {
            LOGGER.debug("Replacing API call " + mc.getMethodName());
        }
        String modifiedAPICall = replaceAPICall(mc.getMethodName(), calledMethod);
        if (DEBUG) {
            LOGGER.debug("Replacing API call by " + modifiedAPICall);
        }
        mc.replace(modifiedAPICall);
    } else if (!LoaderUtils.contains(instrCandidates, calledMethod)) {
        // The method is a black box
        if (DEBUG) {
            LOGGER.debug("Replacing regular method call " + mc.getMethodName());
        }
        String modifiedCall = replaceBlackBox(mc.getMethodName(), mc.getClassName(), calledMethod);
        if (DEBUG) {
            LOGGER.debug("Replacing regular method call by " + modifiedCall);
        }
        mc.replace(modifiedCall);
    } else {
        // The method is an instrumented method
        if (DEBUG) {
            LOGGER.debug("Skipping instrumented method " + mc.getMethodName());
        }
    // Nothing to do
    }
    LOGGER.debug("---- END EDIT METHOD CALL ----");
}
Also used : NotFoundException(javassist.NotFoundException) CtMethod(javassist.CtMethod) Method(java.lang.reflect.Method) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Example 60 with NotFoundException

use of javassist.NotFoundException in project compss by bsc-wdc.

the class ITAppEditor method edit.

/**
 * Check the access to fields of objects
 */
@Override
public void edit(FieldAccess fa) throws CannotCompileException {
    CtField field = null;
    try {
        field = fa.getField();
        if (Modifier.isStatic(field.getModifiers())) {
            return;
        }
    } catch (NotFoundException e) {
        throw new CannotCompileException(e);
    }
    String fieldName = field.getName();
    if (DEBUG) {
        LOGGER.debug("Keeping track of access to field " + fieldName + " of class " + field.getDeclaringClass().getName());
    }
    boolean isWriter = fa.isWriter();
    // First check the object containing the field
    StringBuilder toInclude = new StringBuilder();
    toInclude.append(itORVar).append(NEW_OBJECT_ACCESS).append("$0,").append(isWriter).append(");");
    // Execute the access on the internal object
    String internalObject = itORVar + GET_INTERNAL_OBJECT + "$0)";
    String objectClass = fa.getClassName();
    toInclude.append("if (").append(internalObject).append(" != null) {");
    if (isWriter) {
        // store a new value in the field
        toInclude.append("((").append(objectClass).append(')').append(internalObject).append(").").append(fieldName).append(" = $1;");
        toInclude.append("} else { " + PROCEED + "$$); }");
        // Serialize the (internal) object locally after the access
        toInclude.append(itORVar).append(SERIALIZE_LOCALLY + "$0);");
    } else {
        // read the field value
        // read
        toInclude.append("$_ = ((").append(objectClass).append(')').append(internalObject).append(").").append(fieldName).append(';');
        toInclude.append("} else { " + PROCEED + "$$); }");
    }
    fa.replace(toInclude.toString());
    if (DEBUG) {
        LOGGER.debug("Replaced regular field access by " + toInclude.toString());
    }
}
Also used : CtField(javassist.CtField) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException)

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