下面列出了怎么用org.hibernate.boot.registry.classloading.spi.ClassLoaderService的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Builds the selector.
*
* @param classLoaderService The class loading service used to (attempt to) resolve any un-registered
* strategy implementations.
*
* @return The selector.
*/
public static StrategySelector buildSelector(ClassLoaderService classLoaderService) {
final StrategySelectorImpl strategySelector = new StrategySelectorImpl(classLoaderService);
// build the baseline...
strategySelector.registerStrategyLazily(Dialect.class, new DefaultDialectSelector());
strategySelector.registerStrategyLazily(JtaPlatform.class, new DefaultJtaPlatformSelector());
addTransactionCoordinatorBuilders(strategySelector);
addMultiTableBulkIdStrategies(strategySelector);
addImplicitNamingStrategies(strategySelector);
addCacheKeysFactories(strategySelector);
// Required to support well known extensions e.g. Envers
// TODO: should we introduce a new integrator SPI to limit these to extensions supported by Quarkus?
for (StrategyRegistrationProvider provider : classLoaderService.loadJavaServices(StrategyRegistrationProvider.class)) {
for (StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations()) {
applyFromStrategyRegistration(strategySelector, discoveredStrategyRegistration);
}
}
return strategySelector;
}
public LoadedConfig loadConfigXmlResource(String cfgXmlResourceName) {
final InputStream stream = bootstrapServiceRegistry.getService( ClassLoaderService.class ).locateResourceStream( cfgXmlResourceName );
if ( stream == null ) {
throw new ConfigurationException( "Could not locate cfg.xml resource [" + cfgXmlResourceName + "]" );
}
try {
final JaxbCfgHibernateConfiguration jaxbCfg = jaxbProcessorHolder.getValue().unmarshal(
stream,
new Origin( SourceType.RESOURCE, cfgXmlResourceName )
);
return LoadedConfig.consume( jaxbCfg );
}
finally {
try {
stream.close();
}
catch (IOException e) {
log.debug( "Unable to close cfg.xml resource stream", e );
}
}
}
@SuppressWarnings({"unchecked", "UnusedParameters"})
private static void applyRelationalConstraints(ValidatorFactory factory, ActivationContext activationContext) {
final ConfigurationService cfgService = activationContext.getServiceRegistry().getService( ConfigurationService.class );
if ( !cfgService.getSetting( BeanValidationIntegrator.APPLY_CONSTRAINTS, StandardConverters.BOOLEAN, true ) ) {
LOG.debug( "Skipping application of relational constraints from legacy Hibernate Validator" );
return;
}
final Set<ValidationMode> modes = activationContext.getValidationModes();
if ( ! ( modes.contains( ValidationMode.DDL ) || modes.contains( ValidationMode.AUTO ) ) ) {
return;
}
applyRelationalConstraints(
factory,
activationContext.getMetadata().getEntityBindings(),
cfgService.getSettings(),
activationContext.getServiceRegistry().getService( JdbcServices.class ).getDialect(),
new ClassLoaderAccessImpl(
null,
activationContext.getServiceRegistry().getService( ClassLoaderService.class )
)
);
}
/**
* @deprecated Use {@link JPAMetadataProvider#JPAMetadataProvider(BootstrapContext)} instead.
*/
@Deprecated
public JPAMetadataProvider(final MetadataBuildingOptions metadataBuildingOptions) {
this( new ClassLoaderAccessDelegateImpl() {
ClassLoaderAccess delegate;
@Override
protected ClassLoaderAccess getDelegate() {
if ( delegate == null ) {
delegate = new ClassLoaderAccessImpl(
metadataBuildingOptions.getTempClassLoader(),
metadataBuildingOptions.getServiceRegistry().getService( ClassLoaderService.class )
);
}
return delegate;
}
} );
}
public Class getElementClass() throws MappingException {
if ( elementClassName == null ) {
org.hibernate.type.Type elementType = getElement().getType();
return isPrimitiveArray()
? ( (PrimitiveType) elementType ).getPrimitiveClass()
: elementType.getReturnedClass();
}
else {
try {
return getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class )
.classForName( elementClassName );
}
catch (ClassLoadingException e) {
throw new MappingException( e );
}
}
}
public Comparator getComparator() {
if ( comparator == null && comparatorClassName != null ) {
try {
final ClassLoaderService classLoaderService = getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class );
setComparator( (Comparator) classLoaderService.classForName( comparatorClassName ).newInstance() );
}
catch (Exception e) {
throw new MappingException(
"Could not instantiate comparator class [" + comparatorClassName
+ "] for collection " + getRole()
);
}
}
return comparator;
}
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;
}
@Override
public String[] getImplementors(String className) throws MappingException {
// computeIfAbsent() can be a contention point and we expect all the values to be in the map at some point so
// let's do an optimistic check first
String[] implementors = implementorsCache.get( className );
if ( implementors != null ) {
return Arrays.copyOf( implementors, implementors.length );
}
try {
final Class<?> clazz = getSessionFactory().getServiceRegistry().getService( ClassLoaderService.class ).classForName( className );
implementors = doGetImplementors( clazz );
if ( implementors.length > 0 ) {
implementorsCache.putIfAbsent( className, implementors );
return Arrays.copyOf( implementors, implementors.length );
}
else {
return EMPTY_IMPLEMENTORS;
}
}
catch (ClassLoadingException e) {
return new String[]{ className }; // we don't cache anything for dynamic classes
}
}
public static TargetDescriptor buildTargetDescriptor(
EnumSet<TargetType> targetTypes,
String outputFile,
ServiceRegistry serviceRegistry) {
final ScriptTargetOutput scriptTarget;
if ( targetTypes.contains( TargetType.SCRIPT ) ) {
if ( outputFile == null ) {
throw new SchemaManagementException( "Writing to script was requested, but no script file was specified" );
}
scriptTarget = Helper.interpretScriptTargetSetting(
outputFile,
serviceRegistry.getService( ClassLoaderService.class ),
(String) serviceRegistry.getService( ConfigurationService.class ).getSettings().get( AvailableSettings.HBM2DDL_CHARSET_NAME )
);
}
else {
scriptTarget = null;
}
return new TargetDescriptorImpl( targetTypes, scriptTarget );
}
private ScriptSourceInput interpretLegacyImportScriptSetting(
String resourceName,
ClassLoaderService classLoaderService,
String charsetName) {
try {
final URL resourceUrl = classLoaderService.locateResource( resourceName );
if ( resourceUrl == null ) {
return ScriptSourceInputNonExistentImpl.INSTANCE;
}
else {
return new ScriptSourceInputFromUrl( resourceUrl, charsetName );
}
}
catch (Exception e) {
throw new SchemaManagementException( "Error resolving legacy import resource : " + resourceName, e );
}
}
@Override
protected TransactionManager locateTransactionManager() {
//Try WildFly first as it's the "new generation":
try {
return wildflyBasedAlternative.locateTransactionManager();
}
catch ( Exception ignore) {
// ignore and look for Arjuna class
}
try {
final Class jbossTmClass = serviceRegistry()
.getService( ClassLoaderService.class )
.classForName( JBOSS_TM_CLASS_NAME );
return (TransactionManager) jbossTmClass.getMethod( "transactionManager" ).invoke( null );
}
catch ( Exception e ) {
throw new JtaPlatformException( "Could not obtain JBoss Transactions transaction manager instance", e );
}
}
@Override
protected UserTransaction locateUserTransaction() {
//Try WildFly first as it's the "new generation":
try {
return wildflyBasedAlternative.locateUserTransaction();
}
catch ( Exception ignore) {
// ignore and look for Arjuna class
}
try {
final Class jbossUtClass = serviceRegistry()
.getService( ClassLoaderService.class )
.classForName( JBOSS_UT_CLASS_NAME );
return (UserTransaction) jbossUtClass.getMethod( "userTransaction" ).invoke( null );
}
catch ( Exception e ) {
throw new JtaPlatformException( "Could not obtain JBoss Transactions user transaction instance", e );
}
}
private Driver loadDriverIfPossible(String driverClassName) {
if ( driverClassName == null ) {
log.debug( "No driver class specified" );
return null;
}
if ( serviceRegistry != null ) {
final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
final Class<Driver> driverClass = classLoaderService.classForName( driverClassName );
try {
return driverClass.newInstance();
}
catch ( Exception e ) {
throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e );
}
}
try {
return (Driver) Class.forName( driverClassName ).newInstance();
}
catch ( Exception e1 ) {
throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e1 );
}
}
@Override
public BatchBuilder initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
final Object builder = configurationValues.get( BUILDER );
if ( builder == null ) {
return new BatchBuilderImpl(
ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, 1 )
);
}
if ( BatchBuilder.class.isInstance( builder ) ) {
return (BatchBuilder) builder;
}
final String builderClassName = builder.toString();
try {
return (BatchBuilder) registry.getService( ClassLoaderService.class ).classForName( builderClassName ).newInstance();
}
catch (Exception e) {
throw new ServiceException( "Could not build explicit BatchBuilder [" + builderClassName + "]", e );
}
}
@Override
public Class getIdentifierGeneratorClass(String strategy) {
if ( "hilo".equals( strategy ) ) {
throw new UnsupportedOperationException( "Support for 'hilo' generator has been removed" );
}
String resolvedStrategy = "native".equals( strategy ) ?
getDialect().getNativeIdentifierGeneratorStrategy() : strategy;
Class generatorClass = generatorStrategyToClassNameMap.get( resolvedStrategy );
try {
if ( generatorClass == null ) {
final ClassLoaderService cls = serviceRegistry.getService( ClassLoaderService.class );
generatorClass = cls.classForName( resolvedStrategy );
}
}
catch ( ClassLoadingException e ) {
throw new MappingException( String.format( "Could not interpret id generator strategy [%s]", strategy ) );
}
return generatorClass;
}
public XMLHelper(ClassLoaderService classLoaderService) {
this.documentFactory = classLoaderService.workWithClassLoader(
new ClassLoaderService.Work<DocumentFactory>() {
@Override
public DocumentFactory doWork(ClassLoader classLoader) {
final ClassLoader originalTccl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader( classLoader );
return DocumentFactory.getInstance();
}
finally {
Thread.currentThread().setContextClassLoader( originalTccl );
}
}
}
);
}
private void prepareEventListeners(MetadataImplementor metadata) {
final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
final ConfigurationService cfgService = serviceRegistry.getService( ConfigurationService.class );
final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
eventListenerRegistry.prepare( metadata );
for ( Map.Entry entry : ( (Map<?, ?>) cfgService.getSettings() ).entrySet() ) {
if ( !String.class.isInstance( entry.getKey() ) ) {
continue;
}
final String propertyName = (String) entry.getKey();
if ( !propertyName.startsWith( org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX ) ) {
continue;
}
final String eventTypeName = propertyName.substring(
org.hibernate.jpa.AvailableSettings.EVENT_LISTENER_PREFIX.length() + 1
);
final EventType eventType = EventType.resolveEventTypeByName( eventTypeName );
final EventListenerGroup eventListenerGroup = eventListenerRegistry.getEventListenerGroup( eventType );
for ( String listenerImpl : ( (String) entry.getValue() ).split( " ," ) ) {
eventListenerGroup.appendListener( instantiate( listenerImpl, classLoaderService ) );
}
}
}
/**
* Constructs a BootstrapServiceRegistryImpl.
*
* Do not use directly generally speaking. Use {@link org.hibernate.boot.registry.BootstrapServiceRegistryBuilder}
* instead.
*
* @param autoCloseRegistry See discussion on
* {@link org.hibernate.boot.registry.BootstrapServiceRegistryBuilder#disableAutoClose}
* @param classLoaderService The ClassLoaderService to use
* @param providedIntegrators The group of explicitly provided integrators
*
* @see org.hibernate.boot.registry.BootstrapServiceRegistryBuilder
*/
public BootstrapServiceRegistryImpl(
boolean autoCloseRegistry,
ClassLoaderService classLoaderService,
LinkedHashSet<Integrator> providedIntegrators) {
this.autoCloseRegistry = autoCloseRegistry;
this.classLoaderServiceBinding = new ServiceBinding<ClassLoaderService>(
this,
ClassLoaderService.class,
classLoaderService
);
final StrategySelectorImpl strategySelector = new StrategySelectorImpl( classLoaderService );
this.strategySelectorBinding = new ServiceBinding<StrategySelector>(
this,
StrategySelector.class,
strategySelector
);
this.integratorServiceBinding = new ServiceBinding<IntegratorService>(
this,
IntegratorService.class,
new IntegratorServiceImpl( providedIntegrators, classLoaderService )
);
}
/**
* Initialize the internal values from the given {@link Map}.
*
* @param configurationMap The values to use as configuration
*/
public void initialize(Map configurationMap, ClassLoaderService classLoaderService) {
ConfigurationPropertyReader configurationPropertyReader = new ConfigurationPropertyReader( configurationMap, classLoaderService );
this.url = configurationPropertyReader
.property( IgniteProperties.CONFIGURATION_RESOURCE_NAME, URL.class )
.withDefault( IgniteProviderConfiguration.class.getClassLoader().getResource( DEFAULT_CONFIG ) )
.getValue();
String configBuilderClassName = configurationPropertyReader
.property( IgniteProperties.CONFIGURATION_CLASS_NAME, String.class )
.getValue();
if ( configBuilderClassName != null ) {
this.configBuilder = configurationPropertyReader
.property( IgniteProperties.CONFIGURATION_CLASS_NAME, IgniteConfigurationBuilder.class )
.instantiate()
.getValue();
}
this.instanceName = configurationPropertyReader
.property( IgniteProperties.IGNITE_INSTANCE_NAME, String.class )
.getValue();
}
public void coordinateScan(
ManagedResourcesImpl managedResources,
BootstrapContext bootstrapContext,
XmlMappingBinderAccess xmlMappingBinderAccess) {
if ( bootstrapContext.getScanEnvironment() == null ) {
return;
}
final ClassLoaderService classLoaderService = bootstrapContext.getServiceRegistry().getService( ClassLoaderService.class );
final ClassLoaderAccess classLoaderAccess = new ClassLoaderAccessImpl(
bootstrapContext.getJpaTempClassLoader(),
classLoaderService
);
// NOTE : the idea with JandexInitializer/JandexInitManager was to allow adding classes
// to the index as we discovered them via scanning and . Currently
final Scanner scanner = buildScanner( bootstrapContext, classLoaderAccess );
final ScanResult scanResult = scanner.scan(
bootstrapContext.getScanEnvironment(),
bootstrapContext.getScanOptions(),
StandardScanParameters.INSTANCE
);
applyScanResultsToManagedResources( managedResources, scanResult, bootstrapContext, xmlMappingBinderAccess );
}
@Override
public void contribute(InFlightMetadataCollector metadataCollector, IndexView jandexIndex) {
MetadataBuildingOptions options = metadataCollector.getMetadataBuildingOptions();
ClassLoaderService classLoaderService = options.getServiceRegistry().getService(ClassLoaderService.class);
this.metadataBuildingContext = new MetadataBuildingContextRootImpl(
metadataCollector.getBootstrapContext(),
options,
metadataCollector
);
java.util.Collection<PersistentEntity> persistentEntities = hibernateMappingContext.getPersistentEntities();
for (PersistentEntity persistentEntity : persistentEntities) {
if(!persistentEntity.getJavaClass().isAnnotationPresent(Entity.class)) {
if(ConnectionSourcesSupport.usesConnectionSource(persistentEntity, dataSourceName) && persistentEntity.isRoot()) {
bindRoot((HibernatePersistentEntity) persistentEntity, metadataCollector, sessionFactoryName);
}
}
}
}
private CacheManager useExplicitCacheManager(SessionFactoryOptions settings, Object setting) {
if (setting instanceof CacheManager) {
return (CacheManager) setting;
}
final Class<? extends CacheManager> cacheManagerClass;
if (setting instanceof Class) {
cacheManagerClass = (Class<? extends CacheManager>) setting;
} else {
cacheManagerClass = settings.getServiceRegistry().getService(ClassLoaderService.class).classForName(setting.toString());
}
try {
return cacheManagerClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new CacheException("Could not use explicit CacheManager : " + setting);
}
}
private void applyServiceContributors() {
final Iterable<ServiceContributor> serviceContributors =
bootstrapServiceRegistry.getService( ClassLoaderService.class )
.loadJavaServices( ServiceContributor.class );
for ( ServiceContributor serviceContributor : serviceContributors ) {
serviceContributor.contribute( this );
}
}
/**
* Builds the selector.
*
* @param classLoaderService The class loading service used to (attempt to) resolve any un-registered
* strategy implementations.
*
* @return The selector.
*/
public StrategySelector buildSelector(ClassLoaderService classLoaderService) {
final StrategySelectorImpl strategySelector = new StrategySelectorImpl( classLoaderService );
// build the baseline...
addDialects( strategySelector );
addJtaPlatforms( strategySelector );
addTransactionCoordinatorBuilders( strategySelector );
addMultiTableBulkIdStrategies( strategySelector );
addEntityCopyObserverStrategies( strategySelector );
addImplicitNamingStrategies( strategySelector );
addCacheKeysFactories( strategySelector );
// apply auto-discovered registrations
for ( StrategyRegistrationProvider provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) {
for ( StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations() ) {
applyFromStrategyRegistration( strategySelector, discoveredStrategyRegistration );
}
}
// apply customizations
for ( StrategyRegistration explicitStrategyRegistration : explicitStrategyRegistrations ) {
applyFromStrategyRegistration( strategySelector, explicitStrategyRegistration );
}
return strategySelector;
}
private BootstrapServiceRegistry buildBootstrapServiceRegistry(ClassLoaderService providedClassLoaderService) {
// N.B. support for custom IntegratorProvider injected via Properties (as
// instance) removed
final QuarkusIntegratorServiceImpl integratorService = new QuarkusIntegratorServiceImpl(providedClassLoaderService);
final QuarkusStrategySelectorBuilder strategySelectorBuilder = new QuarkusStrategySelectorBuilder();
final StrategySelector strategySelector = strategySelectorBuilder.buildSelector(providedClassLoaderService);
return new BootstrapServiceRegistryImpl(true, providedClassLoaderService, strategySelector, integratorService);
}
private boolean isBeanValidationApiAvailable(ClassLoaderService classLoaderService) {
try {
classLoaderService.classForName( BV_CHECK_CLASS );
return true;
}
catch (Exception e) {
return false;
}
}
private Class loadTypeSafeActivatorClass(ClassLoaderService classLoaderService) {
try {
return classLoaderService.classForName( ACTIVATOR_CLASS_NAME );
}
catch (Exception e) {
throw new HibernateException( "Unable to load TypeSafeActivator class", e );
}
}
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
if (referencedEntityName == null) {
final ClassLoaderService cls = getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class );
referencedEntityName = ReflectHelper.reflectedPropertyClass( className, propertyName, cls ).getName();
}
}
public Class getComponentClass() throws MappingException {
final ClassLoaderService classLoaderService = getMetadata()
.getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class );
try {
return classLoaderService.classForName( componentClassName );
}
catch (ClassLoadingException e) {
throw new MappingException("component class not found: " + componentClassName, e);
}
}
@Override
public void setTypeUsingReflection(String className, String propertyName) throws MappingException {
// NOTE : this is called as the last piece in setting SimpleValue type information, and implementations
// rely on that fact, using it as a signal that all information it is going to get is defined at this point...
if ( typeName != null ) {
// assume either (a) explicit type was specified or (b) determine was already performed
return;
}
if ( type != null ) {
return;
}
if ( attributeConverterDescriptor == null ) {
// this is here to work like legacy. This should change when we integrate with metamodel to
// look for SqlTypeDescriptor and JavaTypeDescriptor individually and create the BasicType (well, really
// keep a registry of [SqlTypeDescriptor,JavaTypeDescriptor] -> BasicType...)
if ( className == null ) {
throw new MappingException( "Attribute types for a dynamic entity must be explicitly specified: " + propertyName );
}
typeName = ReflectHelper.reflectedPropertyClass(
className,
propertyName,
getMetadata()
.getMetadataBuildingOptions()
.getServiceRegistry()
.getService( ClassLoaderService.class )
).getName();
// todo : to fully support isNationalized here we need do the process hinted at above
// essentially, much of the logic from #buildAttributeConverterTypeAdapter wrt resolving
// a (1) SqlTypeDescriptor, a (2) JavaTypeDescriptor and dynamically building a BasicType
// combining them.
return;
}
// we had an AttributeConverter...
type = buildAttributeConverterTypeAdapter();
}