Search in sources :

Example 36 with ClassLoaderService

use of org.hibernate.boot.registry.classloading.spi.ClassLoaderService in project hibernate-orm by hibernate.

the class MultiTenantConnectionProviderInitiator method initiateService.

@Override
@SuppressWarnings({ "unchecked" })
public MultiTenantConnectionProvider initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
    final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy(configurationValues);
    if (!strategy.requiresMultiTenantConnectionProvider()) {
        // nothing to do, but given the separate hierarchies have to handle this here.
        return null;
    }
    final Object configValue = configurationValues.get(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER);
    if (configValue == null) {
        // if they also specified the data source *name*, then lets assume they want
        // DataSourceBasedMultiTenantConnectionProviderImpl
        final Object dataSourceConfigValue = configurationValues.get(AvailableSettings.DATASOURCE);
        if (dataSourceConfigValue != null && String.class.isInstance(dataSourceConfigValue)) {
            return new DataSourceBasedMultiTenantConnectionProviderImpl();
        }
        return null;
    }
    if (MultiTenantConnectionProvider.class.isInstance(configValue)) {
        return (MultiTenantConnectionProvider) configValue;
    } else {
        final Class<MultiTenantConnectionProvider> implClass;
        if (Class.class.isInstance(configValue)) {
            implClass = (Class) configValue;
        } else {
            final String className = configValue.toString();
            final ClassLoaderService classLoaderService = registry.getService(ClassLoaderService.class);
            try {
                implClass = classLoaderService.classForName(className);
            } catch (ClassLoadingException cle) {
                log.warn("Unable to locate specified class [" + className + "]", cle);
                throw new ServiceException("Unable to locate specified multi-tenant connection provider [" + className + "]");
            }
        }
        try {
            return implClass.newInstance();
        } catch (Exception e) {
            log.warn("Unable to instantiate specified class [" + implClass.getName() + "]", e);
            throw new ServiceException("Unable to instantiate specified multi-tenant connection provider [" + implClass.getName() + "]");
        }
    }
}
Also used : MultiTenancyStrategy(org.hibernate.MultiTenancyStrategy) ServiceException(org.hibernate.service.spi.ServiceException) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) MultiTenantConnectionProvider(org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider) DataSourceBasedMultiTenantConnectionProviderImpl(org.hibernate.engine.jdbc.connections.spi.DataSourceBasedMultiTenantConnectionProviderImpl) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) ServiceException(org.hibernate.service.spi.ServiceException) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService)

Example 37 with ClassLoaderService

use of org.hibernate.boot.registry.classloading.spi.ClassLoaderService in project hibernate-orm by hibernate.

the class SimpleValue method setTypeName.

public void setTypeName(String typeName) {
    if (typeName != null && typeName.startsWith(AttributeConverterTypeAdapter.NAME_PREFIX)) {
        final String converterClassName = typeName.substring(AttributeConverterTypeAdapter.NAME_PREFIX.length());
        final ClassLoaderService cls = getMetadata().getMetadataBuildingOptions().getServiceRegistry().getService(ClassLoaderService.class);
        try {
            final Class<? extends AttributeConverter> converterClass = cls.classForName(converterClassName);
            this.attributeConverterDescriptor = new ClassBasedConverterDescriptor(converterClass, false, ((InFlightMetadataCollector) getMetadata()).getClassmateContext());
            return;
        } catch (Exception e) {
            log.logBadHbmAttributeConverterType(typeName, e.getMessage());
        }
    }
    this.typeName = typeName;
}
Also used : InFlightMetadataCollector(org.hibernate.boot.spi.InFlightMetadataCollector) ClassBasedConverterDescriptor(org.hibernate.boot.model.convert.internal.ClassBasedConverterDescriptor) MappingException(org.hibernate.MappingException) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService)

Example 38 with ClassLoaderService

use of org.hibernate.boot.registry.classloading.spi.ClassLoaderService in project hibernate-orm by hibernate.

the class MetadataBuildingProcess method handleTypes.

