Search in sources :

Example 6 with IndexView

use of org.jboss.jandex.IndexView in project wildfly-swarm by wildfly-swarm.

the class DeploymentProducer method index.

private void index(Archive<?> archive, List<IndexView> indexes) throws IOException {
    LOGGER.debugv("Indexing archive: {0}", archive.getName());
    // First try to load attached index
    Node indexNode = archive.get(ArchivePaths.create(INDEX_LOCATION));
    if (indexNode != null) {
        try (InputStream indexStream = indexNode.getAsset().openStream()) {
            LOGGER.debugv("Loading attached index from archive: {0}", archive.getName());
            indexes.add(new IndexReader(indexStream).read());
        }
    } else {
        // No index found - index all classes found
        Indexer indexer = new Indexer();
        for (Map.Entry<ArchivePath, Node> entry : archive.getContent(this::isClass).entrySet()) {
            try (InputStream contentStream = entry.getValue().getAsset().openStream()) {
                LOGGER.debugv("Indexing asset: {0} from archive: {1}", entry.getKey().get(), archive.getName());
                indexer.index(contentStream);
            } catch (IOException indexerIOException) {
                LOGGER.warnv(indexerIOException, "Failed parsing: {0} from archive: {1}", entry.getKey().get(), archive.getName());
            }
        }
        Index index = indexer.complete();
        indexes.add(index);
    }
    if (archive instanceof LibraryContainer) {
        for (Map.Entry<ArchivePath, Node> entry : archive.getContent(a -> a.get().endsWith(JAR_SUFFIX)).entrySet()) {
            if (entry.getValue().getAsset() instanceof ArchiveAsset) {
                ArchiveAsset archiveAsset = (ArchiveAsset) entry.getValue().getAsset();
                index(archiveAsset.getArchive(), indexes);
            } else {
                try (InputStream contentStream = entry.getValue().getAsset().openStream()) {
                    JARArchive jarArchive = ShrinkWrap.create(JARArchive.class, entry.getKey().get()).as(ZipImporter.class).importFrom(contentStream).as(JARArchive.class);
                    index(jarArchive, indexes);
                }
            }
        }
    }
}
Also used : Produces(javax.enterprise.inject.Produces) DeploymentScoped(org.wildfly.swarm.spi.runtime.annotations.DeploymentScoped) Logger(org.jboss.logging.Logger) Node(org.jboss.shrinkwrap.api.Node) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) Indexer(org.jboss.jandex.Indexer) ArchivePath(org.jboss.shrinkwrap.api.ArchivePath) ArchivePaths(org.jboss.shrinkwrap.api.ArchivePaths) CompositeIndex(org.jboss.jandex.CompositeIndex) Map(java.util.Map) Index(org.jboss.jandex.Index) DeploymentContext(org.wildfly.swarm.container.runtime.cdi.DeploymentContext) IndexView(org.jboss.jandex.IndexView) ZipImporter(org.jboss.shrinkwrap.api.importer.ZipImporter) ShrinkWrap(org.jboss.shrinkwrap.api.ShrinkWrap) IndexReader(org.jboss.jandex.IndexReader) JARArchive(org.wildfly.swarm.spi.api.JARArchive) IOException(java.io.IOException) Archive(org.jboss.shrinkwrap.api.Archive) List(java.util.List) LibraryContainer(org.jboss.shrinkwrap.api.container.LibraryContainer) ApplicationScoped(javax.enterprise.context.ApplicationScoped) InputStream(java.io.InputStream) ArchiveAsset(org.jboss.shrinkwrap.api.asset.ArchiveAsset) InputStream(java.io.InputStream) Node(org.jboss.shrinkwrap.api.Node) CompositeIndex(org.jboss.jandex.CompositeIndex) Index(org.jboss.jandex.Index) ArchiveAsset(org.jboss.shrinkwrap.api.asset.ArchiveAsset) IOException(java.io.IOException) ArchivePath(org.jboss.shrinkwrap.api.ArchivePath) Indexer(org.jboss.jandex.Indexer) IndexReader(org.jboss.jandex.IndexReader) LibraryContainer(org.jboss.shrinkwrap.api.container.LibraryContainer) JARArchive(org.wildfly.swarm.spi.api.JARArchive) Map(java.util.Map)

Example 7 with IndexView

use of org.jboss.jandex.IndexView in project wildfly by wildfly.

the class OpenAPIModelServiceConfigurator method get.

