Java Code Examples for org.jboss.jandex.MethodInfo#name()

The following examples show how to use org.jboss.jandex.MethodInfo#name() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Annotations.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
/**
 * Used when we are creating operation and arguments for these operations
 * 
 * @param methodInfo the java method
 * @param pos the argument position
 * @return annotation for this argument
 */
public static Annotations getAnnotationsForArgument(MethodInfo methodInfo, short pos) {
    if (pos >= methodInfo.parameters().size()) {
        throw new IndexOutOfBoundsException(
                "Parameter at position " + pos + " not found on method " + methodInfo.name());
    }

    final org.jboss.jandex.Type parameterType = methodInfo.parameters().get(pos);

    Map<DotName, AnnotationInstance> annotationMap = new HashMap<>();

    annotationMap.putAll(getAnnotations(parameterType));

    for (AnnotationInstance anno : methodInfo.annotations()) {
        if (anno.target().kind().equals(AnnotationTarget.Kind.METHOD_PARAMETER)) {
            MethodParameterInfo methodParameter = anno.target().asMethodParameter();
            short position = methodParameter.position();
            if (position == pos) {
                annotationMap.put(anno.name(), anno);
            }
        }
    }

    return new Annotations(annotationMap);
}
 
Example 2
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void checkTemplatePath(String templatePath, List<TemplatePathBuildItem> templatePaths, ClassInfo enclosingClass,
        MethodInfo methodInfo) {
    for (TemplatePathBuildItem templatePathBuildItem : templatePaths) {
        // perfect match
        if (templatePathBuildItem.getPath().equals(templatePath)) {
            return;
        }
        // if our templatePath is "Foo/hello", make it match "Foo/hello.txt"
        // if they're not equal and they start with our path, there must be something left after
        if (templatePathBuildItem.getPath().startsWith(templatePath)
                // check that we have an extension, let variant matching work later
                && templatePathBuildItem.getPath().charAt(templatePath.length()) == '.') {
            return;
        }
    }
    throw new TemplateException(
            "Declared template " + templatePath + " could not be found. Either add it or delete its declaration in "
                    + enclosingClass.name().toString('.') + "." + methodInfo.name());
}
 
Example 3
Source File: SpringSecurityProcessorUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static int getParameterIndex(MethodInfo methodInfo, String parameterName, String expression) {
    int parametersCount = methodInfo.parameters().size();
    int matchingParameterIndex = -1;
    for (int i = 0; i < parametersCount; i++) {
        if (parameterName.equals(methodInfo.parameterName(i))) {
            matchingParameterIndex = i;
            break;
        }
    }

    if (matchingParameterIndex == -1) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references parameter " + parameterName
                        + " that the method does not declare");
    }
    return matchingParameterIndex;
}
 
Example 4
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether a method follows the Java bean convention for an accessor
 * method (getter). The method name typically begins with "get", but may also
 * begin with "is" when the return type is boolean.
 *
 * @param method the method to check
 * @return true if the method is a Java bean getter, otherwise false
 */
private static boolean isAccessor(MethodInfo method) {
    Type returnType = method.returnType();

    if (!method.parameters().isEmpty() || Type.Kind.VOID.equals(returnType.kind())) {
        return false;
    }

    String methodName = method.name();

    if (methodName.startsWith("get")) {
        return true;
    }

    return methodName.startsWith("is") && TypeUtil.equalTypes(returnType, BOOLEAN_TYPE);
}
 
Example 5
Source File: StringPropertyAccessorData.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Called with data parsed from a Spring expression like #person.name that is places inside a Spring security annotation on
 * a method
 */
static StringPropertyAccessorData from(MethodInfo methodInfo, int matchingParameterIndex, String propertyName,
        IndexView index, String expression) {
    Type matchingParameterType = methodInfo.parameters().get(matchingParameterIndex);
    ClassInfo matchingParameterClassInfo = index.getClassByName(matchingParameterType.name());
    if (matchingParameterClassInfo == null) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references class "
                        + matchingParameterType.name() + " which could not be in Jandex");
    }
    FieldInfo matchingParameterFieldInfo = matchingParameterClassInfo.field(propertyName);
    if (matchingParameterFieldInfo == null) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references unknown property '"
                        + propertyName + "' of class " + matchingParameterClassInfo);
    }
    if (!DotNames.STRING.equals(matchingParameterFieldInfo.type().name())) {
        throw new IllegalArgumentException(
                "Expression: '" + expression + "' in the @PreAuthorize annotation on method '" + methodInfo.name()
                        + "' of class '" + methodInfo.declaringClass() + "' references property '"
                        + propertyName + "' which is not a string");
    }

    return new StringPropertyAccessorData(matchingParameterClassInfo, matchingParameterFieldInfo);
}
 
