Java Code Examples for org.jboss.jandex.IndexView

The following examples show how to use org.jboss.jandex.IndexView. These examples are extracted from open source projects. 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 Project: camel-quarkus   Source File: GoogleSheetsProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
void registerForReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        BuildProducer<UnbannedReflectiveBuildItem> unbannedClass, CombinedIndexBuildItem combinedIndex) {
    IndexView index = combinedIndex.getIndex();

    // Google sheets component configuration class reflection
    Collection<AnnotationInstance> uriParams = index
            .getAnnotations(DotName.createSimple("org.apache.camel.spi.UriParams"));

    String[] googleMailConfigClasses = uriParams.stream()
            .map(annotation -> annotation.target())
            .filter(annotationTarget -> annotationTarget.kind().equals(AnnotationTarget.Kind.CLASS))
            .map(annotationTarget -> annotationTarget.asClass().name().toString())
            .filter(className -> className.startsWith("org.apache.camel.component.google.sheets"))
            .toArray(String[]::new);

    reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, googleMailConfigClasses));
    unbannedClass.produce(new UnbannedReflectiveBuildItem(googleMailConfigClasses));
}
 
Example 2
Source Project: quarkus   Source File: TestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Collect the beans with our custom bean defining annotation and configure them with the runtime config
 *
 * @param recorder - runtime recorder
 * @param beanArchiveIndex - index of type information
 * @param testBeanProducer - producer for located Class<IConfigConsumer> bean types
 */
@BuildStep
@Record(STATIC_INIT)
void scanForBeans(TestRecorder recorder, BeanArchiveIndexBuildItem beanArchiveIndex,
        BuildProducer<TestBeanBuildItem> testBeanProducer) {
    IndexView indexView = beanArchiveIndex.getIndex();
    Collection<AnnotationInstance> testBeans = indexView.getAnnotations(TEST_ANNOTATION);
    for (AnnotationInstance ann : testBeans) {
        ClassInfo beanClassInfo = ann.target().asClass();
        try {
            boolean isConfigConsumer = beanClassInfo.interfaceNames()
                    .stream()
                    .anyMatch(dotName -> dotName.equals(DotName.createSimple(IConfigConsumer.class.getName())));
            if (isConfigConsumer) {
                Class<IConfigConsumer> beanClass = (Class<IConfigConsumer>) Class.forName(beanClassInfo.name().toString(),
                        true, Thread.currentThread().getContextClassLoader());
                testBeanProducer.produce(new TestBeanBuildItem(beanClass));
                log.infof("The configured bean: %s", beanClass);
            }
        } catch (ClassNotFoundException e) {
            log.warn("Failed to load bean class", e);
        }
    }
}
 
Example 3
Source Project: quarkus   Source File: FragmentMethodsUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the simple expected implementation of a Fragment interface or throws an
 * exception indicating the problem
 */
static DotName getImplementationDotName(DotName customInterfaceToImplement, IndexView index) {
    Collection<ClassInfo> knownImplementors = index.getAllKnownImplementors(customInterfaceToImplement);

    if (knownImplementors.size() > 1) {
        DotName previouslyFound = null;
        for (ClassInfo knownImplementor : knownImplementors) {
            if (knownImplementor.name().toString().endsWith("Impl")) { // the default suffix that Spring Data JPA looks for is 'Impl'
                if (previouslyFound != null) { // make sure we don't have multiple implementations suffixed with 'Impl'
                    throw new IllegalArgumentException(
                            "Interface " + customInterfaceToImplement
                                    + " must contain a single implementation whose name ends with 'Impl'. Multiple implementations were found: "
                                    + previouslyFound + "," + knownImplementor);
                }
                previouslyFound = knownImplementor.name();
            }
        }
        return previouslyFound;
    } else if (knownImplementors.size() == 1) {
        return knownImplementors.iterator().next().name();
    } else {
        throw new IllegalArgumentException(
                "No implementation of interface " + customInterfaceToImplement + " was found");
    }
}
 