@Override
public OpenAPI get() {
    OpenApiConfig config = new OpenApiConfigImpl(this.config);
    IndexView indexView = new FilteredIndexView(this.index, config);
    OpenAPIDocumentBuilder builder = new OpenAPIDocumentBuilder();
    builder.config(config);
    Map.Entry<VirtualFile, Format> entry = findStaticFile(this.root);
    if (entry != null) {
        VirtualFile file = entry.getKey();
        Format format = entry.getValue();
        try (OpenApiStaticFile staticFile = new OpenApiStaticFile(file.openStream(), format)) {
            builder.staticFileModel(OpenApiProcessor.modelFromStaticFile(staticFile));
        } catch (IOException e) {
            throw MicroProfileOpenAPILogger.LOGGER.failedToLoadStaticFile(e, file.getPathNameRelativeTo(this.root), this.deploymentName);
        }
    }
    builder.annotationsModel(OpenApiProcessor.modelFromAnnotations(config, AnnotationScanner.class.getClassLoader(), indexView));
    builder.readerModel(OpenApiProcessor.modelFromReader(config, this.module.getClassLoader()));
    builder.filter(OpenApiProcessor.getFilter(config, this.module.getClassLoader()));
    OpenAPI model = builder.build();
    // Generate default title and description based on web metadata
    DescriptionGroupMetaData descriptionMetaData = this.metaData.getDescriptionGroup();
    String displayName = (descriptionMetaData != null) ? descriptionMetaData.getDisplayName() : null;
    String title = (displayName != null) ? displayName : this.deploymentName;
    String description = (descriptionMetaData != null) ? descriptionMetaData.getDescription() : null;
    Info info = model.getInfo();
    // Override SmallRye's default title
    if (info.getTitle().equals(DEFAULT_TITLE)) {
        info.setTitle(title);
    }
    if (info.getDescription() == null) {
        info.setDescription(description);
    }
    Host host = this.host.get();
    List<UndertowListener> listeners = host.getServer().getListeners();
    if (model.getServers() == null) {
        // Generate Server entries if none exist
        String contextPath = this.info.get().getContextPath();
        if (this.config.getOptionalValue(RELATIVE_SERVER_URLS, Boolean.class).orElse(Boolean.TRUE).booleanValue()) {
            model.setServers(Collections.singletonList(OASFactory.createServer().url(contextPath)));
        } else {
            int aliases = host.getAllAliases().size();
            int size = 0;
            for (UndertowListener listener : listeners) {
                size += aliases + listener.getSocketBinding().getClientMappings().size();
            }
            List<Server> servers = new ArrayList<>(size);
            for (UndertowListener listener : listeners) {
                SocketBinding binding = listener.getSocketBinding();
                Set<String> virtualHosts = new TreeSet<>(host.getAllAliases());
                // The name of the host is not a real virtual host (e.g. default-host)
                virtualHosts.remove(host.getName());
                InetAddress address = binding.getAddress();
                // Omit wildcard addresses
                if (!address.isAnyLocalAddress()) {
                    virtualHosts.add(address.getCanonicalHostName());
                }
                for (String virtualHost : virtualHosts) {
                    Server server = createServer(listener.getProtocol(), virtualHost, binding.getPort(), contextPath);
                    if (server != null) {
                        servers.add(server);
                    }
                }
                for (ClientMapping mapping : binding.getClientMappings()) {
                    Server server = createServer(listener.getProtocol(), mapping.getDestinationAddress(), mapping.getDestinationPort(), contextPath);
                    if (server != null) {
                        servers.add(server);
                    }
                }
            }
            model.setServers(servers);
        }
    }
    if (listeners.stream().map(UndertowListener::getProtocol).noneMatch(REQUISITE_LISTENERS::contains)) {
        LOGGER.requiredListenersNotFound(host.getServer().getName(), REQUISITE_LISTENERS);
    }
    return model;
}
Also used : FilteredIndexView(io.smallrye.openapi.runtime.scanner.FilteredIndexView) VirtualFile(org.jboss.vfs.VirtualFile) SocketBinding(org.jboss.as.network.SocketBinding) Server(org.eclipse.microprofile.openapi.models.servers.Server) ArrayList(java.util.ArrayList) Format(io.smallrye.openapi.runtime.io.Format) OpenApiConfig(io.smallrye.openapi.api.OpenApiConfig) TreeSet(java.util.TreeSet) FilteredIndexView(io.smallrye.openapi.runtime.scanner.FilteredIndexView) IndexView(org.jboss.jandex.IndexView) OpenApiStaticFile(io.smallrye.openapi.runtime.OpenApiStaticFile) Host(org.wildfly.extension.undertow.Host) IOException(java.io.IOException) Info(org.eclipse.microprofile.openapi.models.info.Info) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) OpenApiConfigImpl(io.smallrye.openapi.api.OpenApiConfigImpl) ClientMapping(org.jboss.as.network.ClientMapping) DescriptionGroupMetaData(org.jboss.metadata.javaee.spec.DescriptionGroupMetaData) Map(java.util.Map) EnumMap(java.util.EnumMap) AbstractMap(java.util.AbstractMap) OpenAPI(org.eclipse.microprofile.openapi.models.OpenAPI) InetAddress(java.net.InetAddress) UndertowListener(org.wildfly.extension.undertow.UndertowListener)

