Search in sources :

Example 16 with CannotCompileException

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

the class GenerateClassesForMLContext method addDescriptionFunctionCallMethod.

/**
 * Create a method that returns either: (1) the full function body, or (2)
 * the function body up to the end of the documentation comment for the
 * function. If (1) is generated, the method name will be followed
 * "__source". If (2) is generated, the method name will be followed by
 * "__docs". If (2) is generated but no end of documentation comment is
 * detected, the full function body will be displayed.
 *
 * @param fs
 *            a SystemML function statement
 * @param scriptFilePath
 *            the path to a script file
 * @param ctNewScript
 *            the javassist compile-time class representation of a script
 * @param full
 *            if {@code true}, create method to return full function body;
 *            if {@code false}, create method to return the function body up
 *            to the end of the documentation comment
 */
public static void addDescriptionFunctionCallMethod(FunctionStatement fs, String scriptFilePath, CtClass ctNewScript, boolean full) {
    try {
        int bl = fs.getBeginLine();
        int el = fs.getEndLine();
        File f = new File(scriptFilePath);
        List<String> lines = FileUtils.readLines(f);
        int end = el;
        if (!full) {
            for (int i = bl - 1; i < el; i++) {
                String line = lines.get(i);
                if (line.contains("*/")) {
                    end = i + 1;
                    break;
                }
            }
        }
        List<String> sub = lines.subList(bl - 1, end);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sub.size(); i++) {
            String line = sub.get(i);
            String escapeLine = StringEscapeUtils.escapeJava(line);
            sb.append(escapeLine);
            sb.append("\\n");
        }
        String functionString = sb.toString();
        String docFunctionCallMethod = generateDescriptionFunctionCallMethod(fs, functionString, full);
        CtMethod m = CtNewMethod.make(docFunctionCallMethod, ctNewScript);
        ctNewScript.addMethod(m);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }
}
Also used : IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException) File(java.io.File) CtMethod(javassist.CtMethod)

Example 17 with CannotCompileException

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

the class GenerateClassesForMLContext method addFunctionMethods.

/**
 * Add methods to a derived script class to allow invocation of script
 * functions.
 *
 * @param scriptFilePath
 *            the path to a script file
 * @param ctNewScript
 *            the javassist compile-time class representation of a script
 */
public static void addFunctionMethods(String scriptFilePath, CtClass ctNewScript) {
    try {
        DMLProgram dmlProgram = dmlProgramFromScriptFilePath(scriptFilePath);
        if (dmlProgram == null) {
            System.out.println("Could not generate DML Program for: " + scriptFilePath);
            return;
        }
        Map<String, FunctionStatementBlock> defaultNsFsbsMap = dmlProgram.getFunctionStatementBlocks(DMLProgram.DEFAULT_NAMESPACE);
        List<FunctionStatementBlock> fsbs = new ArrayList<>();
        fsbs.addAll(defaultNsFsbsMap.values());
        for (FunctionStatementBlock fsb : fsbs) {
            ArrayList<Statement> sts = fsb.getStatements();
            for (Statement st : sts) {
                if (!(st instanceof FunctionStatement)) {
                    continue;
                }
                FunctionStatement fs = (FunctionStatement) st;
                String dmlFunctionCall = generateDmlFunctionCall(scriptFilePath, fs);
                String functionCallMethod = generateFunctionCallMethod(scriptFilePath, fs, dmlFunctionCall);
                CtMethod m = CtNewMethod.make(functionCallMethod, ctNewScript);
                ctNewScript.addMethod(m);
                addDescriptionFunctionCallMethod(fs, scriptFilePath, ctNewScript, false);
                addDescriptionFunctionCallMethod(fs, scriptFilePath, ctNewScript, true);
            }
        }
    } catch (LanguageException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    } catch (CannotCompileException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    } catch (RuntimeException e) {
        System.out.println("Could not add function methods for " + ctNewScript.getName());
    }
}
Also used : FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) FunctionStatement(org.apache.sysml.parser.FunctionStatement) Statement(org.apache.sysml.parser.Statement) ArrayList(java.util.ArrayList) CannotCompileException(javassist.CannotCompileException) LanguageException(org.apache.sysml.parser.LanguageException) FunctionStatement(org.apache.sysml.parser.FunctionStatement) DMLProgram(org.apache.sysml.parser.DMLProgram) CtMethod(javassist.CtMethod)

Example 18 with CannotCompileException

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

use of javassist.CannotCompileException in project hibernate-orm by hibernate.

the class MethodWriter method addGetter.

