Search in sources :

Example 76 with ClassPool

use of javassist.ClassPool in project dubbo by alibaba.

the class JValidator method getMethodParameterBean.

private static Object getMethodParameterBean(Class<?> clazz, Method method, Object[] args) {
    if (!hasConstraintParameter(method)) {
        return null;
    }
    try {
        String parameterClassName = generateMethodParameterClassName(clazz, method);
        Class<?> parameterClass;
        try {
            parameterClass = (Class<?>) Class.forName(parameterClassName, true, clazz.getClassLoader());
        } catch (ClassNotFoundException e) {
            ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader());
            CtClass ctClass = pool.makeClass(parameterClassName);
            ClassFile classFile = ctClass.getClassFile();
            classFile.setVersionToJava5();
            ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName)));
            // parameter fields
            Class<?>[] parameterTypes = method.getParameterTypes();
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> type = parameterTypes[i];
                Annotation[] annotations = parameterAnnotations[i];
                AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
                        javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation(classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName()));
                        Method[] members = annotation.annotationType().getMethods();
                        for (Method member : members) {
                            if (Modifier.isPublic(member.getModifiers()) && member.getParameterTypes().length == 0 && member.getDeclaringClass() == annotation.annotationType()) {
                                Object value = member.invoke(annotation, new Object[0]);
                                if (null != value) {
                                    MemberValue memberValue = createMemberValue(classFile.getConstPool(), pool.get(member.getReturnType().getName()), value);
                                    ja.addMemberValue(member.getName(), memberValue);
                                }
                            }
                        }
                        attribute.addAnnotation(ja);
                    }
                }
                String fieldName = method.getName() + "Argument" + i;
                CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName));
                ctField.getFieldInfo().addAttribute(attribute);
                ctClass.addField(ctField);
            }
            parameterClass = ctClass.toClass(clazz.getClassLoader(), null);
        }
        Object parameterBean = parameterClass.newInstance();
        for (int i = 0; i < args.length; i++) {
            Field field = parameterClass.getField(method.getName() + "Argument" + i);
            field.set(parameterBean, args[i]);
        }
        return parameterBean;
    } catch (Throwable e) {
        logger.warn(e.getMessage(), e);
        return null;
    }
}
Also used : ClassFile(javassist.bytecode.ClassFile) Constraint(javax.validation.Constraint) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) Constraint(javax.validation.Constraint) CtClass(javassist.CtClass) Field(java.lang.reflect.Field) CtField(javassist.CtField) MemberValue(javassist.bytecode.annotation.MemberValue) ArrayMemberValue(javassist.bytecode.annotation.ArrayMemberValue) CharMemberValue(javassist.bytecode.annotation.CharMemberValue) BooleanMemberValue(javassist.bytecode.annotation.BooleanMemberValue) FloatMemberValue(javassist.bytecode.annotation.FloatMemberValue) DoubleMemberValue(javassist.bytecode.annotation.DoubleMemberValue) ShortMemberValue(javassist.bytecode.annotation.ShortMemberValue) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) IntegerMemberValue(javassist.bytecode.annotation.IntegerMemberValue) LongMemberValue(javassist.bytecode.annotation.LongMemberValue) ClassMemberValue(javassist.bytecode.annotation.ClassMemberValue) EnumMemberValue(javassist.bytecode.annotation.EnumMemberValue) ByteMemberValue(javassist.bytecode.annotation.ByteMemberValue) CtField(javassist.CtField) CtClass(javassist.CtClass)

Example 77 with ClassPool

use of javassist.ClassPool in project incubator-systemml by apache.

the class GenerateClassesForMLContext method createScriptClass.

/**
 * Convert a script file to a Java class that extends the MLContext API's
 * Script class.
 *
 * @param scriptFilePath
 *            the path to a script file
 */
