Search in sources :

Example 1 with BeanArchiveIndexBuildItem

use of io.quarkus.arc.deployment.BeanArchiveIndexBuildItem in project quarkus by quarkusio.

the class MetricsFromExtensionTestCase method buildCustomizer.

protected static Consumer<BuildChainBuilder> buildCustomizer() {
    return new Consumer<BuildChainBuilder>() {

        // This represents the extension.
        @Override
        public void accept(BuildChainBuilder builder) {
            builder.addBuildStep(context -> {
                BeanArchiveIndexBuildItem indexBuildItem = context.consume(BeanArchiveIndexBuildItem.class);
                for (ClassInfo clazz : indexBuildItem.getIndex().getKnownClasses()) {
                    for (MethodInfo method : clazz.methods()) {
                        if (method.name().startsWith("countMePlease")) {
                            Metadata metricMetadata = Metadata.builder().withType(MetricType.COUNTER).withName(clazz.name().toString() + "." + method.name()).build();
                            MetricBuildItem buildItem = new MetricBuildItem.Builder().metadata(metricMetadata).enabled(true).build();
                            context.produce(buildItem);
                        } else if (method.name().startsWith("countMeInBaseScope")) {
                            Metadata metricMetadata = Metadata.builder().withType(MetricType.COUNTER).withName(clazz.name().toString() + "." + method.name()).build();
                            MetricBuildItem buildItem = new MetricBuildItem.Builder().metadata(metricMetadata).registryType(MetricRegistry.Type.BASE).enabled(true).build();
                            context.produce(buildItem);
                        }
                    }
                }
            }).consumes(BeanArchiveIndexBuildItem.class).produces(MetricBuildItem.class).build();
        }
    };
}
Also used : Metadata(org.eclipse.microprofile.metrics.Metadata) MetricType(org.eclipse.microprofile.metrics.MetricType) Matchers(org.hamcrest.Matchers) ClassInfo(org.jboss.jandex.ClassInfo) QuarkusUnitTest(io.quarkus.test.QuarkusUnitTest) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) MethodInfo(org.jboss.jandex.MethodInfo) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) MetricBuildItem(io.quarkus.smallrye.metrics.deployment.spi.MetricBuildItem) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) MetricRegistry(org.eclipse.microprofile.metrics.MetricRegistry) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) RestAssured(io.restassured.RestAssured) Consumer(java.util.function.Consumer) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) BuildChainBuilder(io.quarkus.builder.BuildChainBuilder) Metadata(org.eclipse.microprofile.metrics.Metadata) MethodInfo(org.jboss.jandex.MethodInfo) MetricBuildItem(io.quarkus.smallrye.metrics.deployment.spi.MetricBuildItem) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) ClassInfo(org.jboss.jandex.ClassInfo)

Example 2 with BeanArchiveIndexBuildItem

use of io.quarkus.arc.deployment.BeanArchiveIndexBuildItem in project quarkus by quarkusio.

the class FunctionScannerBuildStep method scanFunctions.