Example 6
Source File: SpringSecurityProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void checksStandardSecurity(AnnotationInstance instance, MethodInfo methodInfo) {
    if (SecurityTransformerUtils.hasStandardSecurityAnnotation(methodInfo)) {
        Optional<AnnotationInstance> firstStandardSecurityAnnotation = SecurityTransformerUtils
                .findFirstStandardSecurityAnnotation(methodInfo);
        if (firstStandardSecurityAnnotation.isPresent()) {
            String securityAnnotationName = SecurityTransformerUtils.findFirstStandardSecurityAnnotation(methodInfo).get()
                    .name()
                    .withoutPackagePrefix();
            throw new IllegalArgumentException("An invalid security annotation combination was detected: Found "
                    + instance.name().withoutPackagePrefix() + " and " + securityAnnotationName + " on method "
                    + methodInfo.name());
        }
    }
}
 
Example 7
Source File: Methods.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static NameAndDescriptor fromMethodInfo(MethodInfo method) {
    String returnTypeDesc = DescriptorUtils.objectToDescriptor(method.returnType().name().toString());
    String[] paramTypesDesc = new String[(method.parameters().size())];
    for (int i = 0; i < method.parameters().size(); i++) {
        paramTypesDesc[i] = DescriptorUtils.objectToDescriptor(method.parameters().get(i).name().toString());
    }

    return new NameAndDescriptor(method.name(),
            DescriptorUtils.methodSignatureToDescriptor(returnTypeDesc, paramTypesDesc));
}
 
Example 8
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the "value" parameter from annotation to be used as the name.
 * If no value was specified or an empty value, return the name of the annotation
 * target.
 *
 * @param annotation parameter annotation
 * @return the name of the parameter
 */
static String paramName(AnnotationInstance annotation) {
    AnnotationValue value = annotation.value();
    String valueString = null;

    if (value != null) {
        valueString = value.asString();
        if (valueString.length() > 0) {
            return valueString;
        }
    }

    AnnotationTarget target = annotation.target();

    switch (target.kind()) {
        case FIELD:
            valueString = target.asField().name();
            break;
        case METHOD_PARAMETER:
            valueString = target.asMethodParameter().name();
            break;
        case METHOD:
            // This is a bean property setter
            MethodInfo method = target.asMethod();
            if (method.parameters().size() == 1) {
                String methodName = method.name();

                if (methodName.startsWith("set")) {
                    valueString = Introspector.decapitalize(methodName.substring(3));
                } else {
                    valueString = methodName;
                }
            }
            break;
        default:
            break;
    }

    return valueString;
}
 
Example 9
Source File: ParameterProcessor.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the "value" parameter from annotation to be used as the name.
 * If no value was specified or an empty value, return the name of the annotation
 * target.
 *
 * @param annotation parameter annotation
 * @return the name of the parameter
 */
static String paramName(AnnotationInstance annotation) {
    AnnotationValue value = annotation.value();
    String valueString = null;

    if (value != null) {
        valueString = value.asString();
        if (valueString.length() > 0) {
            return valueString;
        }
    }

    AnnotationTarget target = annotation.target();

    switch (target.kind()) {
        case FIELD:
            valueString = target.asField().name();
            break;
        case METHOD_PARAMETER:
            valueString = target.asMethodParameter().name();
            break;
        case METHOD:
            // This is a bean property setter
            MethodInfo method = target.asMethod();
            if (method.parameters().size() == 1) {
                String methodName = method.name();

                if (methodName.startsWith("set")) {
                    valueString = Introspector.decapitalize(methodName.substring(3));
                } else {
                    valueString = methodName;
                }
            }
            break;
        default:
            break;
    }

    return valueString;
}
 