Example 4
Source Project: quarkus   Source File: Types.java    License: 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 5
Source Project: smallrye-graphql   Source File: GenerateSchemaMojo.java    License: Apache License 2.0 6 votes vote down vote up
private String generateSchema(IndexView index) {
    Config config = new Config() {
        @Override
        public boolean isIncludeScalarsInSchema() {
            return includeScalars;
        }

        @Override
        public boolean isIncludeDirectivesInSchema() {
            return includeDirectives;
        }

        @Override
        public boolean isIncludeSchemaDefinitionInSchema() {
            return includeSchemaDefinition;
        }

        @Override
        public boolean isIncludeIntrospectionTypesInSchema() {
            return includeIntrospectionTypes;
        }
    };
    Schema internalSchema = SchemaBuilder.build(index);
    GraphQLSchema graphQLSchema = Bootstrap.bootstrap(internalSchema);
    return new SchemaPrinter(config).print(graphQLSchema);
}
 
Example 6
Source Project: quarkus   Source File: RESTEasyExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void scanAsyncResponseProviders(IndexView index) {
    for (ClassInfo providerClass : index.getAllKnownImplementors(DOTNAME_ASYNC_RESPONSE_PROVIDER)) {
        for (AnnotationInstance annotation : providerClass.classAnnotations()) {
            if (annotation.name().equals(DOTNAME_PROVIDER)) {
                for (Type interf : providerClass.interfaceTypes()) {
                    if (interf.kind() == Type.Kind.PARAMETERIZED_TYPE
                            && interf.name().equals(DOTNAME_ASYNC_RESPONSE_PROVIDER)) {
                        ParameterizedType pType = interf.asParameterizedType();
                        if (pType.arguments().size() == 1) {
                            Type asyncType = pType.arguments().get(0);
                            asyncTypes.add(asyncType.name());
                        }
                    }
                }
            }
        }
    }
}
 
Example 7
Source Project: quarkus   Source File: JandexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the given Jandex ClassInfo is a subclass of the given <tt>parentName</tt>. Note that this will
 * not check interfaces.
 * 
 * @param index the index to use to look up super classes.
 * @param info the ClassInfo we want to check.
 * @param parentName the name of the superclass we want to find.
 * @return true if the given ClassInfo has <tt>parentName</tt> as a superclass.
 * @throws BuildException if one of the superclasses is not indexed.
 */
public static boolean isSubclassOf(IndexView index, ClassInfo info, DotName parentName) throws BuildException {
    if (info.superName().equals(DOTNAME_OBJECT)) {
        return false;
    }
    if (info.superName().equals(parentName)) {
        return true;
    }

    // climb up the hierarchy of classes
    Type superType = info.superClassType();
    ClassInfo superClass = index.getClassByName(superType.name());
    if (superClass == null) {
        // this can happens if the parent is not inside the Jandex index
        throw new BuildException("The class " + superType.name() + " is not inside the Jandex index",
                Collections.emptyList());
    }
    return isSubclassOf(index, superClass, parentName);
}
 
Example 8
Source Project: kogito-runtimes   Source File: KogitoAssetsProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private Collection<GeneratedFile> getGeneratedPersistenceFiles( AppPaths appPaths, IndexView index, boolean usePersistence, List<String> parameters ) {
    GeneratorContext context = buildContext(appPaths, index);

    Collection<ClassInfo> modelClasses = index
            .getAllKnownImplementors(createDotName( Model.class.getCanonicalName()));

    Collection<GeneratedFile> generatedFiles = new ArrayList<>();

    for (Path projectPath : appPaths.projectPaths) {
        PersistenceGenerator persistenceGenerator = new PersistenceGenerator( new File( projectPath.toFile(), "target" ),
                modelClasses, usePersistence,
                new JandexProtoGenerator( index, createDotName( Generated.class.getCanonicalName() ),
                        createDotName( VariableInfo.class.getCanonicalName() ) ),
                parameters );
        persistenceGenerator.setDependencyInjection( new CDIDependencyInjectionAnnotator() );
        persistenceGenerator.setPackageName( appPackageName );
        persistenceGenerator.setContext( context );

        generatedFiles.addAll( persistenceGenerator.generate() );
    }
    return generatedFiles;
}
 
