Java Code Examples for org.jboss.jandex.IndexView#getClassByName()

The following examples show how to use org.jboss.jandex.IndexView#getClassByName() . 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: SpringSecurityProcessorUtil.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static ClassInfo getClassInfoFromBeanName(String beanName, IndexView index, Map<String, DotName> springBeansNameToDotName,
        Map<String, ClassInfo> springBeansNameToClassInfo,
        String expression, MethodInfo methodInfo) {
    ClassInfo beanClassInfo = springBeansNameToClassInfo.get(beanName);
    if (beanClassInfo == null) {
        DotName beanClassDotName = springBeansNameToDotName.get(beanName);
        if (beanClassDotName == null) {
            throw new IllegalArgumentException("Could not find bean named '" + beanName
                    + "' found in expression" + expression + "' in the @PreAuthorize annotation on method "
                    + methodInfo.name() + " of class " + methodInfo.declaringClass()
                    + " in the set of the application beans");
        }
        beanClassInfo = index.getClassByName(beanClassDotName);
        if (beanClassInfo == null) {
            throw new IllegalStateException("Unable to locate class " + beanClassDotName + " in the index");
        }
        springBeansNameToClassInfo.put(beanName, beanClassInfo);
    }
    return beanClassInfo;
}
 
Example 2
Source File: Types.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static Type resolveTypeParam(Type typeParam, Map<TypeVariable, Type> resolvedTypeParameters, IndexView index) {
    if (typeParam.kind() == Kind.TYPE_VARIABLE) {
        return resolvedTypeParameters.getOrDefault(typeParam, typeParam);
    } else if (typeParam.kind() == Kind.PARAMETERIZED_TYPE) {
        ParameterizedType parameterizedType = typeParam.asParameterizedType();
        ClassInfo classInfo = index.getClassByName(parameterizedType.name());
        if (classInfo != null) {
            List<TypeVariable> typeParameters = classInfo.typeParameters();
            List<Type> arguments = parameterizedType.arguments();
            Type[] typeParams = new Type[typeParameters.size()];
            for (int i = 0; i < typeParameters.size(); i++) {
                typeParams[i] = resolveTypeParam(arguments.get(i), resolvedTypeParameters, index);
            }
            return ParameterizedType.create(parameterizedType.name(), typeParams, null);
        }
    }
    return typeParam;
}
 
Example 3
Source File: StockMethodsAdder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private Optional<AnnotationTarget> getVersionAnnotationTargetRec(DotName currentDotName, IndexView index,
        DotName originalEntityDotName) {
    ClassInfo classInfo = index.getClassByName(currentDotName);
    if (classInfo == null) {
        throw new IllegalStateException("Entity " + originalEntityDotName + " was not part of the Quarkus index");
    }

    if (!classInfo.annotations().containsKey(DotNames.VERSION)) {
        if (DotNames.OBJECT.equals(classInfo.superName())) {
            return Optional.empty();
        }
        return getVersionAnnotationTargetRec(classInfo.superName(), index, originalEntityDotName);
    }

    List<AnnotationInstance> annotationInstances = classInfo.annotations().get(DotNames.VERSION);
    if (annotationInstances.size() > 1) {
        throw new IllegalArgumentException(
                "Currently the @Version annotation can only be placed on a single field or method. " +
                        "Offending class is " + originalEntityDotName);
    }

    return Optional.of(annotationInstances.get(0).target());
}
 