// todo (7.0) : buildJandexInitializer
// private static JandexInitManager buildJandexInitializer(
// MetadataBuildingOptions options,
// ClassLoaderAccess classLoaderAccess) {
// final boolean autoIndexMembers = ConfigurationHelper.getBoolean(
// org.hibernate.cfg.AvailableSettings.ENABLE_AUTO_INDEX_MEMBER_TYPES,
// options.getServiceRegistry().getService( ConfigurationService.class ).getSettings(),
// false
// );
// 
// return new JandexInitManager( options.getJandexView(), classLoaderAccess, autoIndexMembers );
// }
private static void handleTypes(BootstrapContext bootstrapContext, MetadataBuildingOptions options) {
    final ClassLoaderService classLoaderService = options.getServiceRegistry().getService(ClassLoaderService.class);
    final TypeContributions typeContributions = new TypeContributions() {

        @Override
        public void contributeType(org.hibernate.type.BasicType type) {
            getBasicTypeRegistry().register(type);
        }

        @Override
        public void contributeType(BasicType type, String... keys) {
            getBasicTypeRegistry().register(type, keys);
        }

        @Override
        public void contributeType(UserType type, String[] keys) {
            getBasicTypeRegistry().register(type, keys);
        }

        @Override
        public void contributeType(CompositeUserType type, String[] keys) {
            getBasicTypeRegistry().register(type, keys);
        }

        @Override
        public void contributeJavaTypeDescriptor(JavaTypeDescriptor descriptor) {
            bootstrapContext.getTypeConfiguration().getJavaTypeDescriptorRegistry().addDescriptor(descriptor);
        }

        @Override
        public void contributeSqlTypeDescriptor(SqlTypeDescriptor descriptor) {
            bootstrapContext.getTypeConfiguration().getSqlTypeDescriptorRegistry().addDescriptor(descriptor);
        }

        @Override
        public TypeConfiguration getTypeConfiguration() {
            return bootstrapContext.getTypeConfiguration();
        }

        final BasicTypeRegistry getBasicTypeRegistry() {
            return bootstrapContext.getTypeConfiguration().getBasicTypeRegistry();
        }
    };
    // add Dialect contributed types
    final Dialect dialect = options.getServiceRegistry().getService(JdbcServices.class).getDialect();
    dialect.contributeTypes(typeContributions, options.getServiceRegistry());
    // add TypeContributor contributed types.
    for (TypeContributor contributor : classLoaderService.loadJavaServices(TypeContributor.class)) {
        contributor.contribute(typeContributions, options.getServiceRegistry());
    }
    // add explicit application registered types
    for (BasicTypeRegistration basicTypeRegistration : options.getBasicTypeRegistrations()) {
        bootstrapContext.getTypeConfiguration().getBasicTypeRegistry().register(basicTypeRegistration.getBasicType(), basicTypeRegistration.getRegistrationKeys());
    }
}
Also used : BasicType(org.hibernate.type.BasicType) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) BasicTypeRegistration(org.hibernate.boot.spi.BasicTypeRegistration) JavaTypeDescriptor(org.hibernate.type.descriptor.java.JavaTypeDescriptor) TypeContributor(org.hibernate.boot.model.TypeContributor) SqlTypeDescriptor(org.hibernate.type.descriptor.sql.SqlTypeDescriptor) TypeContributions(org.hibernate.boot.model.TypeContributions) Dialect(org.hibernate.dialect.Dialect) CompositeUserType(org.hibernate.usertype.CompositeUserType) UserType(org.hibernate.usertype.UserType) CompositeUserType(org.hibernate.usertype.CompositeUserType) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService)

Example 39 with ClassLoaderService

use of org.hibernate.boot.registry.classloading.spi.ClassLoaderService 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)

Example 40 with ClassLoaderService

use of org.hibernate.boot.registry.classloading.spi.ClassLoaderService in project hibernate-orm by hibernate.

the class ScanningCoordinator method applyScanResultsToManagedResources.