Example 9
Source Project: quarkus   Source File: PicocliProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
void picocliRunner(ApplicationIndexBuildItem applicationIndex,
        CombinedIndexBuildItem combinedIndex,
        BuildProducer<AdditionalBeanBuildItem> additionalBean,
        BuildProducer<QuarkusApplicationClassBuildItem> quarkusApplicationClass,
        BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformer) {
    IndexView index = combinedIndex.getIndex();
    Collection<DotName> topCommands = classesAnnotatedWith(index, TopCommand.class.getName());
    if (topCommands.isEmpty()) {
        List<DotName> commands = classesAnnotatedWith(applicationIndex.getIndex(),
                CommandLine.Command.class.getName());
        if (commands.size() == 1) {
            annotationsTransformer.produce(createAnnotationTransformer(commands.get(0)));
        }
    }
    if (index.getAnnotations(DotName.createSimple(QuarkusMain.class.getName())).isEmpty()) {
        additionalBean.produce(AdditionalBeanBuildItem.unremovableOf(PicocliRunner.class));
        additionalBean.produce(AdditionalBeanBuildItem.unremovableOf(DefaultPicocliCommandLineFactory.class));
        quarkusApplicationClass.produce(new QuarkusApplicationClassBuildItem(PicocliRunner.class));
    }
}
 
Example 10
Source Project: quarkus   Source File: QuteProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void produceExtensionMethod(IndexView index, BuildProducer<TemplateExtensionMethodBuildItem> extensionMethods,
        MethodInfo method, AnnotationInstance extensionAnnotation) {
    // Analyze matchName and priority so that it could be used during validation 
    String matchName = null;
    AnnotationValue matchNameValue = extensionAnnotation.value(MATCH_NAME);
    if (matchNameValue != null) {
        matchName = matchNameValue.asString();
    }
    if (matchName == null) {
        matchName = method.name();
    }
    int priority = TemplateExtension.DEFAULT_PRIORITY;
    AnnotationValue priorityValue = extensionAnnotation.value(PRIORITY);
    if (priorityValue != null) {
        priority = priorityValue.asInt();
    }
    extensionMethods.produce(new TemplateExtensionMethodBuildItem(method, matchName,
            index.getClassByName(method.parameters().get(0).name()), priority));
}
 
Example 11
Source Project: quarkus   Source File: ResteasyCommonProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void registerJsonContextResolver(
        DotName jsonImplementation,
        DotName jsonContextResolver,
        CombinedIndexBuildItem combinedIndexBuildItem,
        BuildProducer<ResteasyJaxrsProviderBuildItem> jaxrsProvider,
        BuildProducer<AdditionalBeanBuildItem> additionalBean,
        BuildProducer<UnremovableBeanBuildItem> unremovable) {

    IndexView index = combinedIndexBuildItem.getIndex();

    jaxrsProvider.produce(new ResteasyJaxrsProviderBuildItem(jsonContextResolver.toString()));

    // this needs to be registered manually since the runtime module is not indexed by Jandex
    additionalBean.produce(AdditionalBeanBuildItem.unremovableOf(jsonContextResolver.toString()));
    Set<String> userSuppliedProducers = getUserSuppliedJsonProducerBeans(index, jsonImplementation);
    if (!userSuppliedProducers.isEmpty()) {
        unremovable.produce(
                new UnremovableBeanBuildItem(new UnremovableBeanBuildItem.BeanClassNamesExclusion(userSuppliedProducers)));
    }
}
 