Example 8 with IndexView

use of org.jboss.jandex.IndexView in project sts4 by spring-projects.

the class JandexIndex method findMatch.

private Optional<Tuple2<File, ClassInfo>> findMatch(DotName fqName) {
    return (baseIndex == null ? Stream.<Optional<Tuple2<File, ClassInfo>>>empty() : Arrays.stream(baseIndex).filter(jandexIndex -> jandexIndex != null).map(jandexIndex -> jandexIndex.findMatch(fqName))).filter(o -> o.isPresent()).findFirst().orElseGet(() -> streamOfIndices().map(e -> {
        IndexView view = e.getT2();
        ClassInfo info = view.getClassByName(fqName);
        return Tuples.of(e.getT1(), Optional.ofNullable(info));
    // return Tuples.of(e.getT1(), Optional.ofNullable(e.getT2().getClassByName(fqName)));
    }).filter(t -> t.getT2().isPresent()).map(e -> Tuples.of(e.getT1(), e.getT2().get())).findFirst());
}
Also used : Arrays(java.util.Arrays) JarIndexer(org.jboss.jandex.JarIndexer) DotName(org.jboss.jandex.DotName) Supplier(com.google.common.base.Supplier) Tuples(reactor.util.function.Tuples) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) IJavadocProvider(org.springframework.ide.vscode.commons.java.IJavadocProvider) FuzzyMatcher(org.springframework.ide.vscode.commons.util.FuzzyMatcher) ClassInfo(org.jboss.jandex.ClassInfo) IMethod(org.springframework.ide.vscode.commons.java.IMethod) Indexer(org.jboss.jandex.Indexer) IField(org.springframework.ide.vscode.commons.java.IField) Map(java.util.Map) Suppliers(com.google.common.base.Suppliers) Schedulers(reactor.core.scheduler.Schedulers) IAnnotation(org.springframework.ide.vscode.commons.java.IAnnotation) IndexView(org.jboss.jandex.IndexView) IndexReader(org.jboss.jandex.IndexReader) Iterator(java.util.Iterator) Log(org.springframework.ide.vscode.commons.util.Log) Predicate(java.util.function.Predicate) IJavadoc(org.springframework.ide.vscode.commons.javadoc.IJavadoc) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) IType(org.springframework.ide.vscode.commons.java.IType) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) InputStream(java.io.InputStream) Tuple2(reactor.util.function.Tuple2) IndexView(org.jboss.jandex.IndexView) ClassInfo(org.jboss.jandex.ClassInfo)

Example 9 with IndexView

use of org.jboss.jandex.IndexView in project core by weld.

the class JandexDiscoveryStrategy method beforeDiscovery.

@Override
protected void beforeDiscovery(Collection<BeanArchiveBuilder> builders) {
    List<IndexView> indexes = new ArrayList<IndexView>();
    for (BeanArchiveBuilder builder : builders) {
        IndexView index = (IndexView) builder.getAttribute(Jandex.INDEX_ATTRIBUTE_NAME);
        if (index != null) {
            indexes.add(index);
        }
    }
    cindex = CompositeIndex.create(indexes);
    beanDefiningAnnotations = buildBeanDefiningAnnotationSet(initialBeanDefiningAnnotations, cindex);
    classFileServices = new JandexClassFileServices(this);
}
Also used : IndexView(org.jboss.jandex.IndexView) ArrayList(java.util.ArrayList) BeanArchiveBuilder(org.jboss.weld.environment.deployment.discovery.BeanArchiveBuilder)

Example 10 with IndexView

use of org.jboss.jandex.IndexView in project hibernate-orm by hibernate.

the class MetadataBuildingProcess method complete.

