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

The following examples show how to use org.jboss.jandex.MethodInfo#returnType() . 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: 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 2
Source File: NonNullHelperTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullableString() throws Exception {
    Index complete = IndexCreator.index(AsyncApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
    MethodInfo nonNullString = classByName.method("string");
    Type type = nonNullString.returnType();

    Annotations annotationsForMethod = Annotations.getAnnotationsForMethod(nonNullString);

    assertFalse(NonNullHelper.markAsNonNull(type, annotationsForMethod));
}
 
Example 3
Source File: Types.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static Set<Type> getProducerMethodTypeClosure(MethodInfo producerMethod, BeanDeployment beanDeployment) {
    Set<Type> types;
    Type returnType = producerMethod.returnType();
    if (returnType.kind() == Kind.PRIMITIVE || returnType.kind() == Kind.ARRAY) {
        types = new HashSet<>();
        types.add(returnType);
        types.add(OBJECT_TYPE);
        return types;
    } else {
        ClassInfo returnTypeClassInfo = getClassByName(beanDeployment.getIndex(), returnType);
        if (returnTypeClassInfo == null) {
            throw new IllegalArgumentException(
                    "Producer method return type not found in index: " + producerMethod.returnType().name());
        }
        if (Kind.CLASS.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod, Collections.emptyMap(), beanDeployment, null);
        } else if (Kind.PARAMETERIZED_TYPE.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod,
                    buildResolvedMap(returnType.asParameterizedType().arguments(), returnTypeClassInfo.typeParameters(),
                            Collections.emptyMap(), beanDeployment.getIndex()),
                    beanDeployment, null);
        } else {
            throw new IllegalArgumentException("Unsupported return type");
        }
    }
    return restrictBeanTypes(types, beanDeployment.getAnnotations(producerMethod));
}
 
Example 4
Source File: AnnotationLiteralGenerator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void generateStaticFieldsWithDefaultValues(ClassCreator annotationLiteral,
        List<MethodInfo> defaultOfClassType) {
    if (defaultOfClassType.isEmpty()) {
        return;
    }

    MethodCreator staticConstructor = annotationLiteral.getMethodCreator(Methods.CLINIT, void.class);
    staticConstructor.setModifiers(ACC_STATIC);

    for (MethodInfo method : defaultOfClassType) {
        Type returnType = method.returnType();
        String returnTypeName = returnType.name().toString();
        AnnotationValue defaultValue = method.defaultValue();

        FieldCreator fieldCreator = annotationLiteral.getFieldCreator(defaultValueStaticFieldName(method), returnTypeName);
        fieldCreator.setModifiers(ACC_PUBLIC | ACC_STATIC | ACC_FINAL);

        if (defaultValue.kind() == AnnotationValue.Kind.ARRAY) {
            Type[] clazzArray = defaultValue.asClassArray();
            ResultHandle array = staticConstructor.newArray(returnTypeName, clazzArray.length);
            for (int i = 0; i < clazzArray.length; ++i) {
                staticConstructor.writeArrayValue(array, staticConstructor.load(i),
                        staticConstructor.loadClass(clazzArray[i].name().toString()));
            }
            staticConstructor.writeStaticField(fieldCreator.getFieldDescriptor(), array);
        } else {
            staticConstructor.writeStaticField(fieldCreator.getFieldDescriptor(),
                    staticConstructor.loadClass(defaultValue.asClass().name().toString()));

        }
    }

    staticConstructor.returnValue(null);
}
 
Example 5
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether a method follows the Java bean convention for a mutator
 * method (setter).
 *
 * @param method the method to check
 * @return true if the method is a Java bean setter, otherwise false
 */
private static boolean isMutator(MethodInfo method) {
    Type returnType = method.returnType();

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

    return method.name().startsWith("set");
}
 
Example 6
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a method is a bean property method. The method must conform to the Java bean
 * conventions for getter or setter methods.
 *
 * @param properties current map of properties discovered
 * @param field the method to scan
 * @param stack type resolution stack for parameterized types
 */