Example 12
Source Project: quarkus   Source File: SpringWebProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
public void generateExceptionMapperProviders(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem,
        BuildProducer<GeneratedClassBuildItem> generatedExceptionMappers,
        BuildProducer<ResteasyJaxrsProviderBuildItem> providersProducer,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) {

    TypesUtil typesUtil = new TypesUtil(Thread.currentThread().getContextClassLoader());

    // Look for all exception classes that are annotated with @ResponseStatus

    IndexView index = beanArchiveIndexBuildItem.getIndex();
    ClassOutput classOutput = new GeneratedClassGizmoAdaptor(generatedExceptionMappers, true);
    generateMappersForResponseStatusOnException(providersProducer, index, classOutput, typesUtil);
    generateMappersForExceptionHandlerInControllerAdvice(providersProducer, reflectiveClassProducer, index, classOutput,
            typesUtil);
}
 
Example 13
Source Project: quarkus   Source File: IndexClassLookupUtils.java    License: Apache License 2.0 6 votes vote down vote up
static ClassInfo getClassByName(IndexView index, DotName dotName, boolean withLogging) {
    if (dotName == null) {
        throw new IllegalArgumentException("Cannot lookup class, provided DotName was null.");
    }
    if (index == null) {
        throw new IllegalArgumentException("Cannot lookup class, provided Jandex Index was null.");
    }
    ClassInfo info = index.getClassByName(dotName);
    if (info == null && withLogging && !alreadyKnown.contains(dotName)) {
        // class not in index, log info as this may cause the application to blow up or behave weirdly
        LOGGER.infof("Class for name: %s was not found in Jandex index. Please ensure the class " +
                "is part of the index.", dotName);
        alreadyKnown.add(dotName);
    }
    return info;
}
 
Example 14
@Test
public void testMethodRolesAllowedGeneratedScheme() throws IOException {
    Index index = indexOf(RolesAllowedApp.class, RolesAllowedResource2.class);
    OpenApiConfig config = emptyConfig();
    IndexView filtered = new FilteredIndexView(index, config);
    OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
    OpenAPI result = scanner.scan();
    printToConsole(result);
    SecurityRequirement requirement = result.getPaths().getPathItem("/v2/secured").getGET().getSecurity().get(0);
    assertNotNull(requirement);
    assertEquals(2, requirement.getScheme("rolesScheme").size());
    assertEquals("admin", requirement.getScheme("rolesScheme").get(0));
    assertEquals("users", requirement.getScheme("rolesScheme").get(1));
    assertArrayEquals(new String[] { "admin", "users" },
            result.getComponents()
                    .getSecuritySchemes()
                    .get("rolesScheme")
                    .getFlows()
                    .getClientCredentials()
                    .getScopes()
                    .keySet()
                    .toArray());
}
 
Example 15
Source Project: quarkus   Source File: SpringDataJPAProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
void build(CombinedIndexBuildItem index,
        BuildProducer<GeneratedClassBuildItem> generatedClasses,
        BuildProducer<GeneratedBeanBuildItem> generatedBeans,
        BuildProducer<AdditionalBeanBuildItem> additionalBeans, BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {

    detectAndLogSpecificSpringPropertiesIfExist();

    IndexView indexIndex = index.getIndex();
    List<ClassInfo> interfacesExtendingCrudRepository = getAllInterfacesExtending(DotNames.SUPPORTED_REPOSITORIES,
            indexIndex);

    removeNoRepositoryBeanClasses(interfacesExtendingCrudRepository);
    implementCrudRepositories(generatedBeans, generatedClasses, additionalBeans, reflectiveClasses,
            interfacesExtendingCrudRepository, indexIndex);
}
 
Example 16
Source Project: quarkus   Source File: Types.java    License: 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 = getClassByName(index, parameterizedType.name());
        if (classInfo != null) {
            List<TypeVariable> typeParameters = classInfo.typeParameters();
            List<Type> arguments = parameterizedType.arguments();
            Map<TypeVariable, Type> resolvedMap = buildResolvedMap(arguments, typeParameters,
                    resolvedTypeParameters, index);
            Type[] typeParams = new Type[typeParameters.size()];
            for (int i = 0; i < typeParameters.size(); i++) {
                typeParams[i] = resolveTypeParam(arguments.get(i), resolvedMap, index);
            }
            return ParameterizedType.create(parameterizedType.name(), typeParams, null);
        }
    }
    return typeParam;
}
 