@BuildStep
public void scanFunctions(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem, BuildProducer<BytecodeTransformerBuildItem> transformers, BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformer, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, BuildProducer<FunctionBuildItem> functions) {
    IndexView index = beanArchiveIndexBuildItem.getIndex();
    Collection<AnnotationInstance> funqs = index.getAnnotations(FUNQ);
    Set<ClassInfo> classes = new HashSet<>();
    Set<String> classNames = new HashSet<>();
    for (AnnotationInstance funqMethod : funqs) {
        MethodInfo method = funqMethod.target().asMethod();
        String className = method.declaringClass().name().toString();
        classNames.add(className);
        classes.add(method.declaringClass());
        String methodName = method.name();
        String functionName = null;
        if (funqMethod.value() != null) {
            functionName = funqMethod.value().asString();
        }
        if (functionName != null && functionName.isEmpty())
            functionName = null;
        functions.produce(new FunctionBuildItem(className, methodName, functionName));
        String source = FunctionScannerBuildStep.class.getSimpleName() + " > " + method.declaringClass() + "[" + method + "]";
        Type returnType = method.returnType();
        if (returnType.kind() != Type.Kind.VOID) {
            reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem.Builder().type(returnType).index(index).ignoreTypePredicate(IGNORE_TYPE_FOR_REFLECTION_PREDICATE).ignoreFieldPredicate(IGNORE_FIELD_FOR_REFLECTION_PREDICATE).ignoreMethodPredicate(IGNORE_METHOD_FOR_REFLECTION_PREDICATE).source(source).build());
        }
        for (short i = 0; i < method.parameters().size(); i++) {
            Type parameterType = method.parameters().get(i);
            if (!hasAnnotation(method, i, CONTEXT)) {
                reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem.Builder().type(parameterType).index(index).ignoreTypePredicate(IGNORE_TYPE_FOR_REFLECTION_PREDICATE).ignoreFieldPredicate(IGNORE_FIELD_FOR_REFLECTION_PREDICATE).ignoreMethodPredicate(IGNORE_METHOD_FOR_REFLECTION_PREDICATE).source(source).build());
            }
        }
    }
    Set<ClassInfo> withoutDefaultCtor = new HashSet<>();
    for (ClassInfo clazz : classes) {
        reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, true, clazz.name().toString()));
        if (!clazz.hasNoArgsConstructor()) {
            withoutDefaultCtor.add(clazz);
        }
    }
    unremovableBeans.produce(new UnremovableBeanBuildItem(b -> classNames.contains(b.getBeanClass().toString())));
    generateDefaultConstructors(transformers, withoutDefaultCtor);
    // we need to use an annotation transformer here instead of an AdditionalBeanBuildItem because
    // the use of the latter along with the BeanArchiveIndexBuildItem results in build cycles
    annotationsTransformer.produce(new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {

        @Override
        public boolean appliesTo(AnnotationTarget.Kind kind) {
            return kind == AnnotationTarget.Kind.CLASS;
        }

        @Override
        public void transform(TransformationContext transformationContext) {
            ClassInfo clazz = transformationContext.getTarget().asClass();
            if (!classes.contains(clazz))
                return;
            if (BuiltinScope.isDeclaredOn(clazz)) {
                // nothing to do as the presence of a scope will automatically qualify the class as a bean
                return;
            }
            Transformation transformation = transformationContext.transform();
            transformation.add(BuiltinScope.DEPENDENT.getName());
            if (clazz.classAnnotation(DotNames.TYPED) == null) {
                // Add @Typed(MySubresource.class)
                transformation.add(createTypedAnnotationInstance(clazz));
            }
            transformation.done();
        }
    }));
}
Also used : DotNames(io.quarkus.arc.processor.DotNames) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) Record(io.quarkus.deployment.annotations.Record) MethodVisitor(org.objectweb.asm.MethodVisitor) FunctionRecorder(io.quarkus.funqy.runtime.FunctionRecorder) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) BiFunction(java.util.function.BiFunction) DotName(org.jboss.jandex.DotName) Type(org.jboss.jandex.Type) ClassInfo(org.jboss.jandex.ClassInfo) RecorderContext(io.quarkus.deployment.recording.RecorderContext) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) HashSet(java.util.HashSet) BuildStep(io.quarkus.deployment.annotations.BuildStep) MethodInfo(org.jboss.jandex.MethodInfo) ReflectionRegistrationUtil(io.quarkus.funqy.deployment.ReflectionRegistrationUtil) AnnotationTarget(org.jboss.jandex.AnnotationTarget) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) ClassVisitor(org.objectweb.asm.ClassVisitor) AnnotationsTransformerBuildItem(io.quarkus.arc.deployment.AnnotationsTransformerBuildItem) Gizmo(io.quarkus.gizmo.Gizmo) IndexView(org.jboss.jandex.IndexView) AnnotationValue(org.jboss.jandex.AnnotationValue) ReflectiveHierarchyBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem) Opcodes(org.objectweb.asm.Opcodes) STATIC_INIT(io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT) Collection(java.util.Collection) Set(java.util.Set) Funq(io.quarkus.funqy.Funq) BuiltinScope(io.quarkus.arc.processor.BuiltinScope) AnnotationsTransformer(io.quarkus.arc.processor.AnnotationsTransformer) Context(io.quarkus.funqy.Context) List(java.util.List) AnnotationInstance(org.jboss.jandex.AnnotationInstance) Modifier(java.lang.reflect.Modifier) BytecodeTransformerBuildItem(io.quarkus.deployment.builditem.BytecodeTransformerBuildItem) Transformation(io.quarkus.arc.processor.Transformation) Transformation(io.quarkus.arc.processor.Transformation) IndexView(org.jboss.jandex.IndexView) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) AnnotationsTransformerBuildItem(io.quarkus.arc.deployment.AnnotationsTransformerBuildItem) Type(org.jboss.jandex.Type) AnnotationsTransformer(io.quarkus.arc.processor.AnnotationsTransformer) MethodInfo(org.jboss.jandex.MethodInfo) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) ClassInfo(org.jboss.jandex.ClassInfo) HashSet(java.util.HashSet) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Example 3 with BeanArchiveIndexBuildItem

use of io.quarkus.arc.deployment.BeanArchiveIndexBuildItem in project quarkus by quarkusio.

the class ResteasyCommonProcessor method setupProviders.

