Search in sources :

Example 36 with CtConstructor

use of javassist.CtConstructor in project afterburner by stephanenicolas.

the class AfterBurner method extractExistingConstructors.

private List<CtConstructor> extractExistingConstructors(final InsertableConstructor insertableConstructor) throws NotFoundException, AfterBurnerImpossibleException {
    List<CtConstructor> constructors = new ArrayList<CtConstructor>();
    CtConstructor[] declaredConstructors = insertableConstructor.getClassToInsertInto().getDeclaredConstructors();
    for (CtConstructor constructor : declaredConstructors) {
        CtClass[] paramClasses = constructor.getParameterTypes();
        if (insertableConstructor.acceptParameters(paramClasses)) {
            constructors.add(constructor);
        }
    }
    return constructors;
}
Also used : CtClass(javassist.CtClass) ArrayList(java.util.ArrayList) CtConstructor(javassist.CtConstructor)

Example 37 with CtConstructor

use of javassist.CtConstructor in project motech by motech.

the class EntityBuilderImpl method injectDefaultConstructor.

private void injectDefaultConstructor(CtClass ctClass) {
    CtConstructor[] constructors = ctClass.getDeclaredConstructors();
    // No constructors? Nothing to do here - Java will inject default one
    if (constructors.length == 0) {
        return;
    }
    try {
        for (CtConstructor constructor : constructors) {
            int parameters = constructor.getParameterTypes().length;
            int modifiers = constructor.getModifiers();
            if (parameters == 0 && Modifier.isPublic(modifiers)) {
                // Default constructor present? Nothing to do here.
                return;
            } else if (parameters == 0 && !Modifier.isPublic(modifiers)) {
                // If there's a default private or protected constructor, we remove it to create a public one
                ctClass.removeConstructor(constructor);
                break;
            }
        }
    } catch (NotFoundException e) {
        LOGGER.error("Could not read constructor parameters for class {}.", ctClass.getName());
    }
    // We create and inject default constructor
    try {
        CtConstructor defaultConstructor = CtNewConstructor.make(new CtClass[] {}, new CtClass[] {}, ctClass);
        ctClass.addConstructor(defaultConstructor);
    } catch (CannotCompileException e) {
        LOGGER.error("Could not create and insert default constructor for class {}.", ctClass.getName());
    }
}
Also used : NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtConstructor(javassist.CtConstructor)

Example 38 with CtConstructor

use of javassist.CtConstructor in project BIMserver by opensourceBIM.

the class RealtimeReflectorFactoryBuilder method build1.