Example 10
Source File: MethodDescriptor.java    From gizmo with Apache License 2.0 5 votes vote down vote up
private MethodDescriptor(MethodInfo info) {
    this.name = info.name();
    this.returnType = DescriptorUtils.typeToString(info.returnType());
    String[] paramTypes = new String[info.parameters().size()];
    for (int i = 0; i < paramTypes.length; ++i) {
        paramTypes[i] = DescriptorUtils.typeToString(info.parameters().get(i));
    }
    this.parameterTypes = paramTypes;
    this.declaringClass = info.declaringClass().toString().replace('.', '/');
    this.descriptor = DescriptorUtils.methodSignatureToDescriptor(returnType, parameterTypes);
}
 
Example 11
Source File: OperationCreator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private static void validateFieldType(MethodInfo methodInfo, OperationType operationType) {
    Type returnType = methodInfo.returnType();
    if (returnType.kind().equals(Type.Kind.VOID)) {
        throw new SchemaBuilderException(
                "Can not have a void return for [" + operationType.name()
                        + "] on method [" + methodInfo.name() + "]");
    }
}
 
Example 12
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * Adds (or updates) a TypeResolver with the method if (1) the method represents
 * a property not already in the properties map or (2) if the method has the same
 * type as an existing property having the same name and the new method has a
 * higher priority than the current method of the same type (getter or setter).
 *
 * @param properties current map of properties discovered
 * @param stack type resolution stack for parameterized types
 * @param method the method to add/update in properties
 * @param propertyType the type of the property associated with the method
 */
private static void updateTypeResolvers(Map<String, TypeResolver> properties,
        Deque<Map<String, Type>> stack,
        MethodInfo method,
        Type propertyType) {
    String methodName = method.name();
    boolean isWriteMethod = isMutator(method);
    String propertyName;
    int nameStart;

    if (isWriteMethod) {
        nameStart = 3;
    } else {
        nameStart = methodName.startsWith("is") ? 2 : 3;
    }

    if (methodName.length() == nameStart) {
        // The method's name is "get", "set", or "is" without the property name
        return;
    }

    propertyName = Character.toLowerCase(methodName.charAt(nameStart)) + methodName.substring(nameStart + 1);
    TypeResolver resolver;

    if (properties.containsKey(propertyName)) {
        resolver = properties.get(propertyName);

        // Only store the accessor/mutator methods if the type of property matches
        if (!TypeUtil.equalTypes(resolver.getUnresolvedType(), propertyType)) {
            return;
        }
    } else {
        resolver = new TypeResolver(propertyName, null, new ArrayDeque<>(stack));
        properties.put(propertyName, resolver);
    }

    if (isWriteMethod) {
        if (isHigherPriority(method, resolver.getWriteMethod())) {
            resolver.setWriteMethod(method);
        }
    } else {
        if (isHigherPriority(method, resolver.getReadMethod())) {
            resolver.setReadMethod(method);
        }
    }
}
 
Example 13
Source File: PanacheRepositoryEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void generateModelBridge(MethodInfo method, AnnotationValue targetReturnTypeErased) {
    String descriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
    // JpaOperations erases the Id type to Object
    String descriptorForJpaOperations = AsmUtil.getDescriptor(method,
            name -> name.equals("Entity") ? entitySignature : null);
    String signature = AsmUtil.getSignature(method, name -> typeArguments.get(name));
    List<org.jboss.jandex.Type> parameters = method.parameters();

    String castTo = null;
    if (targetReturnTypeErased != null && targetReturnTypeErased.asBoolean()) {
        org.jboss.jandex.Type type = method.returnType();
        if (type.kind() == Kind.TYPE_VARIABLE &&
                type.asTypeVariable().identifier().equals("Entity")) {
            castTo = entityBinaryType;
        }
        if (castTo == null)
            castTo = type.name().toString('/');
    }

    // Note: we can't use SYNTHETIC here because otherwise Mockito will never mock these methods
    MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC,
            method.name(),
            descriptor,
            signature,
            null);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
    }
    mv.visitCode();
    injectModel(mv);
    for (int i = 0; i < parameters.size(); i++) {
        mv.visitIntInsn(Opcodes.ALOAD, i + 1);
    }
    // inject Class
    String forwardingDescriptor = "(" + getModelDescriptor() + descriptorForJpaOperations.substring(1);
    if (castTo != null) {
        // return type is erased to Object
        int lastParen = forwardingDescriptor.lastIndexOf(')');
        forwardingDescriptor = forwardingDescriptor.substring(0, lastParen + 1) + "Ljava/lang/Object;";
    }
    mv.visitMethodInsn(Opcodes.INVOKESTATIC,
            getPanacheOperationsBinaryName(),
            method.name(),
            forwardingDescriptor, false);
    if (castTo != null)
        mv.visitTypeInsn(Opcodes.CHECKCAST, castTo);
    String returnTypeDescriptor = descriptor.substring(descriptor.lastIndexOf(")") + 1);
    mv.visitInsn(AsmUtil.getReturnInstruction(returnTypeDescriptor));
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}
 