Example 4
Source File: ValueResolverGenerator.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static boolean hasCompletionStageInTypeClosure(ClassInfo classInfo,
        IndexView index) {

    if (classInfo == null) {
        // TODO cannot perform analysis
        return false;
    }
    if (classInfo.name().equals(COMPLETION_STAGE)) {
        return true;
    }
    // Interfaces
    for (Type interfaceType : classInfo.interfaceTypes()) {
        ClassInfo interfaceClassInfo = index.getClassByName(interfaceType.name());
        if (interfaceClassInfo != null && hasCompletionStageInTypeClosure(interfaceClassInfo, index)) {
            return true;
        }
    }
    // Superclass
    if (classInfo.superClassType() != null) {
        ClassInfo superClassInfo = index.getClassByName(classInfo.superName());
        if (superClassInfo != null && hasCompletionStageInTypeClosure(superClassInfo, index)) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: StockMethodsAdder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private AnnotationTarget getIdAnnotationTargetRec(DotName currentDotName, IndexView index, DotName originalEntityDotName) {
    ClassInfo classInfo = index.getClassByName(currentDotName);
    if (classInfo == null) {
        throw new IllegalStateException("Entity " + originalEntityDotName + " was not part of the Quarkus index");
    }

    if (!classInfo.annotations().containsKey(DotNames.JPA_ID)) {
        if (DotNames.OBJECT.equals(classInfo.superName())) {
            throw new IllegalArgumentException("Currently only Entities with the @Id annotation are supported. " +
                    "Offending class is " + originalEntityDotName);
        }
        return getIdAnnotationTargetRec(classInfo.superName(), index, originalEntityDotName);
    }

    List<AnnotationInstance> annotationInstances = classInfo.annotations().get(DotNames.JPA_ID);
    if (annotationInstances.size() > 1) {
        throw new IllegalArgumentException(
                "Currently the @Id annotation can only be placed on a single field or method. " +
                        "Offending class is " + originalEntityDotName);
    }

    return annotationInstances.get(0).target();
}
 
Example 6
Source File: FieldNameTest.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldNamePriority() {
    Indexer indexer = new Indexer();
    indexDirectory(indexer, "io/smallrye/graphql/schema/creator/fieldnameapp");
    IndexView index = indexer.complete();

    ClassInfo classInfo = index.getClassByName(DotName.createSimple(SomeObjectAnnotatedGetters.class.getName()));
    // @Name
    MethodInfo methodInfo = classInfo.method("getName");
    Annotations annotations = Annotations.getAnnotationsForMethod(methodInfo);
    assertEquals("a", FieldCreator.getFieldName(Direction.OUT, annotations, "name"));

    // @Query
    methodInfo = classInfo.method("getQuery");
    annotations = Annotations.getAnnotationsForMethod(methodInfo);
    assertEquals("d", FieldCreator.getFieldName(Direction.OUT, annotations, "query"));

    // @JsonbProperty
    methodInfo = classInfo.method("getJsonbProperty");
    annotations = Annotations.getAnnotationsForMethod(methodInfo);
    assertEquals("f", FieldCreator.getFieldName(Direction.OUT, annotations, "jsonbProperty"));

    // no annotation
    methodInfo = classInfo.method("getFieldName");
    annotations = Annotations.getAnnotationsForMethod(methodInfo);
    assertEquals("fieldName", FieldCreator.getFieldName(Direction.OUT, annotations, "fieldName"));
}
 
Example 7
Source File: JpaJandexScavenger.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void enlistExplicitClasses(IndexView index, JpaEntitiesBuildItem domainObjectCollector,
        Set<String> enumTypeCollector, Set<String> javaTypeCollector, List<String> managedClassNames,
        Set<DotName> unindexedClasses) {
    for (String className : managedClassNames) {
        DotName dotName = DotName.createSimple(className);
        boolean isInIndex = index.getClassByName(dotName) != null;
        if (!isInIndex) {
            unindexedClasses.add(dotName);
        }

        addClassHierarchyToReflectiveList(index, domainObjectCollector, enumTypeCollector, javaTypeCollector, dotName,
                unindexedClasses);
    }
}
 
Example 8
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
static ClassInfo getClassInfo(IndexView appIndex, DotName className) {
    ClassInfo clazz = appIndex.getClassByName(className);
    if (clazz == null) {
        clazz = jdkIndex.getClassByName(className);
    }
    return clazz;
}
 
Example 9
Source File: SchemaFactory.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a Jandex enum class type to a {@link Schema} model.Adds each enum constant name to the list of the given schema's
 * enumeration list.
 * 
 * The given type must be found in the index.
 *
 * @param index Jandex index containing the ClassInfo for the given enum type
 * @param enumType type containing Java Enum constants
 * @return Schema model
 *
 * @see java.lang.reflect.Field#isEnumConstant()
 */
public static Schema enumToSchema(IndexView index, Type enumType) {
    IoLogging.log.enumProcessing(enumType);
    final int ENUM = 0x00004000; // see java.lang.reflect.Modifier#ENUM
    ClassInfo enumKlazz = index.getClassByName(TypeUtil.getName(enumType));
    AnnotationInstance schemaAnnotation = enumKlazz.classAnnotation(SchemaConstant.DOTNAME_SCHEMA);
    Schema enumSchema = new SchemaImpl();
    List<Object> enumeration = enumKlazz.fields()
            .stream()
            .filter(field -> (field.flags() & ENUM) != 0)
            .map(FieldInfo::name)
            .sorted() // Make the order determinate
            .collect(Collectors.toList());

    if (schemaAnnotation != null) {
        Map<String, Object> defaults = new HashMap<>(2);
        defaults.put(SchemaConstant.PROP_TYPE, SchemaType.STRING);
        defaults.put(SchemaConstant.PROP_ENUMERATION, enumeration);

        enumSchema = readSchema(index, enumSchema, schemaAnnotation, enumKlazz, defaults);
    } else {
        enumSchema.setType(SchemaType.STRING);
        enumSchema.setEnumeration(enumeration);
    }

    return enumSchema;
}
 
Example 10
Source File: RestClientProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void findInterfaces(IndexView index, Map<DotName, ClassInfo> interfaces, Set<Type> returnTypes,
        DotName annotationToFind) {
    for (AnnotationInstance annotation : index.getAnnotations(annotationToFind)) {
        AnnotationTarget target = annotation.target();
        ClassInfo theInfo;
        if (target.kind() == AnnotationTarget.Kind.CLASS) {
            theInfo = target.asClass();
        } else if (target.kind() == AnnotationTarget.Kind.METHOD) {
            theInfo = target.asMethod().declaringClass();
        } else {
            continue;
        }

        if (!isRestClientInterface(index, theInfo)) {
            continue;
        }

        interfaces.put(theInfo.name(), theInfo);

        // Find Return types
        processInterfaceReturnTypes(theInfo, returnTypes);
        for (Type interfaceType : theInfo.interfaceTypes()) {
            ClassInfo interfaceClassInfo = index.getClassByName(interfaceType.name());
            if (interfaceClassInfo != null) {
                processInterfaceReturnTypes(interfaceClassInfo, returnTypes);
            }
        }
    }
}
 
Example 11
Source File: SmallRyeFaultToleranceProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private boolean hasFTAnnotations(IndexView index, AnnotationStore annotationStore, ClassInfo info) {
    if (info == null) {
        //should not happen, but guard against it
        //happens in this case due to a bug involving array types

        return false;
    }
    // first check annotations on type
    if (annotationStore.hasAnyAnnotation(info, FT_ANNOTATIONS)) {
        return true;
    }

    // then check on the methods
    for (MethodInfo method : info.methods()) {
        if (annotationStore.hasAnyAnnotation(method, FT_ANNOTATIONS)) {
            return true;
        }
    }

    // then check on the parent
    DotName parentClassName = info.superName();
    if (parentClassName == null || parentClassName.equals(DotNames.OBJECT)) {
        return false;
    }
    ClassInfo parentClassInfo = index.getClassByName(parentClassName);
    if (parentClassInfo == null) {
        return false;
    }
    return hasFTAnnotations(index, annotationStore, parentClassInfo);
}
 
Example 12
Source File: GenerationUtil.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static Set<MethodInfo> interfaceMethods(Collection<DotName> interfaces, IndexView index) {
    Set<MethodInfo> result = new HashSet<>();
    for (DotName dotName : interfaces) {
        ClassInfo classInfo = index.getClassByName(dotName);
        result.addAll(classInfo.methods());
        List<DotName> extendedInterfaces = classInfo.interfaceNames();
        if (!extendedInterfaces.isEmpty()) {
            result.addAll(interfaceMethods(extendedInterfaces, index));
        }
    }
    return result;
}
 
Example 13
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Find a non-static non-synthetic method with the given name, matching number of params and assignable parameter types.
 * 
 * @param virtualMethod
 * @param clazz
 * @param expression
 * @param index
 * @param templateIdToPathFun
 * @param results
 * @return the method or null
 */
private AnnotationTarget findMethod(VirtualMethodPart virtualMethod, ClassInfo clazz, Expression expression,
        IndexView index, Function<String, String> templateIdToPathFun, Map<String, Match> results) {
    while (clazz != null) {
        for (MethodInfo method : clazz.methods()) {
            if (Modifier.isPublic(method.flags()) && !Modifier.isStatic(method.flags())
                    && !ValueResolverGenerator.isSynthetic(method.flags())
                    && method.name().equals(virtualMethod.getName())) {
                boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);
                List<Type> parameters = method.parameters();
                int lastParamIdx = parameters.size() - 1;

                if (isVarArgs) {
                    // For varargs methods match the minimal number of params
                    if (lastParamIdx > virtualMethod.getParameters().size()) {
                        continue;
                    }
                } else {
                    if (virtualMethod.getParameters().size() != parameters.size()) {
                        // Number of params must be equal
                        continue;
                    }
                }

                // Check parameter types if available
                boolean matches = true;
                byte idx = 0;

                for (Expression param : virtualMethod.getParameters()) {
                    Match result = results.get(param.toOriginalString());
                    if (result != null && !result.isEmpty()) {
                        // Type info available - validate parameter type
                        Type paramType;
                        if (isVarArgs && idx >= lastParamIdx) {
                            // Replace the type for varargs methods
                            paramType = parameters.get(lastParamIdx).asArrayType().component();
                        } else {
                            paramType = parameters.get(idx);
                        }
                        if (!Types.isAssignableFrom(result.type,
                                paramType, index)) {
                            matches = false;
                            break;
                        }
                    } else {
                        LOGGER.debugf(
                                "Type info not available - skip validation for parameter [%s] of method [%s] for expression [%s] in template [%s] on line %s",
                                method.parameterName(idx),
                                method.declaringClass().name() + "#" + method,
                                expression.toOriginalString(),
                                templateIdToPathFun.apply(expression.getOrigin().getTemplateId()),
                                expression.getOrigin().getLine());
                    }
                    idx++;
                }
                return matches ? method : null;
            }
        }
        DotName superName = clazz.superName();
        if (superName == null || DotNames.OBJECT.equals(superName)) {
            clazz = null;
        } else {
            clazz = index.getClassByName(clazz.superName());
        }
    }
    return null;
}
 
Example 14
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
void processLoopHint(Match match, IndexView index, Expression expression) {
    if (match.type.name().equals(DotNames.INTEGER)) {
        return;
    }
    Type matchType = null;
    if (match.type.kind() == Type.Kind.ARRAY) {
        matchType = match.type.asArrayType().component();
    } else if (match.type.kind() == Type.Kind.CLASS || match.type.kind() == Type.Kind.PARAMETERIZED_TYPE) {
        Set<Type> closure = Types.getTypeClosure(match.clazz, Types.buildResolvedMap(
                match.getParameterizedTypeArguments(), match.getTypeParameters(), new HashMap<>(), index), index);
        Function<Type, Type> firstParamType = t -> t.asParameterizedType().arguments().get(0);
        // Iterable<Item> => Item
        matchType = extractMatchType(closure, ITERABLE, firstParamType);
        if (matchType == null) {
            // Stream<Long> => Long
            matchType = extractMatchType(closure, STREAM, firstParamType);
        }
        if (matchType == null) {
            // Entry<K,V> => Entry<String,Item>
            matchType = extractMatchType(closure, MAP, t -> {
                Type[] args = new Type[2];
                args[0] = t.asParameterizedType().arguments().get(0);
                args[1] = t.asParameterizedType().arguments().get(1);
                return ParameterizedType.create(MAP_ENTRY, args, null);
            });
        }
        if (matchType == null) {
            // Iterator<Item> => Item
            matchType = extractMatchType(closure, ITERATOR, firstParamType);
        }
    }
    if (matchType != null) {
        match.type = matchType;
        match.clazz = index.getClassByName(match.type.name());
    } else {
        throw new IllegalStateException(String.format(
                "Unsupported iterable type found in [%s]\n\t- matching type: %s \n\t- found in template [%s] on line %s",
                expression.toOriginalString(),
                match.type, expression.getOrigin().getTemplateId(), expression.getOrigin().getLine()));
    }
}
 
Example 15
Source File: InterceptedStaticMethodsProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private ResultHandle createBindingLiteral(IndexView index, ClassOutput classOutput, BytecodeCreator init,
        AnnotationInstance binding, AnnotationLiteralProcessor annotationLiteralProcessor) {
    ClassInfo bindingClass = index.getClassByName(binding.name());
    return annotationLiteralProcessor.process(init, classOutput, bindingClass, binding,
            "io.quarkus.arc.runtime");
}
 
Example 16
Source File: TypesTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetTypeClosure() throws IOException {
    IndexView index = Basics.index(Foo.class, Baz.class, Producer.class, Object.class, List.class, Collection.class,
            Iterable.class);
    DotName bazName = DotName.createSimple(Baz.class.getName());
    DotName fooName = DotName.createSimple(Foo.class.getName());
    DotName producerName = DotName.createSimple(Producer.class.getName());
    ClassInfo fooClass = index.getClassByName(fooName);
    Map<ClassInfo, Map<TypeVariable, Type>> resolvedTypeVariables = new HashMap<>();
    BeanDeployment dummyDeployment = BeanProcessor.builder().setIndex(index).build().getBeanDeployment();

    // Baz, Foo<String>, Object
    Set<Type> bazTypes = Types.getTypeClosure(index.getClassByName(bazName), null,
            Collections.emptyMap(),
            dummyDeployment,
            resolvedTypeVariables::put);
    assertEquals(3, bazTypes.size());
    assertTrue(bazTypes.contains(Type.create(bazName, Kind.CLASS)));
    assertTrue(bazTypes.contains(ParameterizedType.create(fooName,
            new Type[] { Type.create(DotName.createSimple(String.class.getName()), Kind.CLASS) },
            null)));
    assertEquals(resolvedTypeVariables.size(), 1);
    assertTrue(resolvedTypeVariables.containsKey(fooClass));
    assertEquals(resolvedTypeVariables.get(fooClass).get(fooClass.typeParameters().get(0)),
            Type.create(DotName.createSimple(String.class.getName()), Kind.CLASS));

    resolvedTypeVariables.clear();
    // Foo<T>, Object
    Set<Type> fooTypes = Types.getClassBeanTypeClosure(fooClass,
            dummyDeployment);
    assertEquals(2, fooTypes.size());
    for (Type t : fooTypes) {
        if (t.kind().equals(Kind.PARAMETERIZED_TYPE)) {
            ParameterizedType fooType = t.asParameterizedType();
            assertEquals("T", fooType.arguments().get(0).asTypeVariable().identifier());
            assertEquals(DotNames.OBJECT, fooType.arguments().get(0).asTypeVariable().bounds().get(0).name());
        }
    }
    ClassInfo producerClass = index.getClassByName(producerName);
    String producersName = "produce";
    MethodInfo producerMethod = producerClass.method(producersName);
    // Object is the sole type
    Set<Type> producerMethodTypes = Types.getProducerMethodTypeClosure(producerMethod,
            dummyDeployment);
    assertEquals(1, producerMethodTypes.size());

    // Object is the sole type
    FieldInfo producerField = producerClass.field(producersName);
    Set<Type> producerFieldTypes = Types.getProducerFieldTypeClosure(producerField,
            dummyDeployment);
    assertEquals(1, producerFieldTypes.size());
}
 
Example 17
Source File: ConfigurationPropertiesProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private ConfigPropertiesMetadataBuildItem createConfigPropertiesMetadataFromMethod(AnnotationInstance annotation,
        IndexView index) {
    return new ConfigPropertiesMetadataBuildItem(index.getClassByName(annotation.target().asMethod().returnType().name()),
            getPrefix(annotation), ConfigProperties.NamingStrategy.VERBATIM, true, false);
}
 
Example 18
Source File: PanacheEntityEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public PanacheEntityEnhancer(IndexView index, DotName panacheEntityBaseName,
        List<PanacheMethodCustomizer> methodCustomizers) {
    this.panacheEntityBaseClassInfo = index.getClassByName(panacheEntityBaseName);
    this.indexView = index;
    this.methodCustomizers = methodCustomizers;
}
 
Example 19
Source File: JpaJandexScavenger.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Add the class to the reflective list with full method and field access.
 * Add the superclasses recursively as well as the interfaces.
 * Un-indexed classes/interfaces are accumulated to be thrown as a configuration error in the top level caller method
 * <p>
 * TODO should we also return the return types of all methods and fields? It could contain Enums for example.
 */
private static void addClassHierarchyToReflectiveList(IndexView index, JpaEntitiesBuildItem domainObjectCollector,
        Set<String> enumTypeCollector, Set<String> javaTypeCollector, DotName className, Set<DotName> unindexedClasses) {
    if (className == null || isIgnored(className)) {
        // bail out if java.lang.Object or a class we want to ignore
        return;
    }

    // if the class is in the java. package and is not ignored, we want to register it for reflection
    if (isInJavaPackage(className)) {
        javaTypeCollector.add(className.toString());
        return;
    }

    ClassInfo classInfo = index.getClassByName(className);
    if (classInfo == null) {
        unindexedClasses.add(className);
        return;
    }
    // we need to check for enums
    for (FieldInfo fieldInfo : classInfo.fields()) {
        DotName fieldType = fieldInfo.type().name();
        ClassInfo fieldTypeClassInfo = index.getClassByName(fieldType);
        if (fieldTypeClassInfo != null && ENUM.equals(fieldTypeClassInfo.superName())) {
            enumTypeCollector.add(fieldType.toString());
        }
    }

    //Capture this one (for various needs: Reflective access enablement, Hibernate enhancement, JPA Template)
    collectDomainObject(domainObjectCollector, classInfo);

    // add superclass recursively
    addClassHierarchyToReflectiveList(index, domainObjectCollector, enumTypeCollector, javaTypeCollector,
            classInfo.superName(),
            unindexedClasses);
    // add interfaces recursively
    for (DotName interfaceDotName : classInfo.interfaceNames()) {
        addClassHierarchyToReflectiveList(index, domainObjectCollector, enumTypeCollector, javaTypeCollector,
                interfaceDotName,
                unindexedClasses);
    }
}
 
Example 20
Source File: TypeUtil.java    From smallrye-open-api with Apache License 2.0 3 votes vote down vote up
/**
 * Determines if a type is eligible for registration. If the schema type is
 * array or object, the type must be in the provided index. Otherwise, only
 * those types with defined properties beyond 'type' and 'format' are
 * eligible.
 * 
 * @param index index of classes to consider
 * @param classType the type to check
 * @return true if the type may be registered in the SchemaRegistry, false otherwise.
 */
public static boolean allowRegistration(IndexView index, Type classType) {
    TypeWithFormat typeFormat = getTypeFormat(classType);

    if (typeFormat.isSchemaType(SchemaType.ARRAY, SchemaType.OBJECT)) {
        return index.getClassByName(classType.name()) != null;
    }
    return typeFormat.getProperties().size() > 2;
}