Search in sources :

Example 46 with CannotCompileException

use of javassist.CannotCompileException in project 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 47 with CannotCompileException

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

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

the class JavassistUtils method createClass.

public static Class<?> createClass(ClassLoader classLoader, ClassConfig config) {
    if (classLoader == null) {
        classLoader = Thread.currentThread().getContextClassLoader();
    }
    ClassPool classPool = getOrCreateClassPool(classLoader);
    CtClass ctClass = classPool.getOrNull(config.getClassName());
    if (ctClass == null) {
        if (config.isIntf()) {
            ctClass = classPool.makeInterface(config.getClassName());
        } else {
            ctClass = classPool.makeClass(config.getClassName());
        }
    }
    try {
        for (String intfName : config.getIntfList()) {
            ctClass.addInterface(classPool.get(intfName));
        }
        for (FieldConfig fieldConfig : config.getFieldList()) {
            CtField field = createCtField(classPool, ctClass, fieldConfig);
            ctClass.addField(field);
            if (fieldConfig.isGenGetter()) {
                addFieldGetter(config, fieldConfig);
            }
            if (fieldConfig.isGenSetter()) {
                addFieldSetter(config, fieldConfig);
            }
        }
        for (MethodConfig methodConfig : config.getMethodList()) {
            try {
                CtMethod ctMethod = CtMethod.make(methodConfig.getSource(), ctClass);
                if (methodConfig.getGenericSignature() != null) {
                    ctMethod.setGenericSignature(methodConfig.getGenericSignature());
                }
                ctClass.addMethod(ctMethod);
            } catch (CannotCompileException e) {
                LOGGER.error("Failed to create method, source:\n{}.", methodConfig.getSource());
                throw e;
            }
        }
        LOGGER.info("generate {} in classLoader {}.", config.getClassName(), classLoader);
        return ctClass.toClass(classLoader, null);
    } catch (Throwable e) {
        throw new Error(String.format("Failed to create %s in classLoader %s.", config.getClassName(), classLoader), e);
    }
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Example 49 with CannotCompileException

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

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

the class ITAppEditor method processReturnParameter.

/**
 * Process the return parameter of a given method call
 *
 * @param isVoid
 * @param numParams
 * @param retType
 * @return
 */
private ReturnInformation processReturnParameter(boolean isVoid, int numParams, Class<?> retType) throws CannotCompileException {
    StringBuilder infoToAppend = new StringBuilder("");
    StringBuilder infoToPrepend = new StringBuilder("");
    StringBuilder afterExecute = new StringBuilder("");
    if (!isVoid) {
        if (numParams > 1) {
            infoToAppend.append(',');
        }
        if (retType.isPrimitive()) {
            /*
                 * ********************************* PRIMITIVE *********************************
                 */
            String tempRetVar = "ret" + System.nanoTime();
            infoToAppend.append(tempRetVar).append(',').append(DATA_TYPES + ".OBJECT_T").append(',').append(DATA_DIRECTION + ".OUT").append(',').append(DATA_STREAM + "." + Stream.UNSPECIFIED).append(',').append("\"").append(Constants.PREFIX_EMTPY).append("\"");
            String retValueCreation = "Object " + tempRetVar + " = ";
            String cast;
            String converterMethod;
            if (retType.isAssignableFrom(boolean.class)) {
                retValueCreation += "new Boolean(false);";
                cast = "(Boolean)";
                converterMethod = "booleanValue()";
            } else if (retType.isAssignableFrom(char.class)) {
                retValueCreation += "new Character(Character.MIN_VALUE);";
                cast = "(Character)";
                converterMethod = "charValue()";
            } else if (retType.isAssignableFrom(byte.class)) {
                retValueCreation += "new Byte(Byte.MIN_VALUE);";
                cast = "(Byte)";
                converterMethod = "byteValue()";
            } else if (retType.isAssignableFrom(short.class)) {
                retValueCreation += "new Short(Short.MIN_VALUE);";
                cast = "(Short)";
                converterMethod = "shortValue()";
            } else if (retType.isAssignableFrom(int.class)) {
                retValueCreation += "new Integer(Integer.MIN_VALUE);";
                cast = "(Integer)";
                converterMethod = "intValue()";
            } else if (retType.isAssignableFrom(long.class)) {
                retValueCreation += "new Long(Long.MIN_VALUE);";
                cast = "(Long)";
                converterMethod = "longValue()";
            } else if (retType.isAssignableFrom(float.class)) {
                retValueCreation += "new Float(Float.MIN_VALUE);";
                cast = "(Float)";
                converterMethod = "floatValue()";
            } else {
                // (retType.isAssignableFrom(double.class))
                retValueCreation += "new Double(Double.MIN_VALUE);";
                cast = "(Double)";
                converterMethod = "doubleValue()";
            }
            // Before paramsModified, declare and instance a temp wrapper object containing the primitive value
            infoToPrepend.insert(0, retValueCreation);
            /*
                 * After execute task, register an access to the wrapper object, get its (remotely) generated value and
                 * assign it to the application's primitive type var
                 */
            afterExecute.append(itORVar).append(NEW_OBJECT_ACCESS).append(tempRetVar).append(");");
            afterExecute.append("$_ = (").append(cast).append(itORVar).append(GET_INTERNAL_OBJECT).append(tempRetVar).append(")).").append(converterMethod).append(";");
        } else if (retType.isArray()) {
            /*
                 * ********************************* ARRAY
                 *********************************/
            String typeName = retType.getName();
            Class<?> compType = retType.getComponentType();
            int numDim = typeName.lastIndexOf('[');
            String dims = "[0]";
            while (numDim-- > 0) {
                dims += "[]";
            }
            while (compType.getComponentType() != null) {
                compType = compType.getComponentType();
            }
            String compTypeName = compType.getName();
            infoToPrepend.insert(0, "$_ = new " + compTypeName + dims + ';');
            infoToAppend.append("$_,").append(DATA_TYPES + ".OBJECT_T");
            infoToAppend.append(',').append(DATA_DIRECTION + ".OUT");
            infoToAppend.append(',').append(DATA_STREAM + ".UNSPECIFIED");
            infoToAppend.append(',').append("\"").append(Constants.PREFIX_EMTPY).append("\"");
        } else {
            // Wrapper for a primitive type: return a default value
            if (retType.isAssignableFrom(Boolean.class)) {
                infoToPrepend.insert(0, "$_ = new Boolean(false);");
            } else if (retType.isAssignableFrom(Character.class)) {
                infoToPrepend.insert(0, "$_ = new Character(Character.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Byte.class)) {
                infoToPrepend.insert(0, "$_ = new Byte(Byte.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Short.class)) {
                infoToPrepend.insert(0, "$_ = new Short(Short.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Integer.class)) {
                infoToPrepend.insert(0, "$_ = new Integer(Integer.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Long.class)) {
                infoToPrepend.insert(0, "$_ = new Long(Long.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Float.class)) {
                infoToPrepend.insert(0, "$_ = new Float(Float.MIN_VALUE);");
            } else if (retType.isAssignableFrom(Double.class)) {
                infoToPrepend.insert(0, "$_ = new Double(Double.MIN_VALUE);");
            } else // Object (maybe String): use the no-args constructor
            {
                // Check that object class has empty constructor
                String typeName = retType.getName();
                try {
                    Class.forName(typeName).getConstructor();
                } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
                    throw new CannotCompileException(ERROR_NO_EMTPY_CONSTRUCTOR + typeName);
                }
                infoToPrepend.insert(0, "$_ = new " + typeName + "();");
            }
            infoToAppend.append("$_,").append(CHECK_SCO_TYPE + "$_)");
            // Add direction
            infoToAppend.append(',').append(DATA_DIRECTION + ".OUT");
            // Add stream binary
            infoToAppend.append(',').append(DATA_STREAM + ".UNSPECIFIED");
            // Add empty prefix
            infoToAppend.append(',').append("\"").append(Constants.PREFIX_EMTPY).append("\"");
        }
    }
    ReturnInformation returnInfo = new ReturnInformation(infoToAppend.toString(), infoToPrepend.toString(), afterExecute.toString());
    return returnInfo;
}
Also used : CannotCompileException(javassist.CannotCompileException) CtClass(javassist.CtClass)

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