Example 14
Source File: VertxWebProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private String generateHandler(BeanInfo bean, MethodInfo method, ClassOutput classOutput) {

        String baseName;
        if (bean.getImplClazz().enclosingClass() != null) {
            baseName = DotNames.simpleName(bean.getImplClazz().enclosingClass()) + "_"
                    + DotNames.simpleName(bean.getImplClazz().name());
        } else {
            baseName = DotNames.simpleName(bean.getImplClazz().name());
        }
        String targetPackage = DotNames.packageName(bean.getImplClazz().name());

        StringBuilder sigBuilder = new StringBuilder();
        sigBuilder.append(method.name()).append("_").append(method.returnType().name().toString());
        for (Type i : method.parameters()) {
            sigBuilder.append(i.name().toString());
        }
        String generatedName = targetPackage.replace('.', '/') + "/" + baseName + HANDLER_SUFFIX + "_" + method.name() + "_"
                + HashUtil.sha1(sigBuilder.toString());

        ClassCreator invokerCreator = ClassCreator.builder().classOutput(classOutput).className(generatedName)
                .interfaces(RouteHandler.class).build();

        // Initialized state
        FieldCreator beanField = invokerCreator.getFieldCreator("bean", InjectableBean.class)
                .setModifiers(ACC_PRIVATE | ACC_FINAL);
        FieldCreator contextField = null;
        FieldCreator containerField = null;
        if (BuiltinScope.APPLICATION.is(bean.getScope()) || BuiltinScope.SINGLETON.is(bean.getScope())) {
            // Singleton and application contexts are always active and unambiguous
            contextField = invokerCreator.getFieldCreator("context", InjectableContext.class)
                    .setModifiers(ACC_PRIVATE | ACC_FINAL);
        } else {
            containerField = invokerCreator.getFieldCreator("container", ArcContainer.class)
                    .setModifiers(ACC_PRIVATE | ACC_FINAL);
        }

        implementConstructor(bean, invokerCreator, beanField, contextField, containerField);
        implementInvoke(bean, method, invokerCreator, beanField, contextField, containerField);

        invokerCreator.close();
        return generatedName.replace('/', '.');
    }
 
Example 15
Source File: AnnotationLiteralGenerator.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private static String defaultValueStaticFieldName(MethodInfo methodInfo) {
    return methodInfo.name() + "_default_value";
}
 
Example 16
Source File: SpringScheduledProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
void processSpringScheduledAnnotation(BuildProducer<ScheduledBusinessMethodItem> scheduledBusinessMethods,
        BeanInfo bean, MethodInfo method, List<AnnotationInstance> scheduledAnnotations) {
    List<AnnotationInstance> schedules = new ArrayList<>();
    if (scheduledAnnotations != null) {
        for (AnnotationInstance scheduledAnnotation : scheduledAnnotations) {
            List<AnnotationValue> springAnnotationValues = scheduledAnnotation.values();
            List<AnnotationValue> confValues = new ArrayList<>();
            if (!springAnnotationValues.isEmpty()) {
                if (annotationsValuesContain(springAnnotationValues, "fixedRate")
                        || annotationsValuesContain(springAnnotationValues, "fixedRateString")) {
                    confValues.add(buildEveryParam(springAnnotationValues));
                    if (annotationsValuesContain(springAnnotationValues, "initialDelay")
                            || annotationsValuesContain(springAnnotationValues, "initialDelayString")) {
                        confValues.addAll(buildDelayParams(springAnnotationValues));
                    }

                } else if (annotationsValuesContain(springAnnotationValues, "fixedDelay")
                        || annotationsValuesContain(springAnnotationValues, "fixedDelayString")) {
                    throw new IllegalArgumentException(
                            "Invalid @Scheduled method '" + method.name()
                                    + "': 'fixedDelay' not supported");
                } else if (annotationsValuesContain(springAnnotationValues, "cron")) {
                    if (annotationsValuesContain(springAnnotationValues, "initialDelay")) {
                        throw new IllegalArgumentException(
                                "Invalid @Scheduled method '" + method.name()
                                        + "': 'initialDelay' not supported for cron triggers");
                    }
                    confValues.add(buildCronParam(springAnnotationValues));
                }

            }
            AnnotationInstance regularAnnotationInstance = AnnotationInstance.create(QUARKUS_SCHEDULED,
                    scheduledAnnotation.target(), confValues);
            schedules.add(regularAnnotationInstance);
        }
        if (schedules != null) {
            scheduledBusinessMethods.produce(new ScheduledBusinessMethodItem(bean, method, schedules));
            LOGGER.debugf("Found scheduled business method %s declared on %s", method, bean);
        }
    }
}
 