/**
 * Second step of 2-phase for MetadataSources->Metadata process
 *
 * @param managedResources The token/memento from 1st phase
 * @param options The building options
 *
 * @return Token/memento representing all known users resources (classes, packages, mapping files, etc).
 */
public static MetadataImplementor complete(final ManagedResources managedResources, final BootstrapContext bootstrapContext, final MetadataBuildingOptions options) {
    final InFlightMetadataCollectorImpl metadataCollector = new InFlightMetadataCollectorImpl(bootstrapContext, options);
    handleTypes(bootstrapContext, options);
    final ClassLoaderService classLoaderService = options.getServiceRegistry().getService(ClassLoaderService.class);
    final MetadataBuildingContextRootImpl rootMetadataBuildingContext = new MetadataBuildingContextRootImpl(bootstrapContext, options, metadataCollector);
    for (AttributeConverterInfo converterInfo : managedResources.getAttributeConverterDefinitions()) {
        metadataCollector.addAttributeConverter(converterInfo.toConverterDescriptor(rootMetadataBuildingContext));
    }
    bootstrapContext.getTypeConfiguration().scope(rootMetadataBuildingContext);
    final IndexView jandexView = bootstrapContext.getJandexView();
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Set up the processors and start binding
    // NOTE : this becomes even more simplified after we move purely
    // to unified model
    final MetadataSourceProcessor processor = new MetadataSourceProcessor() {

        private final HbmMetadataSourceProcessorImpl hbmProcessor = new HbmMetadataSourceProcessorImpl(managedResources, rootMetadataBuildingContext);

        private final AnnotationMetadataSourceProcessorImpl annotationProcessor = new AnnotationMetadataSourceProcessorImpl(managedResources, rootMetadataBuildingContext, jandexView);

        @Override
        public void prepare() {
            hbmProcessor.prepare();
            annotationProcessor.prepare();
        }

        @Override
        public void processTypeDefinitions() {
            hbmProcessor.processTypeDefinitions();
            annotationProcessor.processTypeDefinitions();
        }

        @Override
        public void processQueryRenames() {
            hbmProcessor.processQueryRenames();
            annotationProcessor.processQueryRenames();
        }

        @Override
        public void processNamedQueries() {
            hbmProcessor.processNamedQueries();
            annotationProcessor.processNamedQueries();
        }

        @Override
        public void processAuxiliaryDatabaseObjectDefinitions() {
            hbmProcessor.processAuxiliaryDatabaseObjectDefinitions();
            annotationProcessor.processAuxiliaryDatabaseObjectDefinitions();
        }

        @Override
        public void processIdentifierGenerators() {
            hbmProcessor.processIdentifierGenerators();
            annotationProcessor.processIdentifierGenerators();
        }

        @Override
        public void processFilterDefinitions() {
            hbmProcessor.processFilterDefinitions();
            annotationProcessor.processFilterDefinitions();
        }

        @Override
        public void processFetchProfiles() {
            hbmProcessor.processFetchProfiles();
            annotationProcessor.processFetchProfiles();
        }

        @Override
        public void prepareForEntityHierarchyProcessing() {
            for (MetadataSourceType metadataSourceType : options.getSourceProcessOrdering()) {
                if (metadataSourceType == MetadataSourceType.HBM) {
                    hbmProcessor.prepareForEntityHierarchyProcessing();
                }
                if (metadataSourceType == MetadataSourceType.CLASS) {
                    annotationProcessor.prepareForEntityHierarchyProcessing();
                }
            }
        }

        @Override
        public void processEntityHierarchies(Set<String> processedEntityNames) {
            for (MetadataSourceType metadataSourceType : options.getSourceProcessOrdering()) {
                if (metadataSourceType == MetadataSourceType.HBM) {
                    hbmProcessor.processEntityHierarchies(processedEntityNames);
                }
                if (metadataSourceType == MetadataSourceType.CLASS) {
                    annotationProcessor.processEntityHierarchies(processedEntityNames);
                }
            }
        }

        @Override
        public void postProcessEntityHierarchies() {
            for (MetadataSourceType metadataSourceType : options.getSourceProcessOrdering()) {
                if (metadataSourceType == MetadataSourceType.HBM) {
                    hbmProcessor.postProcessEntityHierarchies();
                }
                if (metadataSourceType == MetadataSourceType.CLASS) {
                    annotationProcessor.postProcessEntityHierarchies();
                }
            }
        }

        @Override
        public void processResultSetMappings() {
            hbmProcessor.processResultSetMappings();
            annotationProcessor.processResultSetMappings();
        }

        @Override
        public void finishUp() {
            hbmProcessor.finishUp();
            annotationProcessor.finishUp();
        }
    };
    processor.prepare();
    processor.processTypeDefinitions();
    processor.processQueryRenames();
    processor.processAuxiliaryDatabaseObjectDefinitions();
    processor.processIdentifierGenerators();
    processor.processFilterDefinitions();
    processor.processFetchProfiles();
    final Set<String> processedEntityNames = new HashSet<>();
    processor.prepareForEntityHierarchyProcessing();
    processor.processEntityHierarchies(processedEntityNames);
    processor.postProcessEntityHierarchies();
    processor.processResultSetMappings();
    processor.processNamedQueries();
    processor.finishUp();
    for (MetadataContributor contributor : classLoaderService.loadJavaServices(MetadataContributor.class)) {
        log.tracef("Calling MetadataContributor : %s", contributor);
        contributor.contribute(metadataCollector, jandexView);
    }
    metadataCollector.processSecondPasses(rootMetadataBuildingContext);
    Iterable<AdditionalJaxbMappingProducer> producers = classLoaderService.loadJavaServices(AdditionalJaxbMappingProducer.class);
    if (producers != null) {
        final EntityHierarchyBuilder hierarchyBuilder = new EntityHierarchyBuilder();
        // final MappingBinder mappingBinder = new MappingBinder( true );
        // We need to disable validation here.  It seems Envers is not producing valid (according to schema) XML
        final MappingBinder mappingBinder = new MappingBinder(classLoaderService, false);
        for (AdditionalJaxbMappingProducer producer : producers) {
            log.tracef("Calling AdditionalJaxbMappingProducer : %s", producer);
            Collection<MappingDocument> additionalMappings = producer.produceAdditionalMappings(metadataCollector, jandexView, mappingBinder, rootMetadataBuildingContext);
            for (MappingDocument mappingDocument : additionalMappings) {
                hierarchyBuilder.indexMappingDocument(mappingDocument);
            }
        }
        ModelBinder binder = ModelBinder.prepare(rootMetadataBuildingContext);
        for (EntityHierarchySourceImpl entityHierarchySource : hierarchyBuilder.buildHierarchies()) {
            binder.bindEntityHierarchy(entityHierarchySource);
        }
    }
    return metadataCollector.buildMetadataInstance(rootMetadataBuildingContext);
}
Also used : MetadataSourceProcessor(org.hibernate.boot.model.source.spi.MetadataSourceProcessor) EntityHierarchySourceImpl(org.hibernate.boot.model.source.internal.hbm.EntityHierarchySourceImpl) HashSet(java.util.HashSet) Set(java.util.Set) AttributeConverterInfo(org.hibernate.boot.AttributeConverterInfo) IndexView(org.jboss.jandex.IndexView) MetadataContributor(org.hibernate.boot.spi.MetadataContributor) MappingDocument(org.hibernate.boot.model.source.internal.hbm.MappingDocument) MetadataSourceType(org.hibernate.cfg.MetadataSourceType) AdditionalJaxbMappingProducer(org.hibernate.boot.spi.AdditionalJaxbMappingProducer) EntityHierarchyBuilder(org.hibernate.boot.model.source.internal.hbm.EntityHierarchyBuilder) AnnotationMetadataSourceProcessorImpl(org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl) MappingBinder(org.hibernate.boot.jaxb.internal.MappingBinder) HbmMetadataSourceProcessorImpl(org.hibernate.boot.model.source.internal.hbm.HbmMetadataSourceProcessorImpl) InFlightMetadataCollectorImpl(org.hibernate.boot.internal.InFlightMetadataCollectorImpl) MetadataBuildingContextRootImpl(org.hibernate.boot.internal.MetadataBuildingContextRootImpl) ModelBinder(org.hibernate.boot.model.source.internal.hbm.ModelBinder) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) HashSet(java.util.HashSet)

Aggregations

IndexView (org.jboss.jandex.IndexView)11 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Map (java.util.Map)4 InputStream (java.io.InputStream)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 ClassInfo (org.jboss.jandex.ClassInfo)3 Supplier (com.google.common.base.Supplier)2 Suppliers (com.google.common.base.Suppliers)2 Cache (com.google.common.cache.Cache)2 CacheBuilder (com.google.common.cache.CacheBuilder)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Iterator (java.util.Iterator)2 Optional (java.util.Optional)2 Set (java.util.Set)2