@BuildStep
JaxrsProvidersToRegisterBuildItem setupProviders(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, CombinedIndexBuildItem indexBuildItem, BeanArchiveIndexBuildItem beanArchiveIndexBuildItem, BuildProducer<UnremovableBeanBuildItem> unremovableBeans, List<ResteasyJaxrsProviderBuildItem> contributedProviderBuildItems, List<RestClientBuildItem> restClients, ResteasyConfigBuildItem resteasyConfig, Capabilities capabilities) throws Exception {
    Set<String> contributedProviders = new HashSet<>();
    for (ResteasyJaxrsProviderBuildItem contributedProviderBuildItem : contributedProviderBuildItems) {
        contributedProviders.add(contributedProviderBuildItem.getName());
    }
    Set<String> annotatedProviders = new HashSet<>();
    for (AnnotationInstance i : indexBuildItem.getIndex().getAnnotations(ResteasyDotNames.PROVIDER)) {
        if (i.target().kind() == AnnotationTarget.Kind.CLASS) {
            annotatedProviders.add(i.target().asClass().name().toString());
        }
        checkProperConfigAccessInProvider(i);
    }
    contributedProviders.addAll(annotatedProviders);
    Set<String> availableProviders = new HashSet<>(ServiceUtil.classNamesNamedIn(getClass().getClassLoader(), "META-INF/services/" + Providers.class.getName()));
    // this one is added manually in RESTEasy's ResteasyDeploymentImpl
    availableProviders.add(ServerFormUrlEncodedProvider.class.getName());
    MediaTypeMap<String> categorizedReaders = new MediaTypeMap<>();
    MediaTypeMap<String> categorizedWriters = new MediaTypeMap<>();
    MediaTypeMap<String> categorizedContextResolvers = new MediaTypeMap<>();
    Set<String> otherProviders = new HashSet<>();
    categorizeProviders(availableProviders, categorizedReaders, categorizedWriters, categorizedContextResolvers, otherProviders);
    // add the other providers detected
    Set<String> providersToRegister = new HashSet<>(otherProviders);
    if (!capabilities.isPresent(Capability.VERTX) && !capabilities.isCapabilityWithPrefixPresent(Capability.RESTEASY_JSON)) {
        boolean needJsonSupport = restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.CONSUMES) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.PRODUCES) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.RESTEASY_SSE_ELEMENT_TYPE) || restJsonSupportNeeded(indexBuildItem, ResteasyDotNames.RESTEASY_PART_TYPE);
        if (needJsonSupport) {
            LOGGER.warn("Quarkus detected the need of REST JSON support but you have not provided the necessary JSON " + "extension for this. You can visit https://quarkus.io/guides/rest-json for more " + "information on how to set one.");
        }
    }
    if (!capabilities.isPresent(Capability.RESTEASY_MUTINY)) {
        String needsMutinyClasses = mutinySupportNeeded(indexBuildItem);
        if (needsMutinyClasses != null) {
            LOGGER.warn("Quarkus detected the need for Mutiny reactive programming support, however the quarkus-resteasy-mutiny extension " + "was not present. Reactive REST endpoints in your application that return Uni or Multi " + "will not function as you expect until you add this extension. Endpoints that need Mutiny are: " + needsMutinyClasses);
        }
    }
    // we add a couple of default providers
    providersToRegister.add(StringTextStar.class.getName());
    providersToRegister.addAll(categorizedWriters.getPossible(MediaType.APPLICATION_JSON_TYPE));
    IndexView index = indexBuildItem.getIndex();
    IndexView beansIndex = beanArchiveIndexBuildItem.getIndex();
    // find the providers declared in our services
    boolean useBuiltinProviders = collectDeclaredProviders(restClients, resteasyConfig, providersToRegister, categorizedReaders, categorizedWriters, categorizedContextResolvers, index, beansIndex);
    if (useBuiltinProviders) {
        providersToRegister = new HashSet<>(contributedProviders);
        providersToRegister.addAll(availableProviders);
    } else {
        providersToRegister.addAll(contributedProviders);
    }
    if (providersToRegister.contains("org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider")) {
        // This abstract one is also accessed directly via reflection
        reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, "org.jboss.resteasy.plugins.providers.jsonb.AbstractJsonBindingProvider"));
    }
    JaxrsProvidersToRegisterBuildItem result = new JaxrsProvidersToRegisterBuildItem(providersToRegister, contributedProviders, annotatedProviders, useBuiltinProviders);
    // Providers that are also beans are unremovable
    unremovableBeans.produce(new UnremovableBeanBuildItem(b -> result.getProviders().contains(b.getBeanClass().toString())));
    return result;
}
Also used : DotNames(io.quarkus.arc.processor.DotNames) ConfigGroup(io.quarkus.runtime.annotations.ConfigGroup) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) AcceptEncodingGZIPFilter(org.jboss.resteasy.plugins.interceptors.AcceptEncodingGZIPFilter) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) ResteasyConfigSourceProvider(io.quarkus.resteasy.common.runtime.config.ResteasyConfigSourceProvider) FieldInfo(org.jboss.jandex.FieldInfo) CombinedIndexBuildItem(io.quarkus.deployment.builditem.CombinedIndexBuildItem) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) Capabilities(io.quarkus.deployment.Capabilities) ContextResolver(javax.ws.rs.ext.ContextResolver) MediaType(javax.ws.rs.core.MediaType) MethodInfo(org.jboss.jandex.MethodInfo) ServerFormUrlEncodedProvider(io.quarkus.resteasy.common.runtime.providers.ServerFormUrlEncodedProvider) AdditionalBeanBuildItem(io.quarkus.arc.deployment.AdditionalBeanBuildItem) Consumes(javax.ws.rs.Consumes) ResteasyConfigBuildItem(io.quarkus.resteasy.common.spi.ResteasyConfigBuildItem) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ParameterizedType(org.jboss.jandex.ParameterizedType) AnnotationValue(org.jboss.jandex.AnnotationValue) Consume(io.quarkus.deployment.annotations.Consume) Providers(javax.ws.rs.ext.Providers) STATIC_INIT(io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) ServletContextConfigSourceImpl(org.jboss.resteasy.microprofile.config.ServletContextConfigSourceImpl) StringTextStar(org.jboss.resteasy.plugins.providers.StringTextStar) List(java.util.List) MediaTypeMap(org.jboss.resteasy.core.MediaTypeMap) ConfigItem(io.quarkus.runtime.annotations.ConfigItem) AnnotationInstance(org.jboss.jandex.AnnotationInstance) BeanContainerBuildItem(io.quarkus.arc.deployment.BeanContainerBuildItem) ServiceProviderBuildItem(io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem) SseConstants(org.jboss.resteasy.plugins.providers.sse.SseConstants) ServletConfigSourceImpl(org.jboss.resteasy.microprofile.config.ServletConfigSourceImpl) StaticInitConfigSourceProviderBuildItem(io.quarkus.deployment.builditem.StaticInitConfigSourceProviderBuildItem) GZIPDecodingInterceptor(org.jboss.resteasy.plugins.interceptors.GZIPDecodingInterceptor) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) Record(io.quarkus.deployment.annotations.Record) MemorySize(io.quarkus.runtime.configuration.MemorySize) Logger(org.jboss.logging.Logger) DotName(org.jboss.jandex.DotName) Type(org.jboss.jandex.Type) FilterConfigSourceImpl(org.jboss.resteasy.microprofile.config.FilterConfigSourceImpl) Function(java.util.function.Function) ResteasyInjectorFactoryRecorder(io.quarkus.resteasy.common.runtime.ResteasyInjectorFactoryRecorder) ArrayList(java.util.ArrayList) ConfigRoot(io.quarkus.runtime.annotations.ConfigRoot) HashSet(java.util.HashSet) BuildStep(io.quarkus.deployment.annotations.BuildStep) GZIPEncodingInterceptor(org.jboss.resteasy.plugins.interceptors.GZIPEncodingInterceptor) ResteasyDotNames(io.quarkus.resteasy.common.spi.ResteasyDotNames) RuntimeValue(io.quarkus.runtime.RuntimeValue) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) IndexView(org.jboss.jandex.IndexView) Capability(io.quarkus.deployment.Capability) InjectorFactory(org.jboss.resteasy.spi.InjectorFactory) Kind(org.jboss.jandex.AnnotationValue.Kind) ServiceUtil(io.quarkus.deployment.util.ServiceUtil) ResteasyJaxrsProviderBuildItem(io.quarkus.resteasy.common.spi.ResteasyJaxrsProviderBuildItem) Collections(java.util.Collections) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MediaTypeMap(org.jboss.resteasy.core.MediaTypeMap) IndexView(org.jboss.jandex.IndexView) ResteasyJaxrsProviderBuildItem(io.quarkus.resteasy.common.spi.ResteasyJaxrsProviderBuildItem) UnremovableBeanBuildItem(io.quarkus.arc.deployment.UnremovableBeanBuildItem) Providers(javax.ws.rs.ext.Providers) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ServerFormUrlEncodedProvider(io.quarkus.resteasy.common.runtime.providers.ServerFormUrlEncodedProvider) ReflectiveClassBuildItem(io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem) HashSet(java.util.HashSet) StringTextStar(org.jboss.resteasy.plugins.providers.StringTextStar) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Example 4 with BeanArchiveIndexBuildItem