Example 17
Source File: PanacheRepositoryEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void generateJvmBridge(MethodInfo method) {
    // get a bounds-erased descriptor
    String descriptor = AsmUtil.getDescriptor(method, name -> null);
    // make sure we need a bridge
    if (!userMethods.contains(method.name() + "/" + descriptor)) {
        MethodVisitor mv = super.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE,
                method.name(),
                descriptor,
                null,
                null);
        List<org.jboss.jandex.Type> parameters = method.parameters();
        for (int i = 0; i < parameters.size(); i++) {
            mv.visitParameter(method.parameterName(i), 0 /* modifiers */);
        }
        mv.visitCode();
        // this
        mv.visitIntInsn(Opcodes.ALOAD, 0);
        // each param
        for (int i = 0; i < parameters.size(); i++) {
            org.jboss.jandex.Type paramType = parameters.get(i);
            if (paramType.kind() == Kind.PRIMITIVE)
                throw new IllegalStateException("BUG: Don't know how to generate JVM bridge method for " + method
                        + ": has primitive parameters");
            mv.visitIntInsn(Opcodes.ALOAD, i + 1);
            if (paramType.kind() == Kind.TYPE_VARIABLE) {
                String typeParamName = paramType.asTypeVariable().identifier();
                switch (typeParamName) {
                    case "Entity":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, entityBinaryType);
                        break;
                    case "Id":
                        mv.visitTypeInsn(Opcodes.CHECKCAST, idBinaryType);
                        break;
                }
            }
        }

        String targetDescriptor = AsmUtil.getDescriptor(method, name -> typeArguments.get(name));
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
                daoBinaryName,
                method.name(),
                targetDescriptor, false);
        String targetReturnTypeDescriptor = targetDescriptor.substring(targetDescriptor.indexOf(')') + 1);
        mv.visitInsn(AsmUtil.getReturnInstruction(targetReturnTypeDescriptor));
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

}
 
Example 18
Source File: SmallRyeReactiveMessagingProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Generates an invoker class that looks like the following:
 *
 * <pre>
 * public class SomeName implements Invoker {
 *     private BeanType beanInstance;
 *
 *     public SomeName(Object var1) {
 *         this.beanInstance = var1;
 *     }
 *
 *     public Object invoke(Object[] args) {
 *         return this.beanInstance.doSomething(var1);
 *     }
 * }
 * </pre>
 */