public static void createScriptClass(String scriptFilePath) {
    try {
        String fullScriptClassName = BASE_DEST_PACKAGE + "." + scriptFilePathToFullClassNameNoBase(scriptFilePath);
        System.out.println("Generating Class: " + fullScriptClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctNewScript = pool.makeClass(fullScriptClassName);
        CtClass ctScript = pool.get(Script.class.getName());
        ctNewScript.setSuperclass(ctScript);
        CtConstructor ctCon = new CtConstructor(null, ctNewScript);
        ctCon.setBody(scriptConstructorBody(scriptFilePath));
        ctNewScript.addConstructor(ctCon);
        addFunctionMethods(scriptFilePath, ctNewScript);
        ctNewScript.writeFile(destination);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
}
Also used : CtClass(javassist.CtClass) Script(org.apache.sysml.api.mlcontext.Script) DMLScript(org.apache.sysml.api.DMLScript) ClassPool(javassist.ClassPool) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException) CtConstructor(javassist.CtConstructor)

Example 78 with ClassPool

use of javassist.ClassPool in project incubator-systemml by apache.

the class GenerateClassesForMLContext method createFunctionOutputClass.

/**
 * Create a class that encapsulates the outputs of a function.
 *
 * @param scriptFilePath
 *            the path to a script file
 * @param fs
 *            a SystemML function statement
 */
public static void createFunctionOutputClass(String scriptFilePath, FunctionStatement fs) {
    try {
        ArrayList<DataIdentifier> oparams = fs.getOutputParams();
        // than encapsulating it in a function output class
        if ((oparams.size() == 0) || (oparams.size() == 1)) {
            return;
        }
        String fullFunctionOutputClassName = getFullFunctionOutputClassName(scriptFilePath, fs);
        System.out.println("Generating Class: " + fullFunctionOutputClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctFuncOut = pool.makeClass(fullFunctionOutputClassName);
        // add fields
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            String fstring = "public " + type + " " + name + ";";
            CtField field = CtField.make(fstring, ctFuncOut);
            ctFuncOut.addField(field);
        }
        // add constructor
        String simpleFuncOutClassName = fullFunctionOutputClassName.substring(fullFunctionOutputClassName.lastIndexOf(".") + 1);
        StringBuilder con = new StringBuilder();
        con.append("public " + simpleFuncOutClassName + "(");
        for (int i = 0; i < oparams.size(); i++) {
            if (i > 0) {
                con.append(", ");
            }
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            con.append(type + " " + name);
        }
        con.append(") {\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            con.append("this." + name + "=" + name + ";\n");
        }
        con.append("}\n");
        String cstring = con.toString();
        CtConstructor ctCon = CtNewConstructor.make(cstring, ctFuncOut);
        ctFuncOut.addConstructor(ctCon);
        // add toString
        StringBuilder s = new StringBuilder();
        s.append("public String toString(){\n");
        s.append("StringBuilder sb = new StringBuilder();\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            s.append("sb.append(\"" + name + " (" + getSimpleParamTypeAsString(oparam) + "): \" + " + name + " + \"\\n\");\n");
        }
        s.append("String str = sb.toString();\nreturn str;\n");
        s.append("}\n");
        String toStr = s.toString();
        CtMethod toStrMethod = CtNewMethod.make(toStr, ctFuncOut);
        ctFuncOut.addMethod(toStrMethod);
        ctFuncOut.writeFile(destination);
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : DataIdentifier(org.apache.sysml.parser.DataIdentifier) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) CtMethod(javassist.CtMethod)

Example 79 with ClassPool

use of javassist.ClassPool in project incubator-systemml by apache.

the class GenerateClassesForMLContext method recurseDirectoriesForConvenienceClassGeneration.

/**
 * Generate convenience classes recursively. This allows for code such as
 * {@code ml.scripts.algorithms...}.
 *
 * @param dirPath
 *            path to directory
 * @return the full name of the class representing the dirPath directory
 */
public static String recurseDirectoriesForConvenienceClassGeneration(String dirPath) {
    try {
        File dir = new File(dirPath);
        String fullDirClassName = dirPathToFullDirClassName(dirPath);
        System.out.println("Generating Class: " + fullDirClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctDir = pool.makeClass(fullDirClassName);
        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 = recurseDirectoriesForConvenienceClassGeneration(subDirPath);
            CtClass subDirClass = pool.get(fullSubDirClassName);
            String subDirName = subdir.getName();
            subDirName = subDirName.replaceAll("-", "_");
            subDirName = subDirName.toLowerCase();
            System.out.println("Adding " + subDirName + "() to " + fullDirClassName);
            String methodBody = "{ " + fullSubDirClassName + " z = new " + fullSubDirClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, subDirClass, subDirName, null, null, methodBody, ctDir);
            ctDir.addMethod(ctMethod);
        }
        File[] scriptFiles = dir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return (name.toLowerCase().endsWith(".dml") || name.toLowerCase().endsWith(".pydml"));
            }
        });
        for (File scriptFile : scriptFiles) {
            String scriptFilePath = scriptFile.getPath();
            String fullScriptClassName = BASE_DEST_PACKAGE + "." + scriptFilePathToFullClassNameNoBase(scriptFilePath);
            CtClass scriptClass = pool.get(fullScriptClassName);
            String methodName = scriptFilePathToSimpleClassName(scriptFilePath);
            String methodBody = "{ " + fullScriptClassName + " z = new " + fullScriptClassName + "(); return z; }";
            CtMethod ctMethod = CtNewMethod.make(Modifier.PUBLIC, scriptClass, methodName, null, null, methodBody, ctDir);
            ctDir.addMethod(ctMethod);
        }
        ctDir.writeFile(destination);
        return fullDirClassName;
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtClass(javassist.CtClass) FilenameFilter(java.io.FilenameFilter) FileFilter(java.io.FileFilter) File(java.io.File) CtMethod(javassist.CtMethod)