/* --- */
public static CtMethod addGetter(CtClass target, String field, String name) {
    CtField actualField = null;
    try {
        actualField = target.getField(field);
        log.debugf("Writing getter method [%s] into [%s] for field [%s]", name, target.getName(), field);
        CtMethod method = CtNewMethod.getter(name, target.getField(field));
        target.addMethod(method);
        return method;
    } catch (CannotCompileException cce) {
        try {
            // Fall back to create a getter from delegation.
            CtMethod method = CtNewMethod.delegator(CtNewMethod.getter(name, actualField), target);
            target.addMethod(method);
            return method;
        } catch (CannotCompileException ignored) {
            String msg = String.format("Could not enhance class [%s] to add method [%s] for field [%s]", target.getName(), name, field);
            throw new EnhancementException(msg, cce);
        }
    } catch (NotFoundException nfe) {
        String msg = String.format("Could not enhance class [%s] to add method [%s] for field [%s]", target.getName(), name, field);
        throw new EnhancementException(msg, nfe);
    }
}
Also used : CtField(javassist.CtField) EnhancementException(org.hibernate.bytecode.enhance.spi.EnhancementException) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Example 20 with CannotCompileException

use of javassist.CannotCompileException in project hibernate-orm by hibernate.

the class PersistentAttributesEnhancer method generateFieldReader.

protected CtMethod generateFieldReader(CtClass managedCtClass, CtField persistentField, AttributeTypeDescriptor typeDescriptor) {
    String fieldName = persistentField.getName();
    String readerName = EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + fieldName;
    String writerName = EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + fieldName;
    CtMethod tmpSuperReader = null;
    CtMethod tmpSuperWriter = null;
    CtMethod reader = null;
    try {
        boolean declared = persistentField.getDeclaringClass().equals(managedCtClass);
        String declaredReadFragment = "this." + fieldName + "";
        String superReadFragment = "super." + readerName + "()";
        if (!declared) {
            // create a temporary getter on the supper entity to be able to compile our code
            try {
                persistentField.getDeclaringClass().getDeclaredMethod(readerName);
                persistentField.getDeclaringClass().getDeclaredMethod(writerName);
            } catch (NotFoundException nfe) {
                tmpSuperReader = MethodWriter.addGetter(persistentField.getDeclaringClass(), persistentField.getName(), readerName);
                tmpSuperWriter = MethodWriter.addSetter(persistentField.getDeclaringClass(), persistentField.getName(), writerName);
            }
        }
        // so if the field is not enabled as lazy-loadable return a plain simple getter as the reader
        if (!enhancementContext.hasLazyLoadableAttributes(managedCtClass) || !enhancementContext.isLazyLoadable(persistentField)) {
            reader = MethodWriter.write(managedCtClass, "public %s %s() {  return %s;%n}", persistentField.getType().getName(), readerName, declared ? declaredReadFragment : superReadFragment);
        } else {
            reader = MethodWriter.write(managedCtClass, "public %s %s() {%n%s%n  return %s;%n}", persistentField.getType().getName(), readerName, typeDescriptor.buildReadInterceptionBodyFragment(fieldName), declared ? declaredReadFragment : superReadFragment);
        }
        if (tmpSuperReader != null) {
            persistentField.getDeclaringClass().removeMethod(tmpSuperReader);
        }
        if (tmpSuperWriter != null) {
            persistentField.getDeclaringClass().removeMethod(tmpSuperWriter);
        }
        return reader;
    } catch (CannotCompileException cce) {
        final String msg = String.format("Could not enhance entity class [%s] to add field reader method [%s]", managedCtClass.getName(), readerName);
        throw new EnhancementException(msg, cce);
    } catch (NotFoundException nfe) {
        final String msg = String.format("Could not enhance entity class [%s] to add field reader method [%s]", managedCtClass.getName(), readerName);
        throw new EnhancementException(msg, nfe);
    }
}
Also used : EnhancementException(org.hibernate.bytecode.enhance.spi.EnhancementException) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Aggregations

CannotCompileException (javassist.CannotCompileException)29 NotFoundException (javassist.NotFoundException)20 CtClass (javassist.CtClass)18 CtMethod (javassist.CtMethod)16 ClassPool (javassist.ClassPool)10 IOException (java.io.IOException)8 CtField (javassist.CtField)8 EnhancementException (org.hibernate.bytecode.enhance.spi.EnhancementException)5 FileNotFoundException (java.io.FileNotFoundException)4 File (java.io.File)3 CtConstructor (javassist.CtConstructor)3 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 FileFilter (java.io.FileFilter)2 AsyncProvider (com.google.gwt.inject.client.AsyncProvider)1 AsyncCallback (com.google.gwt.user.client.rpc.AsyncCallback)1