private static void scanMethod(Map<String, TypeResolver> properties, MethodInfo method, Deque<Map<String, Type>> stack) {
    Type returnType = method.returnType();
    Type propertyType = null;

    if (isAccessor(method)) {
        propertyType = returnType;
    } else if (isMutator(method)) {
        propertyType = method.parameters().get(0);
    }

    if (propertyType != null) {
        updateTypeResolvers(properties, stack, method, propertyType);
    }
}
 
Example 7
Source File: TypeResolver.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the read method for the property. May replace a previously-set method
 * in the case where an interface defines an annotated method with more
 * information than the implementation of the method.
 *
 * @param readMethod the property's read method (getter/accessor)
 */
private void setReadMethod(MethodInfo readMethod) {
    if (this.readMethod != null) {
        targets.remove(this.readMethod);
    }

    this.readMethod = readMethod;

    if (readMethod != null) {
        this.leaf = readMethod.returnType();
        targets.add(readMethod);
    }
}
 
Example 8
Source File: Annotations.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private static Annotations getAnnotationsForOutputField(FieldInfo fieldInfo, MethodInfo methodInfo) {
    Map<DotName, AnnotationInstance> annotationsForField = getAnnotationsForField(fieldInfo, methodInfo);
    if (fieldInfo != null) {
        annotationsForField.putAll(getTypeUseAnnotations(fieldInfo.type()));
    }
    if (methodInfo != null) {
        org.jboss.jandex.Type returnType = methodInfo.returnType();
        if (returnType != null) {
            annotationsForField.putAll(getTypeUseAnnotations(methodInfo.returnType()));
        }
    }
    return new Annotations(annotationsForField);
}
 