Example 80 with ClassPool

use of javassist.ClassPool in project drill by axbaretto.

the class GuavaPatcher method patchStopwatch.

/**
 * Makes Guava stopwatch look like the old version for compatibility with hbase-server (for test purposes).
 */
private static void patchStopwatch() throws Exception {
    ClassPool cp = ClassPool.getDefault();
    CtClass cc = cp.get("com.google.common.base.Stopwatch");
    // Expose the constructor for Stopwatch for old libraries who use the pattern new Stopwatch().start().
    for (CtConstructor c : cc.getConstructors()) {
        if (!Modifier.isStatic(c.getModifiers())) {
            c.setModifiers(Modifier.PUBLIC);
        }
    }
    // Add back the Stopwatch.elapsedMillis() method for old consumers.
    CtMethod newmethod = CtNewMethod.make("public long elapsedMillis() { return elapsed(java.util.concurrent.TimeUnit.MILLISECONDS); }", cc);
    cc.addMethod(newmethod);
    // Load the modified class instead of the original.
    cc.toClass();
    logger.info("Google's Stopwatch patched for old HBase Guava version.");
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Aggregations

ClassPool (javassist.ClassPool)120 CtClass (javassist.CtClass)93 CtMethod (javassist.CtMethod)48 NotFoundException (javassist.NotFoundException)40 CannotCompileException (javassist.CannotCompileException)28 IOException (java.io.IOException)23 LoaderClassPath (javassist.LoaderClassPath)21 CtField (javassist.CtField)20 CtConstructor (javassist.CtConstructor)17 Test (org.junit.Test)17 ClassFile (javassist.bytecode.ClassFile)15 File (java.io.File)13 Method (java.lang.reflect.Method)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ConstPool (javassist.bytecode.ConstPool)12 FileNotFoundException (java.io.FileNotFoundException)11 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)9 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)9 ClassClassPath (javassist.ClassClassPath)7 MethodInfo (javassist.bytecode.MethodInfo)7