Example 17
Source Project: quarkus   Source File: SpringDIProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
SpringBeanNameToDotNameBuildItem createBeanNamesMap(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) {
    final Map<String, DotName> result = new HashMap<>();

    final IndexView index = beanArchiveIndexBuildItem.getIndex();
    final Collection<AnnotationInstance> stereotypeInstances = new ArrayList<>();
    stereotypeInstances.addAll(index.getAnnotations(SPRING_COMPONENT));
    stereotypeInstances.addAll(index.getAnnotations(SPRING_REPOSITORY));
    stereotypeInstances.addAll(index.getAnnotations(SPRING_SERVICE));
    for (AnnotationInstance stereotypeInstance : stereotypeInstances) {
        if (stereotypeInstance.target().kind() != AnnotationTarget.Kind.CLASS) {
            continue;
        }
        result.put(getBeanNameFromStereotypeInstance(stereotypeInstance), stereotypeInstance.target().asClass().name());
    }

    for (AnnotationInstance beanInstance : index.getAnnotations(BEAN_ANNOTATION)) {
        if (beanInstance.target().kind() != AnnotationTarget.Kind.METHOD) {
            continue;
        }
        result.put(getBeanNameFromBeanInstance(beanInstance), beanInstance.target().asMethod().returnType().name());
    }

    return new SpringBeanNameToDotNameBuildItem(result);
}
 
Example 18
Source Project: smallrye-open-api   Source File: ResourceParameterTests.java    License: Apache License 2.0 6 votes vote down vote up
/*************************************************************************/

    /*
     * Test case derived from original example in SmallRye OpenAPI issue #237.
     *
     * https://github.com/smallrye/smallrye-open-api/issues/237
     *
     */
    @Test
    public void testTypeVariableResponse() throws IOException, JSONException {
        Index i = indexOf(TypeVariableResponseTestResource.class,
                TypeVariableResponseTestResource.Dto.class);
        OpenApiConfig config = emptyConfig();
        IndexView filtered = new FilteredIndexView(i, config);
        OpenApiAnnotationScanner scanner = new OpenApiAnnotationScanner(config, filtered);
        OpenAPI result = scanner.scan();
        printToConsole(result);
        assertJsonEquals("resource.parameters.type-variable.json", result);
    }
 
Example 19
Source Project: quarkus   Source File: SpringSecurityProcessorUtil.java    License: 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 20
Source Project: quarkus   Source File: SmallRyeMetricsProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void collectMetricsClassAndSubClasses(IndexView index, Map<DotName, ClassInfo> collectedMetricsClasses,
        ClassInfo clazz) {
    collectedMetricsClasses.put(clazz.name(), clazz);
    for (ClassInfo subClass : index.getAllKnownSubclasses(clazz.name())) {
        collectedMetricsClasses.put(subClass.name(), subClass);
    }
}
 
Example 21
Source Project: quarkus   Source File: ResteasyCommonProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private Set<String> getUserSuppliedJsonProducerBeans(IndexView index, DotName jsonImplementation) {
    Set<String> result = new HashSet<>();
    for (AnnotationInstance annotation : index.getAnnotations(DotNames.PRODUCES)) {
        if (annotation.target().kind() != AnnotationTarget.Kind.METHOD) {
            continue;
        }
        if (jsonImplementation.equals(annotation.target().asMethod().returnType().name())) {
            result.add(annotation.target().asMethod().declaringClass().name().toString());
        }
    }
    return result;
}
 