use of io.quarkus.arc.deployment.BeanArchiveIndexBuildItem in project quarkus by quarkusio.

the class MessageBundleProcessor method processBundles.

@BuildStep
List<MessageBundleBuildItem> processBundles(BeanArchiveIndexBuildItem beanArchiveIndex, ApplicationArchivesBuildItem applicationArchivesBuildItem, BuildProducer<GeneratedClassBuildItem> generatedClasses, BeanRegistrationPhaseBuildItem beanRegistration, BuildProducer<BeanConfiguratorBuildItem> configurators, BuildProducer<MessageBundleMethodBuildItem> messageTemplateMethods, BuildProducer<HotDeploymentWatchedFileBuildItem> watchedFiles, LocalesBuildTimeConfig locales) throws IOException {
    IndexView index = beanArchiveIndex.getIndex();
    Map<String, ClassInfo> found = new HashMap<>();
    List<MessageBundleBuildItem> bundles = new ArrayList<>();
    List<DotName> localizedInterfaces = new ArrayList<>();
    List<Path> messageFiles = findMessageFiles(applicationArchivesBuildItem, watchedFiles);
    // First collect all interfaces annotated with @MessageBundle
    for (AnnotationInstance bundleAnnotation : index.getAnnotations(Names.BUNDLE)) {
        if (bundleAnnotation.target().kind() == Kind.CLASS) {
            ClassInfo bundleClass = bundleAnnotation.target().asClass();
            if (Modifier.isInterface(bundleClass.flags())) {
                AnnotationValue nameValue = bundleAnnotation.value();
                String name = nameValue != null ? nameValue.asString() : MessageBundle.DEFAULT_NAME;
                if (!Namespaces.isValidNamespace(name)) {
                    throw new MessageBundleException(String.format("Message bundle name [%s] declared on %s must be a valid namespace - the value can only consist of alphanumeric characters and underscores", name, bundleClass));
                }
                if (found.containsKey(name)) {
                    throw new MessageBundleException(String.format("Message bundle interface name conflict - [%s] is used for both [%s] and [%s]", name, bundleClass, found.get(name)));
                }
                found.put(name, bundleClass);
                // Find localizations for each interface
                String defaultLocale = getDefaultLocale(bundleAnnotation, locales);
                List<ClassInfo> localized = new ArrayList<>();
                for (ClassInfo implementor : index.getKnownDirectImplementors(bundleClass.name())) {
                    if (Modifier.isInterface(implementor.flags())) {
                        localized.add(implementor);
                    }
                }
                Map<String, ClassInfo> localeToInterface = new HashMap<>();
                for (ClassInfo localizedInterface : localized) {
                    String locale = localizedInterface.classAnnotation(Names.LOCALIZED).value().asString();
                    if (defaultLocale.equals(locale)) {
                        throw new MessageBundleException(String.format("Locale of [%s] conflicts with the locale [%s] of the default message bundle [%s]", localizedInterface, locale, bundleClass));
                    }
                    ClassInfo previous = localeToInterface.put(locale, localizedInterface);
                    if (previous != null) {
                        throw new MessageBundleException(String.format("Cannot register [%s] - a localized message bundle interface exists for locale [%s]: %s", localizedInterface, locale, previous));
                    }
                    localizedInterfaces.add(localizedInterface.name());
                }
                // Find localized files
                Map<String, Path> localeToFile = new HashMap<>();
                // Message templates not specified by a localized interface are looked up in a localized file (merge candidate)
                Map<String, Path> localeToMergeCandidate = new HashMap<>();
                for (Path messageFile : messageFiles) {
                    String fileName = messageFile.getFileName().toString();
                    if (fileName.startsWith(name)) {
                        // msg_en.txt -> en
                        String locale = fileName.substring(fileName.indexOf('_') + 1, fileName.indexOf('.'));
                        ClassInfo localizedInterface = localeToInterface.get(locale);
                        if (defaultLocale.equals(locale) || localizedInterface != null) {
                            // both file and interface exist for one locale, therefore we need to merge them
                            Path previous = localeToMergeCandidate.put(locale, messageFile);
                            if (previous != null) {
                                throw new MessageBundleException(String.format("Cannot register [%s] - a localized file already exists for locale [%s]: [%s]", fileName, locale, previous.getFileName().toString()));
                            }
                        } else {
                            localeToFile.put(locale, messageFile);
                        }
                    }
                }
                bundles.add(new MessageBundleBuildItem(name, bundleClass, localeToInterface, localeToFile, localeToMergeCandidate, defaultLocale));
            } else {
                throw new MessageBundleException("@MessageBundle must be declared on an interface: " + bundleClass);
            }
        }
    }
    // Detect interfaces annotated with @Localized that don't extend a message bundle interface
    for (AnnotationInstance localizedAnnotation : index.getAnnotations(Names.LOCALIZED)) {
        if (localizedAnnotation.target().kind() == Kind.CLASS) {
            ClassInfo localized = localizedAnnotation.target().asClass();
            if (Modifier.isInterface(localized.flags())) {
                if (!localizedInterfaces.contains(localized.name())) {
                    throw new MessageBundleException("A localized message bundle interface must extend a message bundle interface: " + localized);
                }
            } else {
                throw new MessageBundleException("@Localized must be declared on an interface: " + localized);
            }
        }
    }
    // Generate implementations
    // name -> impl class
    Map<String, String> generatedImplementations = generateImplementations(bundles, generatedClasses, messageTemplateMethods);
    // Register synthetic beans
    for (MessageBundleBuildItem bundle : bundles) {
        ClassInfo bundleInterface = bundle.getDefaultBundleInterface();
        beanRegistration.getContext().configure(bundleInterface.name()).addType(bundle.getDefaultBundleInterface().name()).addQualifier(DotNames.DEFAULT).addQualifier().annotation(Names.LOCALIZED).addValue("value", getDefaultLocale(bundleInterface.classAnnotation(Names.BUNDLE), locales)).done().unremovable().scope(Singleton.class).creator(mc -> {
            // Just create a new instance of the generated class
            mc.returnValue(mc.newInstance(MethodDescriptor.ofConstructor(generatedImplementations.get(bundleInterface.name().toString()))));
        }).done();
        // Localized interfaces
        for (ClassInfo localizedInterface : bundle.getLocalizedInterfaces().values()) {
            beanRegistration.getContext().configure(localizedInterface.name()).addType(bundle.getDefaultBundleInterface().name()).addQualifier(localizedInterface.classAnnotation(Names.LOCALIZED)).unremovable().scope(Singleton.class).creator(mc -> {
                // Just create a new instance of the generated class
                mc.returnValue(mc.newInstance(MethodDescriptor.ofConstructor(generatedImplementations.get(localizedInterface.name().toString()))));
            }).done();
        }
        // Localized files
        for (Entry<String, Path> entry : bundle.getLocalizedFiles().entrySet()) {
            beanRegistration.getContext().configure(bundle.getDefaultBundleInterface().name()).addType(bundle.getDefaultBundleInterface().name()).addQualifier().annotation(Names.LOCALIZED).addValue("value", entry.getKey()).done().unremovable().scope(Singleton.class).creator(mc -> {
                // Just create a new instance of the generated class
                mc.returnValue(mc.newInstance(MethodDescriptor.ofConstructor(generatedImplementations.get(entry.getValue().toString()))));
            }).done();
        }
    }
    return bundles;
}
Also used : Path(java.nio.file.Path) DotNames(io.quarkus.arc.processor.DotNames) GeneratedClassGizmoAdaptor(io.quarkus.deployment.GeneratedClassGizmoAdaptor) IsNormal(io.quarkus.deployment.IsNormal) Expressions(io.quarkus.qute.Expressions) ListIterator(java.util.ListIterator) Namespaces(io.quarkus.qute.Namespaces) ClassOutput(io.quarkus.gizmo.ClassOutput) ClassInfo(org.jboss.jandex.ClassInfo) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) Expression(io.quarkus.qute.Expression) MethodInfo(org.jboss.jandex.MethodInfo) AdditionalBeanBuildItem(io.quarkus.arc.deployment.AdditionalBeanBuildItem) BeanDiscoveryFinishedBuildItem(io.quarkus.arc.deployment.BeanDiscoveryFinishedBuildItem) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) BytecodeCreator(io.quarkus.gizmo.BytecodeCreator) TemplateAnalysis(io.quarkus.qute.deployment.TemplatesAnalysisBuildItem.TemplateAnalysis) Match(io.quarkus.qute.deployment.QuteProcessor.Match) EvalContext(io.quarkus.qute.EvalContext) Path(java.nio.file.Path) AnnotationValue(org.jboss.jandex.AnnotationValue) BeanRegistrationPhaseBuildItem(io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem) MessageBundleRecorder(io.quarkus.qute.runtime.MessageBundleRecorder) STATIC_INIT(io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT) Predicate(java.util.function.Predicate) Part(io.quarkus.qute.Expression.Part) Message(io.quarkus.qute.i18n.Message) QuteConfig(io.quarkus.qute.runtime.QuteConfig) Set(java.util.Set) Annotations(io.quarkus.arc.processor.Annotations) Collectors(java.util.stream.Collectors) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) AnnotationInstance(org.jboss.jandex.AnnotationInstance) Modifier(java.lang.reflect.Modifier) Entry(java.util.Map.Entry) LocalesBuildTimeConfig(io.quarkus.runtime.LocalesBuildTimeConfig) Builder(io.quarkus.gizmo.ClassCreator.Builder) ResultHandle(io.quarkus.gizmo.ResultHandle) TryBlock(io.quarkus.gizmo.TryBlock) Localized(io.quarkus.qute.i18n.Localized) IntStream(java.util.stream.IntStream) SyntheticBeanBuildItem(io.quarkus.arc.deployment.SyntheticBeanBuildItem) Record(io.quarkus.deployment.annotations.Record) CatchBlockCreator(io.quarkus.gizmo.CatchBlockCreator) HotDeploymentWatchedFileBuildItem(io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem) Logger(org.jboss.logging.Logger) MethodCreator(io.quarkus.gizmo.MethodCreator) DotName(org.jboss.jandex.DotName) Type(org.jboss.jandex.Type) LookupConfig(io.quarkus.qute.deployment.QuteProcessor.LookupConfig) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) StringUtil(io.quarkus.runtime.util.StringUtil) ClassCreator(io.quarkus.gizmo.ClassCreator) Singleton(javax.inject.Singleton) Resolver(io.quarkus.qute.Resolver) MessageBundles(io.quarkus.qute.i18n.MessageBundles) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) BeanConfiguratorBuildItem(io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem.BeanConfiguratorBuildItem) BuildStep(io.quarkus.deployment.annotations.BuildStep) Kind(org.jboss.jandex.AnnotationTarget.Kind) AssignableResultHandle(io.quarkus.gizmo.AssignableResultHandle) FunctionCreator(io.quarkus.gizmo.FunctionCreator) BiConsumer(java.util.function.BiConsumer) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) BuildSystemTargetBuildItem(io.quarkus.deployment.pkg.builditem.BuildSystemTargetBuildItem) IndexView(org.jboss.jandex.IndexView) GeneratedResourceBuildItem(io.quarkus.deployment.builditem.GeneratedResourceBuildItem) BranchResult(io.quarkus.gizmo.BranchResult) MethodDescriptor(io.quarkus.gizmo.MethodDescriptor) Iterator(java.util.Iterator) ApplicationArchivesBuildItem(io.quarkus.deployment.builditem.ApplicationArchivesBuildItem) Files(java.nio.file.Files) ValueResolverGenerator(io.quarkus.qute.generator.ValueResolverGenerator) MessageBundle(io.quarkus.qute.i18n.MessageBundle) IOException(java.io.IOException) DescriptorUtils(io.quarkus.gizmo.DescriptorUtils) File(java.io.File) ApplicationArchive(io.quarkus.deployment.ApplicationArchive) EvaluatedParams(io.quarkus.qute.EvaluatedParams) Descriptors(io.quarkus.qute.generator.Descriptors) GeneratedClassBuildItem(io.quarkus.deployment.builditem.GeneratedClassBuildItem) LoopSectionHelper(io.quarkus.qute.LoopSectionHelper) Comparator(java.util.Comparator) Collections(java.util.Collections) BeanInfo(io.quarkus.arc.processor.BeanInfo) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IndexView(org.jboss.jandex.IndexView) ArrayList(java.util.ArrayList) DotName(org.jboss.jandex.DotName) AnnotationValue(org.jboss.jandex.AnnotationValue) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ClassInfo(org.jboss.jandex.ClassInfo) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Example 5 with BeanArchiveIndexBuildItem