public void applyScanResultsToManagedResources(ManagedResourcesImpl managedResources, ScanResult scanResult, BootstrapContext bootstrapContext, XmlMappingBinderAccess xmlMappingBinderAccess) {
    final ScanEnvironment scanEnvironment = bootstrapContext.getScanEnvironment();
    final ServiceRegistry serviceRegistry = bootstrapContext.getServiceRegistry();
    final ClassLoaderService classLoaderService = serviceRegistry.getService(ClassLoaderService.class);
    // mapping files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final Set<String> nonLocatedMappingFileNames = new HashSet<String>();
    final List<String> explicitMappingFileNames = scanEnvironment.getExplicitlyListedMappingFiles();
    if (explicitMappingFileNames != null) {
        nonLocatedMappingFileNames.addAll(explicitMappingFileNames);
    }
    for (MappingFileDescriptor mappingFileDescriptor : scanResult.getLocatedMappingFiles()) {
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(mappingFileDescriptor.getStreamAccess()));
        nonLocatedMappingFileNames.remove(mappingFileDescriptor.getName());
    }
    for (String name : nonLocatedMappingFileNames) {
        final URL url = classLoaderService.locateResource(name);
        if (url == null) {
            throw new MappingException("Unable to resolve explicitly named mapping-file : " + name, new Origin(SourceType.RESOURCE, name));
        }
        final UrlInputStreamAccess inputStreamAccess = new UrlInputStreamAccess(url);
        managedResources.addXmlBinding(xmlMappingBinderAccess.bind(inputStreamAccess));
    }
    // classes and packages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    final List<String> unresolvedListedClassNames = scanEnvironment.getExplicitlyListedClassNames() == null ? new ArrayList<String>() : new ArrayList<String>(scanEnvironment.getExplicitlyListedClassNames());
    for (ClassDescriptor classDescriptor : scanResult.getLocatedClasses()) {
        if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.CONVERTER) {
            // converter classes are safe to load because we never enhance them,
            // and notice we use the ClassLoaderService specifically, not the temp ClassLoader (if any)
            managedResources.addAttributeConverterDefinition(AttributeConverterDefinition.from(classLoaderService.<AttributeConverter>classForName(classDescriptor.getName())));
        } else if (classDescriptor.getCategorization() == ClassDescriptor.Categorization.MODEL) {
            managedResources.addAnnotatedClassName(classDescriptor.getName());
        }
        unresolvedListedClassNames.remove(classDescriptor.getName());
    }
    // IMPL NOTE : "explicitlyListedClassNames" can contain class or package names...
    for (PackageDescriptor packageDescriptor : scanResult.getLocatedPackages()) {
        managedResources.addAnnotatedPackageName(packageDescriptor.getName());
        unresolvedListedClassNames.remove(packageDescriptor.getName());
    }
    for (String unresolvedListedClassName : unresolvedListedClassNames) {
        // because the explicit list can contain either class names or package names
        // we need to check for both here...
        // First, try it as a class name
        final String classFileName = unresolvedListedClassName.replace('.', '/') + ".class";
        final URL classFileUrl = classLoaderService.locateResource(classFileName);
        if (classFileUrl != null) {
            managedResources.addAnnotatedClassName(unresolvedListedClassName);
            continue;
        }
        // Then, try it as a package name
        final String packageInfoFileName = unresolvedListedClassName.replace('.', '/') + "/package-info.class";
        final URL packageInfoFileUrl = classLoaderService.locateResource(packageInfoFileName);
        if (packageInfoFileUrl != null) {
            managedResources.addAnnotatedPackageName(unresolvedListedClassName);
            continue;
        }
        log.debugf("Unable to resolve class [%s] named in persistence unit [%s]", unresolvedListedClassName, scanEnvironment.getRootUrl());
    }
}
Also used : Origin(org.hibernate.boot.jaxb.Origin) MappingFileDescriptor(org.hibernate.boot.archive.scan.spi.MappingFileDescriptor) ClassDescriptor(org.hibernate.boot.archive.scan.spi.ClassDescriptor) UrlInputStreamAccess(org.hibernate.boot.archive.internal.UrlInputStreamAccess) PackageDescriptor(org.hibernate.boot.archive.scan.spi.PackageDescriptor) URL(java.net.URL) MappingException(org.hibernate.boot.MappingException) AttributeConverter(javax.persistence.AttributeConverter) ScanEnvironment(org.hibernate.boot.archive.scan.spi.ScanEnvironment) ServiceRegistry(org.hibernate.service.ServiceRegistry) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) HashSet(java.util.HashSet)

Aggregations

ClassLoaderService (org.hibernate.boot.registry.classloading.spi.ClassLoaderService)43 HibernateException (org.hibernate.HibernateException)9 ClassLoaderAccessImpl (org.hibernate.boot.internal.ClassLoaderAccessImpl)9 ClassLoaderAccess (org.hibernate.boot.spi.ClassLoaderAccess)9 InFlightMetadataCollectorImpl (org.hibernate.boot.internal.InFlightMetadataCollectorImpl)8 MetadataBuildingContextRootImpl (org.hibernate.boot.internal.MetadataBuildingContextRootImpl)8 StandardServiceRegistryBuilder (org.hibernate.boot.registry.StandardServiceRegistryBuilder)8 MetadataSources (org.hibernate.boot.MetadataSources)7 InFlightMetadataCollector (org.hibernate.boot.spi.InFlightMetadataCollector)7 TypeResolver (org.hibernate.type.TypeResolver)7 MappingException (org.hibernate.MappingException)6 MetadataBuildingOptionsImpl (org.hibernate.boot.internal.MetadataBuilderImpl.MetadataBuildingOptionsImpl)6 StandardServiceRegistry (org.hibernate.boot.registry.StandardServiceRegistry)6 ClassLoadingException (org.hibernate.boot.registry.classloading.spi.ClassLoadingException)6 MetadataBuildingContext (org.hibernate.boot.spi.MetadataBuildingContext)6 HashSet (java.util.HashSet)5 MetadataImplementor (org.hibernate.boot.spi.MetadataImplementor)4 ConfigurationService (org.hibernate.engine.config.spi.ConfigurationService)4 ServiceRegistry (org.hibernate.service.ServiceRegistry)4 Set (java.util.Set)3