Example 9
Source File: NonNullHelperTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonNullCompletionStage() throws Exception {
    Index complete = IndexCreator.index(AsyncApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
    MethodInfo nonNullString = classByName.method("nonNullCompletionStage");
    Type type = nonNullString.returnType();

    Annotations annotationsForMethod = Annotations.getAnnotationsForMethod(nonNullString);

    assertTrue(NonNullHelper.markAsNonNull(type, annotationsForMethod));
}
 
Example 10
Source File: NonNullHelperTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonNullString() throws Exception {
    Index complete = IndexCreator.index(AsyncApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
    MethodInfo nonNullString = classByName.method("nonNullString");
    Type type = nonNullString.returnType();

    Annotations annotationsForMethod = Annotations.getAnnotationsForMethod(nonNullString);

    assertTrue(NonNullHelper.markAsNonNull(type, annotationsForMethod));
}
 
Example 11
Source File: RestClientProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void processInterfaceReturnTypes(ClassInfo classInfo, Set<Type> returnTypes) {
    for (MethodInfo method : classInfo.methods()) {
        Type type = method.returnType();
        if (!type.name().toString().startsWith("java.lang")) {
            returnTypes.add(type);
        }
    }
}
 
Example 12
Source File: FormatHelperTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormattedLocalDate() throws Exception {
    Index complete = IndexCreator.index(AsyncApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
    MethodInfo nonNullString = classByName.method("formattedLocalDate");
    Type type = nonNullString.returnType();

    Annotations annotations = Annotations.getAnnotationsForMethod(nonNullString);

    Optional<TransformInfo> format = FormatHelper.getFormat(type, annotations);

    TransformInfo transformInfo = format.get();
    assertEquals("yyyy-MM-dd", transformInfo.getFormat());
}
 
Example 13
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 14
Source File: ControllerAdviceAbstractExceptionMapperGenerator.java    From quarkus with Apache License 2.0 5 votes vote down vote up
ControllerAdviceAbstractExceptionMapperGenerator(MethodInfo controllerAdviceMethod, DotName exceptionDotName,
        ClassOutput classOutput, TypesUtil typesUtil) {
    super(exceptionDotName, classOutput);
    this.controllerAdviceMethod = controllerAdviceMethod;
    this.typesUtil = typesUtil;

    this.returnType = controllerAdviceMethod.returnType();
    this.parameterTypes = controllerAdviceMethod.parameters();
    this.declaringClassName = controllerAdviceMethod.declaringClass().name().toString();
}
 
Example 15
Source File: EventBusCodecProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static Type extractPayloadTypeFromReturn(MethodInfo method) {
    Type returnType = method.returnType();
    if (returnType.kind() == Type.Kind.CLASS) {
        return returnType;
    } else if (returnType.kind() == Type.Kind.PARAMETERIZED_TYPE) {
        ParameterizedType returnedParamType = returnType.asParameterizedType();
        if (!returnedParamType.arguments().isEmpty()
                && (returnedParamType.name().equals(COMPLETION_STAGE) || returnedParamType.name().equals(UNI))) {
            return returnedParamType.arguments().get(0);
        } else {
            return returnedParamType;
        }
    }
    return null;
}
 
Example 16
Source File: JaxRsAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
/**
 * Scans a sub-resource locator method's return type as a resource class. The list of locator path parameters
 * will be expanded with any parameters that apply to the resource sub-locator method (both path and operation
 * parameters).
 * 
 * @param openApi current OAI result
 * @param locatorPathParameters the parent resource's list of path parameters, may be null
 * @param resourceClass the JAX-RS resource class being processed. May be a sub-class of the class which declares method
 * @param method sub-resource locator JAX-RS method
 */
private void processSubResource(final AnnotationScannerContext context,
        final ClassInfo resourceClass,
        final MethodInfo method,
        OpenAPI openApi,
        List<Parameter> locatorPathParameters) {
    final Type methodReturnType = method.returnType();

    if (Type.Kind.VOID.equals(methodReturnType.kind())) {
        // Can sub-resource locators return a CompletionStage?
        return;
    }

    JaxRsSubResourceLocator locator = new JaxRsSubResourceLocator(resourceClass, method);
    ClassInfo subResourceClass = context.getIndex().getClassByName(methodReturnType.name());

    // Do not allow the same resource locator method to be used twice (sign of infinite recursion)
    if (subResourceClass != null && !this.subResourceStack.contains(locator)) {
        Function<AnnotationInstance, Parameter> reader = t -> ParameterReader.readParameter(context, t);

        ResourceParameters params = ParameterProcessor.process(context, resourceClass, method,
                reader, context.getExtensions());

        final String originalAppPath = this.currentAppPath;
        final String subResourcePath;

        if (this.subResourceStack.isEmpty()) {
            subResourcePath = params.getFullOperationPath();
        } else {
            // If we are already processing a sub-resource, ignore any @Path information from the current class
            subResourcePath = params.getOperationPath();
        }

        this.currentAppPath = super.makePath(subResourcePath);
        this.subResourceStack.push(locator);

        /*
         * Combine parameters passed previously with all of those from the current resource class and
         * method that apply to this Path. The full list will be used as PATH-LEVEL parameters for
         * sub-resource methods deeper in the scan.
         */
        processResourceClass(context, openApi, subResourceClass,
                ListUtil.mergeNullableLists(locatorPathParameters,
                        params.getPathItemParameters(),
                        params.getOperationParameters()));

        this.subResourceStack.pop();
        this.currentAppPath = originalAppPath;
    }
}
 
Example 17
Source File: CustomQueryMethodsAdder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void generateCustomResultTypes(DotName interfaceName, DotName implName, Map<String, List<String>> queryMethods) {

        ClassInfo interfaceInfo = index.getClassByName(interfaceName);

        try (ClassCreator implClassCreator = ClassCreator.builder().classOutput(nonBeansClassOutput)
                .interfaces(interfaceName.toString()).className(implName.toString())
                .build()) {

            Map<String, FieldDescriptor> fields = new HashMap<>(3);

            for (MethodInfo method : interfaceInfo.methods()) {
                String getterName = method.name();
                String propertyName = JavaBeanUtil.getPropertyNameFromGetter(getterName);

                Type returnType = method.returnType();
                if (returnType.kind() == Type.Kind.VOID) {
                    throw new IllegalArgumentException("Method " + method.name() + " of interface " + interfaceName
                            + " is not a getter method since it returns void");
                }
                DotName fieldTypeName = getPrimitiveTypeName(returnType.name());

                FieldDescriptor field = implClassCreator.getFieldCreator(propertyName, fieldTypeName.toString())
                        .getFieldDescriptor();

                // create getter (based on the interface)
                try (MethodCreator getter = implClassCreator.getMethodCreator(getterName, returnType.toString())) {
                    getter.setModifiers(Modifier.PUBLIC);
                    getter.returnValue(getter.readInstanceField(field, getter.getThis()));
                }

                fields.put(propertyName.toLowerCase(), field);
            }

            // Add static methods to convert from Object[] to this type
            for (Map.Entry<String, List<String>> queryMethod : queryMethods.entrySet()) {
                try (MethodCreator convert = implClassCreator.getMethodCreator("convert_" + queryMethod.getKey(),
                        implName.toString(), Object[].class.getName())) {
                    convert.setModifiers(Modifier.STATIC);

                    ResultHandle newObject = convert.newInstance(MethodDescriptor.ofConstructor(implName.toString()));

                    // Use field names in the query-declared order
                    List<String> queryNames = queryMethod.getValue();

                    // Object[] is the only paramter: values are in column/declared order
                    ResultHandle array = convert.getMethodParam(0);

                    for (int i = 0; i < queryNames.size(); i++) {
                        FieldDescriptor f = fields.get(queryNames.get(i));
                        if (f == null) {
                            throw new IllegalArgumentException("@Query annotation for " + queryMethod.getKey()
                                    + " does not use fields from " + interfaceName);
                        } else {
                            convert.writeInstanceField(f, newObject,
                                    castReturnValue(convert, convert.readArrayValue(array, i), f.getType()));
                        }
                    }
                    convert.returnValue(newObject);
                }
            }
        }
    }
 
Example 18
Source File: IgnoreResolver.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldIgnore(AnnotationTarget target, DataObjectDeque.PathEntry parentPathEntry) {
    Type classType;

    switch (target.kind()) {
        case FIELD:
            classType = target.asField().type();
            break;
        case METHOD:
            MethodInfo method = target.asMethod();
            if (method.returnType().kind().equals(Type.Kind.VOID)) {
                // Setter method
                classType = method.parameters().get(0);
            } else {
                // Getter method
                classType = method.returnType();
            }
            break;
        default:
            return false;
    }

    // Primitive and non-indexed types will result in a null
    if (classType.kind() == Type.Kind.PRIMITIVE ||
            classType.kind() == Type.Kind.VOID ||
            (classType.kind() == Type.Kind.ARRAY && classType.asArrayType().component().kind() == Type.Kind.PRIMITIVE)
            ||
            !index.containsClass(classType)) {
        return false;
    }

    // Find the real class implementation where the @JsonIgnoreType annotation may be.
    ClassInfo classInfo = index.getClass(classType);

    if (ignoredTypes.contains(classInfo.name())) {
        DataObjectLogging.log.ignoringType(classInfo.name());
        return true;
    }

    AnnotationInstance annotationInstance = TypeUtil.getAnnotation(classInfo, getName());
    if (annotationInstance != null && valueAsBooleanOrTrue(annotationInstance)) {
        // Add the ignored field or class name
        DataObjectLogging.log.ignoringTypeAndAddingToSet(classInfo.name());
        ignoredTypes.add(classInfo.name());
        return true;
    }
    return false;
}
 
Example 19
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 20
Source File: QuarkusMediatorConfigurationUtil.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public ReturnTypeGenericTypeAssignable(MethodInfo method, ClassLoader classLoader) {
    super(method.returnType(), classLoader);
}