use of io.quarkus.arc.deployment.BeanArchiveIndexBuildItem in project quarkus by vaadin.

the class VaadinQuarkusProcessor method mapVaadinServletPaths.

@BuildStep
void mapVaadinServletPaths(final BeanArchiveIndexBuildItem beanArchiveIndex, final BuildProducer<ServletBuildItem> servletProducer) {
    final IndexView indexView = beanArchiveIndex.getIndex();
    // Collect all VaadinServlet instances and remove QuarkusVaadinServlet
    // and VaadinServlet from the list.
    final Collection<ClassInfo> vaadinServlets = indexView.getAllKnownSubclasses(DotName.createSimple(VaadinServlet.class.getName())).stream().filter(servlet -> !servlet.name().toString().equals(QuarkusVaadinServlet.class.getName()) && !servlet.name().toString().equals(VaadinServlet.class.getName())).collect(Collectors.toList());
    // If no VaadinServlet instances found register QuarkusVaadinServlet
    if (vaadinServlets.isEmpty()) {
        servletProducer.produce(ServletBuildItem.builder(QuarkusVaadinServlet.class.getName(), QuarkusVaadinServlet.class.getName()).addMapping("/*").setAsyncSupported(true).build());
    } else {
        registerUserServlets(servletProducer, vaadinServlets);
    }
}
Also used : RouteContextWrapper(com.vaadin.quarkus.context.RouteContextWrapper) UIContextWrapper(com.vaadin.quarkus.context.UIContextWrapper) DotName(org.jboss.jandex.DotName) RouteScoped(com.vaadin.quarkus.annotation.RouteScoped) ClassInfo(org.jboss.jandex.ClassInfo) CombinedIndexBuildItem(io.quarkus.deployment.builditem.CombinedIndexBuildItem) VaadinServiceScoped(com.vaadin.quarkus.annotation.VaadinServiceScoped) VaadinSessionScopedContext(com.vaadin.quarkus.context.VaadinSessionScopedContext) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) Route(com.vaadin.flow.router.Route) ServletBuildItem(io.quarkus.undertow.deployment.ServletBuildItem) NormalUIScoped(com.vaadin.quarkus.annotation.NormalUIScoped) BuildStep(io.quarkus.deployment.annotations.BuildStep) AdditionalBeanBuildItem(io.quarkus.arc.deployment.AdditionalBeanBuildItem) FeatureBuildItem(io.quarkus.deployment.builditem.FeatureBuildItem) HasErrorParameter(com.vaadin.flow.router.HasErrorParameter) BeanArchiveIndexBuildItem(io.quarkus.arc.deployment.BeanArchiveIndexBuildItem) UIScoped(com.vaadin.quarkus.annotation.UIScoped) IndexView(org.jboss.jandex.IndexView) AnnotationValue(org.jboss.jandex.AnnotationValue) VaadinServiceScopedContext(com.vaadin.quarkus.context.VaadinServiceScopedContext) ContextRegistrationPhaseBuildItem(io.quarkus.arc.deployment.ContextRegistrationPhaseBuildItem) UIScopedContext(com.vaadin.quarkus.context.UIScopedContext) Collection(java.util.Collection) ContextConfiguratorBuildItem(io.quarkus.arc.deployment.ContextRegistrationPhaseBuildItem.ContextConfiguratorBuildItem) VaadinServlet(com.vaadin.flow.server.VaadinServlet) CustomScopeBuildItem(io.quarkus.arc.deployment.CustomScopeBuildItem) RouteScopedContext(com.vaadin.quarkus.context.RouteScopedContext) Collectors(java.util.stream.Collectors) WebServlet(javax.servlet.annotation.WebServlet) Objects(java.util.Objects) Stream(java.util.stream.Stream) AnnotationInstance(org.jboss.jandex.AnnotationInstance) BeanDefiningAnnotationBuildItem(io.quarkus.arc.deployment.BeanDefiningAnnotationBuildItem) NormalRouteScoped(com.vaadin.quarkus.annotation.NormalRouteScoped) Optional(java.util.Optional) VaadinSessionScoped(com.vaadin.quarkus.annotation.VaadinSessionScoped) QuarkusVaadinServlet(com.vaadin.quarkus.QuarkusVaadinServlet) QuarkusVaadinServlet(com.vaadin.quarkus.QuarkusVaadinServlet) IndexView(org.jboss.jandex.IndexView) VaadinServlet(com.vaadin.flow.server.VaadinServlet) QuarkusVaadinServlet(com.vaadin.quarkus.QuarkusVaadinServlet) ClassInfo(org.jboss.jandex.ClassInfo) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Aggregations

BeanArchiveIndexBuildItem (io.quarkus.arc.deployment.BeanArchiveIndexBuildItem)5 BuildProducer (io.quarkus.deployment.annotations.BuildProducer)4 BuildStep (io.quarkus.deployment.annotations.BuildStep)4 AnnotationInstance (org.jboss.jandex.AnnotationInstance)4 ClassInfo (org.jboss.jandex.ClassInfo)4 MethodInfo (org.jboss.jandex.MethodInfo)4 AdditionalBeanBuildItem (io.quarkus.arc.deployment.AdditionalBeanBuildItem)3 DotNames (io.quarkus.arc.processor.DotNames)3 STATIC_INIT (io.quarkus.deployment.annotations.ExecutionTime.STATIC_INIT)3 Record (io.quarkus.deployment.annotations.Record)3 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3 AnnotationValue (org.jboss.jandex.AnnotationValue)3 DotName (org.jboss.jandex.DotName)3 IndexView (org.jboss.jandex.IndexView)3 CombinedIndexBuildItem (io.quarkus.deployment.builditem.CombinedIndexBuildItem)2 ArrayList (java.util.ArrayList)2