private String generateInvoker(BeanInfo bean, MethodInfo method, ClassOutput classOutput) {
    String baseName;
    if (bean.getImplClazz().enclosingClass() != null) {
        baseName = DotNames.simpleName(bean.getImplClazz().enclosingClass()) + "_"
                + DotNames.simpleName(bean.getImplClazz().name());
    } else {
        baseName = DotNames.simpleName(bean.getImplClazz().name());
    }
    StringBuilder sigBuilder = new StringBuilder();
    sigBuilder.append(method.name()).append("_").append(method.returnType().name().toString());
    for (Type i : method.parameters()) {
        sigBuilder.append(i.name().toString());
    }
    String targetPackage = DotNames.packageName(bean.getImplClazz().name());
    String generatedName = targetPackage.replace('.', '/') + "/" + baseName + INVOKER_SUFFIX + "_" + method.name() + "_"
            + HashUtil.sha1(sigBuilder.toString());

    try (ClassCreator invoker = ClassCreator.builder().classOutput(classOutput).className(generatedName)
            .interfaces(Invoker.class)
            .build()) {

        String beanInstanceType = method.declaringClass().name().toString();
        FieldDescriptor beanInstanceField = invoker.getFieldCreator("beanInstance", beanInstanceType)
                .getFieldDescriptor();

        // generate a constructor that takes the bean instance as an argument
        // the method type needs to be Object because that is what is used as the call site in SmallRye Reactive Messaging
        try (MethodCreator ctor = invoker.getMethodCreator("<init>", void.class, Object.class)) {
            ctor.setModifiers(Modifier.PUBLIC);
            ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), ctor.getThis());
            ResultHandle self = ctor.getThis();
            ResultHandle beanInstance = ctor.getMethodParam(0);
            ctor.writeInstanceField(beanInstanceField, self, beanInstance);
            ctor.returnValue(null);
        }

        try (MethodCreator invoke = invoker.getMethodCreator(
                MethodDescriptor.ofMethod(generatedName, "invoke", Object.class, Object[].class))) {

            int parametersCount = method.parameters().size();
            String[] argTypes = new String[parametersCount];
            ResultHandle[] args = new ResultHandle[parametersCount];
            for (int i = 0; i < parametersCount; i++) {
                // the only method argument of io.smallrye.reactive.messaging.Invoker is an object array so we need to pull out
                // each argument and put it in the target method arguments array
                args[i] = invoke.readArrayValue(invoke.getMethodParam(0), i);
                argTypes[i] = method.parameters().get(i).name().toString();
            }
            ResultHandle result = invoke.invokeVirtualMethod(
                    MethodDescriptor.ofMethod(beanInstanceType, method.name(),
                            method.returnType().name().toString(), argTypes),
                    invoke.readInstanceField(beanInstanceField, invoke.getThis()), args);
            if (ReactiveMessagingDotNames.VOID.equals(method.returnType().name())) {
                invoke.returnValue(invoke.loadNull());
            } else {
                invoke.returnValue(result);
            }
        }
    }

    return generatedName.replace('/', '.');
}
 
Example 19
Source File: SchedulerProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private String generateInvoker(BeanInfo bean, MethodInfo method, ClassOutput classOutput) {

        String baseName;
        if (bean.getImplClazz().enclosingClass() != null) {
            baseName = DotNames.simpleName(bean.getImplClazz().enclosingClass()) + "_"
                    + DotNames.simpleName(bean.getImplClazz().name());
        } else {
            baseName = DotNames.simpleName(bean.getImplClazz().name());
        }
        StringBuilder sigBuilder = new StringBuilder();
        sigBuilder.append(method.name()).append("_").append(method.returnType().name().toString());
        for (Type i : method.parameters()) {
            sigBuilder.append(i.name().toString());
        }
        String targetPackage = DotNames.packageName(bean.getImplClazz().name());
        String generatedName = targetPackage.replace('.', '/') + "/" + baseName + INVOKER_SUFFIX + "_" + method.name() + "_"
                + HashUtil.sha1(sigBuilder.toString());

        ClassCreator invokerCreator = ClassCreator.builder().classOutput(classOutput).className(generatedName)
                .interfaces(ScheduledInvoker.class)
                .build();

        // The descriptor is: void invokeBean(Object execution)
        MethodCreator invoke = invokerCreator.getMethodCreator("invokeBean", void.class, Object.class);
        // InjectableBean<Foo: bean = Arc.container().bean("1");
        // InstanceHandle<Foo> handle = Arc.container().instance(bean);
        // handle.get().ping();
        ResultHandle containerHandle = invoke
                .invokeStaticMethod(MethodDescriptor.ofMethod(Arc.class, "container", ArcContainer.class));
        ResultHandle beanHandle = invoke.invokeInterfaceMethod(
                MethodDescriptor.ofMethod(ArcContainer.class, "bean", InjectableBean.class, String.class),
                containerHandle, invoke.load(bean.getIdentifier()));
        ResultHandle instanceHandle = invoke.invokeInterfaceMethod(
                MethodDescriptor.ofMethod(ArcContainer.class, "instance", InstanceHandle.class, InjectableBean.class),
                containerHandle, beanHandle);
        ResultHandle beanInstanceHandle = invoke
                .invokeInterfaceMethod(MethodDescriptor.ofMethod(InstanceHandle.class, "get", Object.class), instanceHandle);
        if (method.parameters().isEmpty()) {
            invoke.invokeVirtualMethod(
                    MethodDescriptor.ofMethod(bean.getImplClazz().name().toString(), method.name(), void.class),
                    beanInstanceHandle);
        } else {
            invoke.invokeVirtualMethod(
                    MethodDescriptor.ofMethod(bean.getImplClazz().name().toString(), method.name(), void.class,
                            ScheduledExecution.class),
                    beanInstanceHandle, invoke.getMethodParam(0));
        }
        // handle.destroy() - destroy dependent instance afterwards
        if (BuiltinScope.DEPENDENT.is(bean.getScope())) {
            invoke.invokeInterfaceMethod(MethodDescriptor.ofMethod(InstanceHandle.class, "destroy", void.class),
                    instanceHandle);
        }
        invoke.returnValue(null);

        invokerCreator.close();
        return generatedName.replace('/', '.');
    }
 