Example 22
Source Project: quarkus   Source File: QuteProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void processsTemplateData(IndexView index, AnnotationInstance templateData, AnnotationTarget annotationTarget,
        Set<DotName> controlled, Map<DotName, AnnotationInstance> uncontrolled, Map<DotName, ClassInfo> nameToClass) {
    AnnotationValue targetValue = templateData.value("target");
    if (targetValue == null || targetValue.asClass().name().equals(ValueResolverGenerator.TEMPLATE_DATA)) {
        ClassInfo annotationTargetClass = annotationTarget.asClass();
        controlled.add(annotationTargetClass.name());
        nameToClass.put(annotationTargetClass.name(), annotationTargetClass);
    } else {
        ClassInfo uncontrolledClass = index.getClassByName(targetValue.asClass().name());
        if (uncontrolledClass != null) {
            uncontrolled.compute(uncontrolledClass.name(), (c, v) -> {
                if (v == null) {
                    nameToClass.put(uncontrolledClass.name(), uncontrolledClass);
                    return templateData;
                }
                if (!Objects.equals(v.value(ValueResolverGenerator.IGNORE),
                        templateData.value(ValueResolverGenerator.IGNORE))
                        || !Objects.equals(v.value(ValueResolverGenerator.PROPERTIES),
                                templateData.value(ValueResolverGenerator.PROPERTIES))
                        || !Objects.equals(v.value(ValueResolverGenerator.IGNORE_SUPERCLASSES),
                                templateData.value(ValueResolverGenerator.IGNORE_SUPERCLASSES))) {
                    throw new IllegalStateException(
                            "Multiple unequal @TemplateData declared for " + c + ": " + v + " and " + templateData);
                }
                return v;
            });
        } else {
            LOGGER.warnf("@TemplateData#target() not available: %s", annotationTarget.asClass().name());
        }
    }
}
 
Example 23
Source Project: quarkus   Source File: HibernateValidatorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private static void contributeClassMarkedForCascadingValidation(Set<DotName> classNamesCollector,
        IndexView indexView, DotName consideredAnnotation, Type type) {
    if (VALID != consideredAnnotation) {
        return;
    }

    DotName className = getClassName(type);
    if (className != null) {
        contributeClass(classNamesCollector, indexView, className);
    }
}
 
Example 24
Source Project: camel-quarkus   Source File: MicroProfileHealthProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@BuildStep
List<CamelBeanBuildItem> camelHealthDiscovery(
        CombinedIndexBuildItem combinedIndex,
        CamelMicroProfileHealthConfig config) {

    List<CamelBeanBuildItem> buildItems = new ArrayList<>();
    if (config.enabled) {
        IndexView index = combinedIndex.getIndex();
        Collection<ClassInfo> healthChecks = index.getAllKnownImplementors(CAMEL_HEALTH_CHECK_DOTNAME);
        Collection<ClassInfo> healthCheckRepositories = index
                .getAllKnownImplementors(CAMEL_HEALTH_CHECK_REPOSITORY_DOTNAME);

        // Create CamelBeanBuildItem to bind instances of HealthCheck to the camel registry
        healthChecks.stream()
                .filter(CamelSupport::isConcrete)
                .filter(CamelSupport::isPublic)
                .filter(ClassInfo::hasNoArgsConstructor)
                .map(classInfo -> new CamelBeanBuildItem(classInfo.simpleName(), classInfo.name().toString()))
                .forEach(buildItems::add);

        // Create CamelBeanBuildItem to bind instances of HealthCheckRepository to the camel registry
        healthCheckRepositories.stream()
                .filter(CamelSupport::isConcrete)
                .filter(CamelSupport::isPublic)
                .filter(ClassInfo::hasNoArgsConstructor)
                .filter(classInfo -> !classInfo.simpleName().equals(DefaultHealthCheckRegistry.class.getSimpleName()))
                .map(classInfo -> new CamelBeanBuildItem(classInfo.simpleName(), classInfo.name().toString()))
                .forEach(buildItems::add);
    }

    return buildItems;
}
 
Example 25
Source Project: smallrye-open-api   Source File: FilteredIndexView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param delegate the original (to be wrapped) index
 * @param config the config
 */
public FilteredIndexView(IndexView delegate, OpenApiConfig config) {
    this.delegate = delegate;

    scanClasses = config.scanClasses();
    scanPackages = config.scanPackages();
    scanExcludeClasses = config.scanExcludeClasses();
    scanExcludePackages = config.scanExcludePackages();

}
 