private void build1(String newClassPrefix, Class<? extends PublicInterface> interfaceClass, org.bimserver.shared.meta.SService sService) {
    try {
        CtClass reflectorImplClass = pool.makeClass(GENERATED_CLASSES_PACKAGE + "." + interfaceClass.getSimpleName() + "Impl" + newClassPrefix);
        reflectorImplClass.addInterface(pool.get(interfaceClass.getName()));
        CtClass reflectorClass = pool.get(Reflector.class.getName());
        CtField reflectorField = new CtField(reflectorClass, "reflector", reflectorImplClass);
        reflectorImplClass.addField(reflectorField);
        CtConstructor constructor = new CtConstructor(new CtClass[] { reflectorClass }, reflectorImplClass);
        StringBuilder sb = new StringBuilder();
        reflectorImplClass.addConstructor(constructor);
        sb.append("{");
        sb.append("this.reflector = $1;");
        sb.append("}");
        constructor.setBody(sb.toString());
        for (SMethod sMethod : sService.getMethods()) {
            CtClass[] parameters = new CtClass[sMethod.getParameters().size()];
            int i = 0;
            for (org.bimserver.shared.meta.SParameter sParameter : sMethod.getParameters()) {
                parameters[i] = pool.get(sParameter.getType().toJavaCode());
                i++;
            }
            CtMethod method = new CtMethod(pool.get(sMethod.getReturnType().toJavaCode()), sMethod.getName(), parameters, reflectorImplClass);
            StringBuilder methodBuilder = new StringBuilder();
            methodBuilder.append("{");
            if (sMethod.getReturnType().isVoid()) {
            } else {
                methodBuilder.append("return (" + sMethod.getReturnType().toJavaCode() + ")");
            }
            methodBuilder.append("reflector.callMethod(\"" + interfaceClass.getSimpleName() + "\", \"" + sMethod.getName() + "\", " + sMethod.getReturnType().toJavaCode() + ".class");
            if (sMethod.getParameters().isEmpty()) {
                methodBuilder.append(", new " + KeyValuePair.class.getName() + "[0]");
            } else {
                methodBuilder.append(", new " + KeyValuePair.class.getName() + "[]{");
                int x = 1;
                for (SParameter sParameter : sMethod.getParameters()) {
                    methodBuilder.append("new " + KeyValuePair.class.getName() + "(\"" + sParameter.getName() + "\", $" + x + ")");
                    if (sMethod.getParameter(sMethod.getParameters().size() - 1) != sParameter) {
                        methodBuilder.append(", ");
                    }
                    x++;
                }
                methodBuilder.append("}");
            }
            methodBuilder.append(");");
            methodBuilder.append("}");
            method.setBody(methodBuilder.toString());
            reflectorImplClass.addMethod(method);
        }
        pool.toClass(reflectorImplClass, GeneratedNeighbourClass.class, getClass().getClassLoader(), getClass().getProtectionDomain());
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}
Also used : CannotCompileException(javassist.CannotCompileException) NotFoundException(javassist.NotFoundException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) SParameter(org.bimserver.shared.meta.SParameter) SMethod(org.bimserver.shared.meta.SMethod) SParameter(org.bimserver.shared.meta.SParameter) CtMethod(javassist.CtMethod)

Example 39 with CtConstructor

use of javassist.CtConstructor in project BIMserver by opensourceBIM.

the class RealtimeReflectorFactoryBuilder method build2.

private void build2(String newClassPrefix, Class<? extends PublicInterface> interfaceClass, org.bimserver.shared.meta.SService sService) {
    try {
        CtClass reflectorImplClass = pool.makeClass(GENERATED_CLASSES_PACKAGE + "." + interfaceClass.getSimpleName() + "Reflector" + newClassPrefix);
        CtClass reflectorClass = pool.get(Reflector.class.getName());
        CtClass interfaceCtClass = pool.get(interfaceClass.getName());
        reflectorImplClass.addInterface(reflectorClass);
        CtField reflectorField = new CtField(interfaceCtClass, "publicInterface", reflectorImplClass);
        reflectorImplClass.addField(reflectorField);
        CtConstructor constructor = new CtConstructor(new CtClass[] { interfaceCtClass }, reflectorImplClass);
        StringBuilder sb = new StringBuilder();
        reflectorImplClass.addConstructor(constructor);
        sb.append("{");
        sb.append("this.publicInterface = $1;");
        sb.append("}");
        constructor.setBody(sb.toString());
        CtClass[] parameters = new CtClass[4];
        parameters[0] = pool.get(String.class.getName());
        parameters[1] = pool.get(String.class.getName());
        parameters[2] = pool.get(Class.class.getName());
        parameters[3] = pool.get(KeyValuePair.class.getName() + "[]");
        CtMethod method = new CtMethod(pool.get(Object.class.getName()), "callMethod", parameters, reflectorImplClass);
        StringBuilder methodBuilder = new StringBuilder();
        methodBuilder.append("{");
        methodBuilder.append("if  (1==0) {} ");
        for (SMethod sMethod : sService.getMethods()) {
            methodBuilder.append(" else if ($2.equals(\"" + sMethod.getName() + "\")) {");
            if (!sMethod.getReturnType().isVoid()) {
                methodBuilder.append("return ");
            }
            methodBuilder.append("publicInterface." + sMethod.getName() + "(");
            int i = 0;
            for (SParameter sParameter : sMethod.getParameters()) {
                methodBuilder.append("(" + sParameter.getType().toJavaCode() + ")$4[" + i + "].getValue()");
                if (i < sMethod.getParameters().size() - 1) {
                    methodBuilder.append(", ");
                }
                i++;
            }
            methodBuilder.append(");");
            methodBuilder.append("}");
        }
        methodBuilder.append("return null;");
        methodBuilder.append("}");
        method.setBody(methodBuilder.toString());
        reflectorImplClass.addMethod(method);
        pool.toClass(reflectorImplClass, GeneratedNeighbourClass.class, getClass().getClassLoader(), getClass().getProtectionDomain());
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) SParameter(org.bimserver.shared.meta.SParameter) SMethod(org.bimserver.shared.meta.SMethod) CtMethod(javassist.CtMethod) CannotCompileException(javassist.CannotCompileException) NotFoundException(javassist.NotFoundException) CtConstructor(javassist.CtConstructor)

Example 40 with CtConstructor

use of javassist.CtConstructor in project incubator-skywalking by apache.

the class MeterSystem method create.

/**
 * Create streaming calculation of the given metrics name. This methods is synchronized due to heavy implementation
 * including creating dynamic class. Don't use this in concurrency runtime.
 *
 * @param metricsName  The name used as the storage eneity and in the query stage.
 * @param functionName The function provided through {@link MeterFunction}.
 * @throws IllegalArgumentException if the parameter can't match the expectation.
 * @throws UnexpectedException      if binary code manipulation fails or stream core failure.
 */
public synchronized <T> void create(String metricsName, String functionName, ScopeType type, Class<T> dataType) throws IllegalArgumentException {
    /**
     * Create a new meter class dynamically.
     */
    final Class<? extends AcceptableValue> meterFunction = functionRegister.get(functionName);
    if (meterFunction == null) {
        throw new IllegalArgumentException("Function " + functionName + " can't be found.");
    }
    boolean foundDataType = false;
    String acceptance = null;
    for (final Type genericInterface : meterFunction.getGenericInterfaces()) {
        if (genericInterface instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
            if (parameterizedType.getRawType().getTypeName().equals(AcceptableValue.class.getName())) {
                Type[] arguments = parameterizedType.getActualTypeArguments();
                if (arguments[0].equals(dataType)) {
                    foundDataType = true;
                } else {
                    acceptance = arguments[0].getTypeName();
                }
            }
            if (foundDataType) {
                break;
            }
        }
    }
    if (!foundDataType) {
        throw new IllegalArgumentException("Function " + functionName + " requires <" + acceptance + "> in AcceptableValue" + " but using " + dataType.getName() + " in the creation");
    }
    final CtClass parentClass;
    try {
        parentClass = classPool.get(meterFunction.getCanonicalName());
        if (!Metrics.class.isAssignableFrom(meterFunction)) {
            throw new IllegalArgumentException("Function " + functionName + " doesn't inherit from Metrics.");
        }
    } catch (NotFoundException e) {
        throw new IllegalArgumentException("Function " + functionName + " can't be found by javaassist.");
    }
    final String className = formatName(metricsName);
    /**
     * Check whether the metrics class is already defined or not
     */
    try {
        CtClass existingMetric = classPool.get(METER_CLASS_PACKAGE + className);
        if (existingMetric.getSuperclass() != parentClass || type != meterPrototypes.get(metricsName).getScopeType()) {
            throw new IllegalArgumentException(metricsName + " has been defined, but calculate function or/are scope type is/are different.");
        }
        log.info("Metric {} is already defined, so skip the metric creation.", metricsName);
        return;
    } catch (NotFoundException e) {
    }
    CtClass metricsClass = classPool.makeClass(METER_CLASS_PACKAGE + className, parentClass);
    /**
     * Create empty construct
     */
    try {
        CtConstructor defaultConstructor = CtNewConstructor.make("public " + className + "() {}", metricsClass);
        metricsClass.addConstructor(defaultConstructor);
    } catch (CannotCompileException e) {
        log.error("Can't add empty constructor in " + className + ".", e);
        throw new UnexpectedException(e.getMessage(), e);
    }
    /**
     * Generate `AcceptableValue<T> createNew()` method.
     */
    try {
        metricsClass.addMethod(CtNewMethod.make("" + "public org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue createNew() {" + "    org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue meterVar = new " + METER_CLASS_PACKAGE + className + "();" + "    ((org.apache.skywalking.oap.server.core.analysis.meter.Meter)meterVar).initMeta(\"" + metricsName + "\", " + type.getScopeId() + ");" + "    return meterVar;" + " }", metricsClass));
    } catch (CannotCompileException e) {
        log.error("Can't generate createNew method for " + className + ".", e);
        throw new UnexpectedException(e.getMessage(), e);
    }
    Class targetClass;
    try {
        if (SystemUtils.isJavaVersionAtMost(JavaVersion.JAVA_1_8)) {
            targetClass = metricsClass.toClass(MeterSystem.class.getClassLoader(), null);
        } else {
            targetClass = metricsClass.toClass(MeterClassPackageHolder.class);
        }
        AcceptableValue prototype = (AcceptableValue) targetClass.newInstance();
        meterPrototypes.put(metricsName, new MeterDefinition(type, prototype, dataType));
        log.debug("Generate metrics class, " + metricsClass.getName());
        MetricsStreamProcessor.getInstance().create(manager, new StreamDefinition(metricsName, type.getScopeId(), prototype.builder(), MetricsStreamProcessor.class), targetClass);
    } catch (CannotCompileException | IllegalAccessException | InstantiationException | StorageException e) {
        log.error("Can't compile/load/init " + className + ".", e);
        throw new UnexpectedException(e.getMessage(), e);
    }
}
Also used : UnexpectedException(org.apache.skywalking.oap.server.core.UnexpectedException) StreamDefinition(org.apache.skywalking.oap.server.core.analysis.StreamDefinition) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) MetricsStreamProcessor(org.apache.skywalking.oap.server.core.analysis.worker.MetricsStreamProcessor) CtConstructor(javassist.CtConstructor) ParameterizedType(java.lang.reflect.ParameterizedType) CtClass(javassist.CtClass) MeterClassPackageHolder(org.apache.skywalking.oap.server.core.analysis.meter.dynamic.MeterClassPackageHolder) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Metrics(org.apache.skywalking.oap.server.core.analysis.metrics.Metrics) AcceptableValue(org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue) CtClass(javassist.CtClass) StorageException(org.apache.skywalking.oap.server.core.storage.StorageException)

Aggregations

CtConstructor (javassist.CtConstructor)91 CtClass (javassist.CtClass)66 CtMethod (javassist.CtMethod)38 NotFoundException (javassist.NotFoundException)33 ClassPool (javassist.ClassPool)30 CtField (javassist.CtField)30 CannotCompileException (javassist.CannotCompileException)29 IOException (java.io.IOException)13 Method (java.lang.reflect.Method)9 ArrayList (java.util.ArrayList)7 FileNotFoundException (java.io.FileNotFoundException)6 CtNewMethod (javassist.CtNewMethod)6 MethodInfo (javassist.bytecode.MethodInfo)6 StorageException (org.apache.skywalking.oap.server.core.storage.StorageException)6 StringWriter (java.io.StringWriter)5 ConstPool (javassist.bytecode.ConstPool)5 HashMap (java.util.HashMap)4 Annotation (javassist.bytecode.annotation.Annotation)4 OALCompileException (org.apache.skywalking.oap.server.core.oal.rt.OALCompileException)4 ModuleStartException (org.apache.skywalking.oap.server.library.module.ModuleStartException)4