Example 20
Source File: EventBusConsumer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
static String generateInvoker(BeanInfo bean, MethodInfo method,
        AnnotationInstance consumeEvent,
        ClassOutput classOutput) {

    String baseName;
    if (bean.getImplClazz().enclosingClass() != null) {
        baseName = DotNames.simpleName(bean.getImplClazz().enclosingClass()) + "_"
                + DotNames.simpleName(bean.getImplClazz());
    } else {
        baseName = DotNames.simpleName(bean.getImplClazz().name());
    }
    String targetPackage = DotNames.packageName(bean.getImplClazz().name());

    StringBuilder sigBuilder = new StringBuilder();
    sigBuilder.append(method.name()).append("_").append(method.returnType().name().toString());
    for (Type i : method.parameters()) {
        sigBuilder.append(i.name().toString());
    }
    String generatedName = targetPackage.replace('.', '/') + "/" + baseName + INVOKER_SUFFIX + "_" + method.name() + "_"
            + HashUtil.sha1(sigBuilder.toString());

    ClassCreator invokerCreator = ClassCreator.builder().classOutput(classOutput).className(generatedName)
            .interfaces(EventConsumerInvoker.class).build();

    // The method descriptor is: void invokeBean(Object message)
    MethodCreator invoke = invokerCreator.getMethodCreator("invokeBean", void.class, Object.class);
    ResultHandle containerHandle = invoke.invokeStaticMethod(ARC_CONTAINER);

    AnnotationValue blocking = consumeEvent.value("blocking");
    if (blocking != null && blocking.asBoolean()) {
        // Blocking operation must be performed on a worker thread
        ResultHandle vertxHandle = invoke
                .invokeInterfaceMethod(INSTANCE_HANDLE_GET,
                        invoke.invokeInterfaceMethod(ARC_CONTAINER_INSTANCE_FOR_TYPE, containerHandle,
                                invoke.loadClass(Vertx.class),
                                invoke.newArray(Annotation.class.getName(), invoke.load(0))));

        FunctionCreator func = invoke.createFunction(Handler.class);
        BytecodeCreator funcBytecode = func.getBytecode();
        AssignableResultHandle messageHandle = funcBytecode.createVariable(Message.class);
        funcBytecode.assign(messageHandle, invoke.getMethodParam(0));
        TryBlock tryBlock = funcBytecode.tryBlock();
        invoke(bean, method, messageHandle, tryBlock);
        tryBlock.invokeInterfaceMethod(FUTURE_COMPLETE, funcBytecode.getMethodParam(0), tryBlock.loadNull());
        CatchBlockCreator catchBlock = tryBlock.addCatch(Exception.class);
        catchBlock.invokeInterfaceMethod(FUTURE_FAIL, funcBytecode.getMethodParam(0), catchBlock.getMethodParam(0));
        funcBytecode.returnValue(null);

        invoke.invokeInterfaceMethod(VERTX_EXECUTE_BLOCKING, vertxHandle, func.getInstance(), invoke.load(false),
                invoke.loadNull());
    } else {
        invoke(bean, method, invoke.getMethodParam(0), invoke);
    }
    invoke.returnValue(null);
    invokerCreator.close();
    return generatedName.replace('/', '.');
}