Example 26
Source Project: quarkus   Source File: JpaJandexScavenger.java    License: Apache License 2.0 5 votes vote down vote up
private static void enlistEmbeddedsAndElementCollections(IndexView index, JpaEntitiesBuildItem domainObjectCollector,
        Set<String> enumTypeCollector, Set<String> javaTypeCollector, Set<DotName> unindexedClasses) {
    Set<DotName> embeddedTypes = new HashSet<>();

    for (DotName embeddedAnnotation : EMBEDDED_ANNOTATIONS) {
        Collection<AnnotationInstance> annotations = index.getAnnotations(embeddedAnnotation);

        for (AnnotationInstance annotation : annotations) {
            AnnotationTarget target = annotation.target();

            switch (target.kind()) {
                case FIELD:
                    collectEmbeddedTypes(embeddedTypes, target.asField().type());
                    break;
                case METHOD:
                    collectEmbeddedTypes(embeddedTypes, target.asMethod().returnType());
                    break;
                default:
                    throw new IllegalStateException(
                            "[internal error] " + embeddedAnnotation + " placed on a unknown element: " + target);
            }

        }
    }

    for (DotName embeddedType : embeddedTypes) {
        addClassHierarchyToReflectiveList(index, domainObjectCollector, enumTypeCollector, javaTypeCollector, embeddedType,
                unindexedClasses);
    }
}
 
Example 27
Source Project: quarkus   Source File: NotExposedMethodImplementor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void implement(ClassCreator classCreator, IndexView index, MethodPropertiesAccessor accessor,
        RestDataResourceInfo resourceInfo) {
    MethodCreator methodCreator = classCreator
            .getMethodCreator(methodMetadata.getName(), Response.class.getName(), methodMetadata.getParameterTypes());
    methodCreator
            .throwException(RuntimeException.class, String.format("'%s' method is not exposed", methodMetadata.getName()));
    methodCreator.close();
}
 
Example 28
Source Project: quarkus   Source File: TestResourceManager.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<AnnotationInstance> findQuarkusTestResourceInstances(IndexView index) {
    Set<AnnotationInstance> testResourceAnnotations = new HashSet<>(index
            .getAnnotations(DotName.createSimple(QuarkusTestResource.class.getName())));
    for (AnnotationInstance annotation : index
            .getAnnotations(DotName.createSimple(QuarkusTestResource.List.class.getName()))) {
        Collections.addAll(testResourceAnnotations, annotation.value().asNestedArray());
    }
    return testResourceAnnotations;
}
 
Example 29
Source Project: mPaaS   Source File: InterfaceMetadataContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contribute(InFlightMetadataCollector metadataCollector,
		IndexView jandexIndex) {
	HibernatePropertyParser parser = new HibernatePropertyParser(
			metadataCollector);
	List<String> handled = new ArrayList<>();
	for (PersistentClass pclazz : metadataCollector.getEntityBindingMap()
			.values()) {
		readInterface(parser, pclazz, handled, metadataCollector);
	}
}
 
Example 30
Source Project: mPaaS   Source File: ExtraMappingMetadataContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contribute(InFlightMetadataCollector collector,
		IndexView jandexIndex) {
	DatabaseUtil.setDialect(collector.getDatabase().getDialect().getClass()
			.getSimpleName());
	// SecondPass将在hbm初始化完成后触发
	collector.addSecondPass(new SecondPass() {
		private static final long serialVersionUID = 481789941157136484L;

		@SuppressWarnings("rawtypes")
		@Override
		public void doSecondPass(Map persistentClasses)
				throws MappingException {
			for (Object clazz : persistentClasses.values()) {
				PersistentClass pclazz = (PersistentClass) clazz;
				Iterator<?> iterator = pclazz.getPropertyIterator();
				while (iterator.hasNext()) {
					Property prop = (Property) iterator.next();
					Value value = prop.getValue();
					if (value instanceof ToOne) {
						handleToOne(pclazz, (ToOne) value);
					} else if (value instanceof SimpleValue) {
						handleSimpleValue(pclazz, (SimpleValue) value);
					} else if (value instanceof Collection) {
						handleCollection(pclazz, (Collection) value);
					}
				}
			}
		}
	});
}