diff --git a/hibernate-agroal/src/main/java/org/hibernate/agroal/internal/StrategyRegistrationProviderImpl.java b/hibernate-agroal/src/main/java/org/hibernate/agroal/internal/StrategyRegistrationProviderImpl.java index 30455fb7ba62..997de67b4379 100644 --- a/hibernate-agroal/src/main/java/org/hibernate/agroal/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-agroal/src/main/java/org/hibernate/agroal/internal/StrategyRegistrationProviderImpl.java @@ -4,13 +4,13 @@ */ package org.hibernate.agroal.internal; -import java.util.Collections; - import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import static java.util.Collections.singleton; + /** * Provides the {@link AgroalConnectionProvider} to the * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. @@ -20,8 +20,8 @@ public final class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - public Iterable getStrategyRegistrations() { - final SimpleStrategyRegistrationImpl strategyRegistration = new SimpleStrategyRegistrationImpl<>( + public Iterable> getStrategyRegistrations() { + return singleton( new SimpleStrategyRegistrationImpl<>( ConnectionProvider.class, AgroalConnectionProvider.class, AgroalConnectionProvider.class.getSimpleName(), @@ -29,7 +29,6 @@ public Iterable getStrategyRegistrations() { "Agroal", // for consistency's sake "org.hibernate.connection.AgroalConnectionProvider" - ); - return Collections.singleton( strategyRegistration ); + ) ); } } diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java index c6247952779d..5f5912f85457 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java @@ -4,13 +4,13 @@ */ package org.hibernate.c3p0.internal; -import java.util.Collections; - import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import static java.util.Collections.singleton; + /** * Provides the {@link C3P0ConnectionProvider} to the * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. @@ -20,8 +20,8 @@ public final class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - public Iterable getStrategyRegistrations() { - final SimpleStrategyRegistrationImpl c3p0 = new SimpleStrategyRegistrationImpl<>( + public Iterable> getStrategyRegistrations() { + return singleton( new SimpleStrategyRegistrationImpl<>( ConnectionProvider.class, C3P0ConnectionProvider.class, "c3p0", @@ -30,7 +30,6 @@ public Iterable getStrategyRegistrations() { "org.hibernate.connection.C3P0ConnectionProvider", // legacy "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" - ); - return Collections.singleton( c3p0 ); + ) ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java b/hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java index aa1f117f3c34..11a31753703d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java @@ -5,14 +5,12 @@ package org.hibernate.boot; import org.hibernate.Internal; +import org.hibernate.boot.jaxb.Origin; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.internal.log.SubSystemLogging; -import java.io.File; -import java.io.FileNotFoundException; import java.lang.invoke.MethodHandles; -import org.hibernate.type.SerializationException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; @@ -20,11 +18,11 @@ import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; +import org.jboss.logging.annotations.ValidIdRanges; import static org.jboss.logging.Logger.Level.DEBUG; import static org.jboss.logging.Logger.Level.TRACE; import static org.jboss.logging.Logger.Level.WARN; -import static org.jboss.logging.Logger.Level.INFO; /** * Logging related to Hibernate bootstrapping @@ -34,7 +32,10 @@ description = "Logging related to bootstrapping of a SessionFactory / EntityManagerFactory" ) @MessageLogger(projectCode = "HHH") -@ValidIdRange(min = 160101, max = 160200) +@ValidIdRanges({ + @ValidIdRange(min = 160101, max = 160200), + @ValidIdRange(min = 160201, max = 160260) +}) @Internal public interface BootLogging extends BasicLogger { String NAME = SubSystemLogging.BASE + ".boot"; @@ -44,34 +45,6 @@ public interface BootLogging extends BasicLogger { @Message(id = 160101, value = "Duplicate generator name %s") void duplicateGeneratorName(String name); - @LogMessage(level = INFO) - @Message(id = 160102, value = "Reading mappings from file: %s") - void readingMappingsFromFile(String path); - - @LogMessage(level = INFO) - @Message(id = 160103, value = "Reading mappings from cache file: %s") - void readingCachedMappings(File cachedFile); - - @LogMessage(level = WARN) - @Message(id = 160104, value = "Could not deserialize cache file [%s]: %s") - void unableToDeserializeCache(String path, SerializationException error); - - @LogMessage(level = WARN) - @Message(id = 160105, value = "I/O reported error writing cached file: [%s]: %s") - void unableToWriteCachedFile(String path, String message); - - @LogMessage(level = WARN) - @Message(id = 160106, value = "Could not update cached file timestamp: [%s]") - @SuppressWarnings("unused") - void unableToUpdateCachedFileTimestamp(String path); - - @LogMessage(level = WARN) - @Message(id = 160107, value = "I/O reported cached file could not be found: [%s]: %s") - void cachedFileNotFound(String path, FileNotFoundException error); - - @LogMessage(level = INFO) - @Message(id = 160108, value = "Omitting cached file [%s] as the mapping file is newer") - void cachedFileObsolete(File cachedFile); @LogMessage(level = DEBUG) @Message(id = 160111, value = "Package not found or no package-info.java: %s") @@ -268,10 +241,6 @@ public interface BootLogging extends BasicLogger { @Message(id = 160178, value = "Mapping entity secondary table: %s -> %s") void mappingEntitySecondaryTableToTable(String entityName, String tableName); - @LogMessage(level = TRACE) - @Message(id = 160179, value = "Writing cache file for: %s to: %s") - void writingCacheFile(String xmlPath, String serPath); - @LogMessage(level = DEBUG) @Message(id = 160180, value = "Unexpected ServiceRegistry type [%s] encountered during building of MetadataSources; may cause problems later attempting to construct MetadataBuilder") void unexpectedServiceRegistryType(String registryType); @@ -313,6 +282,7 @@ public interface BootLogging extends BasicLogger { void duplicatedFetchProfile(String name); // EntityBinder discriminator handling + @LogMessage(level = TRACE) @Message(id = 160190, value = "Ignoring explicit @DiscriminatorColumn annotation on: %s") void ignoringExplicitDiscriminatorForJoined(String className); @@ -321,7 +291,8 @@ public interface BootLogging extends BasicLogger { @Message(id = 160191, value = "Inferring implicit @DiscriminatorColumn using defaults for: %s") void inferringImplicitDiscriminatorForJoined(String className); - // GeneratorBinder additions + // GeneratorBinder + @LogMessage(level = TRACE) @Message(id = 160192, value = "Added generator with name: %s, strategy: %s") void addedGenerator(String name, String strategy); @@ -340,4 +311,142 @@ public interface BootLogging extends BasicLogger { ServiceRegistry passed to MetadataBuilder was a BootstrapServiceRegistry; \ this likely won't end well if attempt is made to build SessionFactory""") void badServiceRegistry(); + + @LogMessage(level = DEBUG) + @Message(id = 160201, value = "Unable to close cfg.xml resource stream") + void unableToCloseCfgXmlResourceStream(@Cause Throwable e); + + @LogMessage(level = DEBUG) + @Message(id = 160202, value = "Unable to close cfg.xml URL stream") + void unableToCloseCfgXmlUrlStream(@Cause Throwable e); + + @LogMessage(level = DEBUG) + @Message(id = 160203, value = "Unable to close properties file stream [%s]") + void unableToClosePropertiesFileStream(String path, @Cause Throwable e); + + @LogMessage(level = DEBUG) + @Message(id = 160204, value = "cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information") + void cfgXmlDocumentDidNotDefineNamespaces(); + + @LogMessage(level = DEBUG) + @Message(id = 160212, value = "Unable to adjust relative URL [%s] relative to root URL [%s]") + void unableToAdjustRelativeJarFileUrl(String filePart, String rootPath, @Cause Throwable e); + + @LogMessage(level = TRACE) + @Message(id = 160213, value = "JAR URL from URL Entry: %s >> %s") + void jarUrlFromUrlEntry(String url, String jarUrl); + + @LogMessage(level = TRACE) + @Message(id = 160217, value = "Registering AttributeConverter '%s'") + void registeringAttributeConverter(String converter); + + @LogMessage(level = DEBUG) + @Message(id = 160218, value = "Skipping registration of discovered AttributeConverter '%s' for auto-apply") + void skippingRegistrationAttributeConverterForAutoApply(String converter); + + @LogMessage(level = DEBUG) + @Message(id = 160219, value = "Skipping duplicate '@ConverterRegistration' for '%s'") + void skippingDuplicateConverterRegistration(String converter); + + @LogMessage(level = DEBUG) + @Message(id = 160220, value = "Removed potentially auto-applicable converter '%s' due to @ConverterRegistration") + void removedPotentiallyAutoApplicableConverterDueToRegistration(String converter); + + @LogMessage(level = DEBUG) + @Message(id = 160221, value = "Overwrote existing registration [%s] for type definition.") + void overwroteExistingRegistrationForTypeDefinition(String name); + + @LogMessage(level = TRACE) + @Message(id = 160222, value = "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]") + void injectingJpaTempClassLoader(Object newLoader, Object oldLoader); + + @LogMessage(level = TRACE) + @Message(id = 160223, value = "Injecting ScanOptions [%s] into BootstrapContext; was [%s]") + void injectingScanOptions(Object newOptions, Object oldOptions); + + @LogMessage(level = TRACE) + @Message(id = 160224, value = "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]") + void injectingScanEnvironment(Object newEnv, Object oldEnv); + + @LogMessage(level = TRACE) + @Message(id = 160225, value = "Injecting Scanner [%s] into BootstrapContext; was [%s]") + void injectingScanner(Object newScanner, Object oldScanner); + + @LogMessage(level = TRACE) + @Message(id = 160226, value = "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]") + void injectingArchiveDescriptorFactory(Object newFactory, Object oldFactory); + + // Strategy selector + + @LogMessage(level = TRACE) + @Message(id = 160227, value = "Strategy selector for %s: '%s' -> %s") + void strategySelectorMapping(String strategySimpleName, String name, String implementationName); + + @LogMessage(level = TRACE) + @Message(id = 160228, value = "Strategy selector for %s: '%s' -> %s (replacing %s)") + void strategySelectorMappingReplacing(String strategySimpleName, String name, String implementationName, String oldImplementationName); + + @LogMessage(level = DEBUG) + @Message(id = 160229, value = "Named strategy map did not exist on call to unregister") + void namedStrategyMapDidNotExistOnUnregister(); + + // LoadedConfig + + @LogMessage(level = DEBUG) + @Message(id = 160230, value = "Listener [%s] defined as part of a group also defined event type") + void listenerDefinedAlsoDefinedEventType(String listenerClass); + + @LogMessage(level = DEBUG) + @Message(id = 160231, value = "More than one cfg.xml file attempted to supply SessionFactory name: [%s], [%s]. Keeping initially discovered one [%s]") + void moreThanOneCfgXmlSuppliedSessionFactoryName(String first, String second, String keeping); + + // HBM binding + + @LogMessage(level = TRACE) + @Message(id = 160233, value = "Creating FetchProfile: %s") + void creatingFetchProfile(String name); + + @LogMessage(level = TRACE) + @Message(id = 160234, value = "Processing : %s") + void processingIdentifierGenerator(String name); + + @LogMessage(level = TRACE) + @Message(id = 160235, value = "Processed type definition : %s -> %s") + void processedTypeDefinition(String name, String impl); + + @LogMessage(level = TRACE) + @Message(id = 160236, value = "No temp ClassLoader provided; using live ClassLoader to load potentially unsafe class: %s") + void noTempClassLoaderProvidedUsingLiveClassLoader(String className); + + @LogMessage(level = TRACE) + @Message(id = 160237, value = "Registering non-interface strategy : %s") + void registeringNonInterfaceStrategy(String roleName); + + @LogMessage(level = TRACE) + @Message(id = 160238, value = "Indexing mapping document [%s] for purpose of building entity hierarchy ordering") + void indexingMappingDocumentForHierarchyOrdering(String mappingDocumentName); + + @LogMessage(level = DEBUG) + @Message(id = 160239, value = "Applying filter definition with condition: %s") + void applyingFilterDefinitionCondition(String condition); + + @LogMessage(level = TRACE) + @Message(id = 160240, value = "Processed filter definition: %s") + void processedFilterDefinition(String name); + + @LogMessage(level = DEBUG) + @Message(id = 160241, value = "Entity supertype named as extends [%s] for subclass [%s:%s] not found") + void entitySupertypeExtendsNotFound(String extendsName, Origin origin, String subclassName); + + @LogMessage(level = DEBUG) + @Message(id = 160242, value = "filter-def [name=%s, origin=%s] defined multiple conditions, accepting arbitrary one") + void filterDefDefinedMultipleConditions(String name, String origin); + + @LogMessage(level = TRACE) + @Message(id = 160243, value = "Checking auto-apply AttributeConverter [%s] (domain-type=%s) for match against %s : %s.%s (type=%s)") + void checkingAutoApplyAttributeConverter(String converterClass, String domainTypeSignature, String siteDescriptor, String declaringType, String memberName, String memberTypeName); + + @LogMessage(level = DEBUG) + @Message(id = 160244, value = "Skipping HBM processing of entity hierarchy [%s], as at least one entity [%s] has been processed") + void skippingHbmProcessingOfEntityHierarchy(String rootEntityName, String processedEntity); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java index bf98fbba24a8..89b2b6cc0ebc 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/ArchiveHelper.java @@ -14,7 +14,6 @@ import org.hibernate.boot.archive.spi.ArchiveException; -import org.jboss.logging.Logger; /** * Helper for dealing with archives @@ -23,7 +22,6 @@ * @author Steve Ebersole */ public class ArchiveHelper { - private static final Logger LOG = Logger.getLogger( ArchiveHelper.class ); /** * Get the JAR URL of the JAR containing the given entry. @@ -91,7 +89,7 @@ else if ( "zip".equals( protocol ) "Unable to determine JAR Url from " + url + ". Cause: " + e.getMessage() ); } - LOG.tracef( "JAR URL from URL Entry: %s >> %s", url, jarUrl ); + org.hibernate.boot.BootLogging.BOOT_LOGGER.jarUrlFromUrlEntry( String.valueOf(url), String.valueOf(jarUrl) ); return jarUrl; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/StandardArchiveDescriptorFactory.java b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/StandardArchiveDescriptorFactory.java index 0b009fb7b629..2a409e401177 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/StandardArchiveDescriptorFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/archive/internal/StandardArchiveDescriptorFactory.java @@ -14,7 +14,7 @@ import org.hibernate.boot.archive.spi.JarFileEntryUrlAdjuster; import org.hibernate.internal.util.StringHelper; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * Standard implementation of ArchiveDescriptorFactory @@ -23,7 +23,6 @@ * @author Steve Ebersole */ public class StandardArchiveDescriptorFactory implements ArchiveDescriptorFactory, JarFileEntryUrlAdjuster { - private static final Logger LOG = Logger.getLogger( StandardArchiveDescriptorFactory.class ); /** * Singleton access @@ -129,14 +128,11 @@ public URL adjustJarFileEntryUrl(URL url, URL rootUrl) { } catch (MalformedURLException e) { // allow to pass through to return the original URL - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - e, - "Unable to adjust relative URL [%s] relative to root URL [%s]", - filePart, - rootUrlFile.getAbsolutePath() - ); - } + BOOT_LOGGER.unableToAdjustRelativeJarFileUrl( + filePart, + rootUrlFile.getAbsolutePath(), + e + ); } return url; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java index 0c72fc7770c1..76cceb50d599 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/ConfigLoader.java @@ -14,13 +14,14 @@ import org.hibernate.boot.cfgxml.spi.LoadedConfig; import org.hibernate.boot.jaxb.Origin; -import org.hibernate.boot.jaxb.SourceType; -import org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration; import org.hibernate.boot.registry.BootstrapServiceRegistry; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.internal.util.ValueHolder; import org.hibernate.internal.util.config.ConfigurationException; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.boot.jaxb.SourceType.FILE; +import static org.hibernate.boot.jaxb.SourceType.RESOURCE; +import static org.hibernate.boot.jaxb.SourceType.URL; /** * Loads {@code cfg.xml} files. @@ -28,7 +29,6 @@ * @author Steve Ebersole */ public class ConfigLoader { - private static final Logger LOG = Logger.getLogger( ConfigLoader.class ); private final BootstrapServiceRegistry bootstrapServiceRegistry; @@ -45,38 +45,37 @@ public ConfigLoader(BootstrapServiceRegistry bootstrapServiceRegistry) { this.bootstrapServiceRegistry = bootstrapServiceRegistry; } + private InputStream locateStream(String cfgXmlResourceName) { + return bootstrapServiceRegistry.requireService( ClassLoaderService.class ) + .locateResourceStream( cfgXmlResourceName ); + } + public LoadedConfig loadConfigXmlResource(String cfgXmlResourceName) { - final InputStream stream = bootstrapServiceRegistry.requireService( ClassLoaderService.class ).locateResourceStream( cfgXmlResourceName ); + final var stream = locateStream( 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 ); + return LoadedConfig.consume( jaxbProcessorHolder.getValue() + .unmarshal( stream, new Origin( RESOURCE, cfgXmlResourceName ) ) ); } finally { try { stream.close(); } catch (IOException e) { - LOG.debug( "Unable to close cfg.xml resource stream", e ); + BOOT_LOGGER.unableToCloseCfgXmlResourceStream( e ); } } } public LoadedConfig loadConfigXmlFile(File cfgXmlFile) { try { - final JaxbCfgHibernateConfiguration jaxbCfg = jaxbProcessorHolder.getValue().unmarshal( - new FileInputStream( cfgXmlFile ), - new Origin( SourceType.FILE, cfgXmlFile.getAbsolutePath() ) - ); - return LoadedConfig.consume( jaxbCfg ); + return LoadedConfig.consume( jaxbProcessorHolder.getValue() + .unmarshal( new FileInputStream( cfgXmlFile ), + new Origin( FILE, cfgXmlFile.getAbsolutePath() ) ) ); } catch (FileNotFoundException e) { throw new ConfigurationException( @@ -87,21 +86,17 @@ public LoadedConfig loadConfigXmlFile(File cfgXmlFile) { public LoadedConfig loadConfigXmlUrl(URL url) { try { - final InputStream stream = url.openStream(); + final var stream = url.openStream(); try { - final JaxbCfgHibernateConfiguration jaxbCfg = jaxbProcessorHolder.getValue().unmarshal( - stream, - new Origin( SourceType.URL, url.toExternalForm() ) - ); - - return LoadedConfig.consume( jaxbCfg ); + return LoadedConfig.consume( jaxbProcessorHolder.getValue() + .unmarshal( stream, new Origin( URL, url.toExternalForm() ) ) ); } finally { try { stream.close(); } catch (IOException e) { - LOG.debug( "Unable to close cfg.xml URL stream", e ); + BOOT_LOGGER.unableToCloseCfgXmlUrlStream( e ); } } } @@ -111,16 +106,13 @@ public LoadedConfig loadConfigXmlUrl(URL url) { } public Properties loadProperties(String resourceName) { - final InputStream stream = bootstrapServiceRegistry.requireService( ClassLoaderService.class ).locateResourceStream( resourceName ); - + final var stream = locateStream( resourceName ); if ( stream == null ) { throw new ConfigurationException( "Unable to apply settings from properties file [" + resourceName + "]" ); } try { - Properties properties = new Properties(); - properties.load( stream ); - return properties; + return loadProperties( stream ); } catch (IOException e) { throw new ConfigurationException( "Unable to apply settings from properties file [" + resourceName + "]", e ); @@ -130,18 +122,16 @@ public Properties loadProperties(String resourceName) { stream.close(); } catch (IOException e) { - LOG.debug( "Unable to close properties file stream [" + resourceName + "]", e ); + BOOT_LOGGER.unableToClosePropertiesFileStream( resourceName, e ); } } } public Properties loadProperties(File file) { try { - final InputStream stream = new FileInputStream( file ); + final var stream = new FileInputStream( file ); try { - Properties properties = new Properties(); - properties.load( stream ); - return properties; + return loadProperties( stream ); } catch (IOException e) { throw new ConfigurationException( @@ -154,7 +144,7 @@ public Properties loadProperties(File file) { stream.close(); } catch (IOException e) { - LOG.debug( "Unable to close properties file stream [" + file.getAbsolutePath() + "]", e ); + BOOT_LOGGER.unableToClosePropertiesFileStream( file.getAbsolutePath(), e ); } } } @@ -166,4 +156,9 @@ public Properties loadProperties(File file) { } } + private static Properties loadProperties(InputStream stream) throws IOException { + final var properties = new Properties(); + properties.load( stream ); + return properties; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/JaxbCfgProcessor.java b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/JaxbCfgProcessor.java index 67d793da0647..78653833b596 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/JaxbCfgProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/internal/JaxbCfgProcessor.java @@ -9,19 +9,20 @@ import org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration; import org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.config.ConfigurationException; import org.hibernate.internal.util.xml.XsdException; -import org.jboss.logging.Logger; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; +import static org.hibernate.internal.util.StringHelper.isNotEmpty; + import org.xml.sax.SAXException; -import javax.xml.XMLConstants; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; -import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.ValidationEvent; import jakarta.xml.bind.ValidationEventHandler; -import jakarta.xml.bind.ValidationEventLocator; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventReader; @@ -38,14 +39,12 @@ import java.io.InputStream; import java.net.URL; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; /** * @author Steve Ebersole */ public class JaxbCfgProcessor { - private static final Logger LOG = Logger.getLogger( JaxbCfgProcessor.class ); public static final String HIBERNATE_CONFIGURATION_URI = "http://www.hibernate.org/xsd/orm/cfg"; @@ -59,7 +58,7 @@ public JaxbCfgProcessor(ClassLoaderService classLoaderService) { public JaxbCfgHibernateConfiguration unmarshal(InputStream stream, Origin origin) { try { - XMLEventReader staxReader = staxFactory().createXMLEventReader( stream ); + final var staxReader = staxFactory().createXMLEventReader( stream ); try { return unmarshal( staxReader, origin ); } @@ -86,38 +85,24 @@ private XMLInputFactory staxFactory() { } private XMLInputFactory buildStaxFactory() { - XMLInputFactory staxFactory = XMLInputFactory.newInstance(); + final var staxFactory = XMLInputFactory.newInstance(); staxFactory.setXMLResolver( xmlResourceResolver ); return staxFactory; } private JaxbCfgHibernateConfiguration unmarshal(XMLEventReader staxEventReader, final Origin origin) { - XMLEvent event; - try { - event = staxEventReader.peek(); - while ( event != null && !event.isStartElement() ) { - staxEventReader.nextEvent(); - event = staxEventReader.peek(); - } - } - catch ( Exception e ) { - throw new HibernateException( "Error accessing StAX stream", e ); - } - - if ( event == null ) { - throw new HibernateException( "Could not locate root element" ); - } - + final XMLEvent event = xmlEvent( staxEventReader ); if ( !isNamespaced( event.asStartElement() ) ) { // if the elements are not namespaced, wrap the reader in a reader which will namespace them as pulled. - LOG.debug( "cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information" ); + BOOT_LOGGER.cfgXmlDocumentDidNotDefineNamespaces(); staxEventReader = new NamespaceAddingEventReader( staxEventReader, HIBERNATE_CONFIGURATION_URI ); } - final ContextProvidingValidationEventHandler handler = new ContextProvidingValidationEventHandler(); + final var handler = new ContextProvidingValidationEventHandler(); try { - JAXBContext jaxbContext = JAXBContext.newInstance( JaxbCfgHibernateConfiguration.class ); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + final var unmarshaller = + JAXBContext.newInstance( JaxbCfgHibernateConfiguration.class ) + .createUnmarshaller(); unmarshaller.setSchema( schema() ); unmarshaller.setEventHandler( handler ); return (JaxbCfgHibernateConfiguration) unmarshaller.unmarshal( staxEventReader ); @@ -132,8 +117,25 @@ private JaxbCfgHibernateConfiguration unmarshal(XMLEventReader staxEventReader, } } + private static XMLEvent xmlEvent(XMLEventReader staxEventReader) { + try { + XMLEvent event = staxEventReader.peek(); + while ( event != null && !event.isStartElement() ) { + staxEventReader.nextEvent(); + event = staxEventReader.peek(); + } + if ( event == null ) { + throw new HibernateException( "Could not locate root element" ); + } + return event; + } + catch ( Exception e ) { + throw new HibernateException( "Error accessing StAX stream", e ); + } + } + private boolean isNamespaced(StartElement startElement) { - return StringHelper.isNotEmpty( startElement.getName().getNamespaceURI() ); + return isNotEmpty( startElement.getName().getNamespaceURI() ); } private Schema schema; @@ -146,20 +148,19 @@ private Schema schema() { } private Schema resolveLocalSchema(String schemaName) { - return resolveLocalSchema( schemaName, XMLConstants.W3C_XML_SCHEMA_NS_URI ); + return resolveLocalSchema( schemaName, W3C_XML_SCHEMA_NS_URI ); } private Schema resolveLocalSchema(String schemaName, String schemaLanguage) { - URL url = classLoaderService.locateResource( schemaName ); + final URL url = classLoaderService.locateResource( schemaName ); if ( url == null ) { throw new XsdException( "Unable to locate schema [" + schemaName + "] via classpath", schemaName ); } try { - InputStream schemaStream = url.openStream(); + final var schemaStream = url.openStream(); try { - StreamSource source = new StreamSource( url.openStream() ); - SchemaFactory schemaFactory = SchemaFactory.newInstance( schemaLanguage ); - return schemaFactory.newSchema( source ); + return SchemaFactory.newInstance( schemaLanguage ) + .newSchema( new StreamSource( url.openStream() ) ); } catch ( SAXException | IOException e ) { throw new XsdException( "Unable to load schema [" + schemaName + "]", e, schemaName ); @@ -169,7 +170,7 @@ private Schema resolveLocalSchema(String schemaName, String schemaLanguage) { schemaStream.close(); } catch ( IOException e ) { - LOG.debugf( "Problem closing schema stream [%s]", e.toString() ); + JAXB_LOGGER.problemClosingSchemaStream( e.toString() ); } } } @@ -185,7 +186,7 @@ static class ContextProvidingValidationEventHandler implements ValidationEventHa @Override public boolean handleEvent(ValidationEvent validationEvent) { - ValidationEventLocator locator = validationEvent.getLocator(); + final var locator = validationEvent.getLocator(); lineNumber = locator.getLineNumber(); columnNumber = locator.getColumnNumber(); message = validationEvent.getMessage(); @@ -223,9 +224,9 @@ private StartElement withNamespace(StartElement startElement) { // otherwise, wrap the start element event to provide a default namespace mapping final List namespaces = new ArrayList<>(); namespaces.add( xmlEventFactory.createNamespace( "", namespaceUri ) ); - Iterator originalNamespaces = startElement.getNamespaces(); + final var originalNamespaces = startElement.getNamespaces(); while ( originalNamespaces.hasNext() ) { - namespaces.add( (Namespace) originalNamespaces.next() ); + namespaces.add( originalNamespaces.next() ); } return xmlEventFactory.createStartElement( new QName( namespaceUri, startElement.getName().getLocalPart() ), @@ -236,22 +237,14 @@ private StartElement withNamespace(StartElement startElement) { @Override public XMLEvent nextEvent() throws XMLStreamException { - XMLEvent event = super.nextEvent(); - if ( event.isStartElement() ) { - return withNamespace( event.asStartElement() ); - } - return event; + final var event = super.nextEvent(); + return event.isStartElement() ? withNamespace( event.asStartElement() ) : event; } @Override public XMLEvent peek() throws XMLStreamException { - XMLEvent event = super.peek(); - if ( event.isStartElement() ) { - return withNamespace( event.asStartElement() ); - } - else { - return event; - } + final var event = super.peek(); + return event.isStartElement() ? withNamespace( event.asStartElement() ) : event; } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/spi/LoadedConfig.java b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/spi/LoadedConfig.java index f95379127d4a..be806d5b7dbb 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/spi/LoadedConfig.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/cfgxml/spi/LoadedConfig.java @@ -19,7 +19,8 @@ import org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration; import org.hibernate.event.spi.EventType; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; + /** * Models the information gleaned from parsing a {@code cfg.xml} file. @@ -28,7 +29,6 @@ * representation can be maintained through calls to {@link #merge}. */ public class LoadedConfig { - private static final Logger LOG = Logger.getLogger( LoadedConfig.class ); private String sessionFactoryName; @@ -100,10 +100,11 @@ public static LoadedConfig consume(JaxbCfgHibernateConfiguration jaxbCfg) { final String eventTypeName = listenerGroup.getType().value(); final var eventType = EventType.resolveEventTypeByName( eventTypeName ); for ( var listener : listenerGroup.getListener() ) { - if ( listener.getType() != null ) { - LOG.debugf( "Listener [%s] defined as part of a group also defined event type", - listener.getClazz() ); - } + if ( listener.getType() != null ) { + BOOT_LOGGER.listenerDefinedAlsoDefinedEventType( + listener.getClazz() + ); + } cfg.addEventListener( eventType, listener.getClazz() ); } } @@ -185,18 +186,18 @@ public void addEventListener(EventType eventType, String listenerClass) { * @param incoming The incoming config information to merge in. */ public void merge(LoadedConfig incoming) { - if ( sessionFactoryName != null ) { - if ( incoming.getSessionFactoryName() != null ) { - LOG.debugf( - "More than one cfg.xml file attempted to supply SessionFactory name: [%s], [%s]. Keeping initially discovered one [%s]", - getSessionFactoryName(), - incoming.getSessionFactoryName(), - getSessionFactoryName() + final String sessionFactoryName = incoming.getSessionFactoryName(); + if ( this.sessionFactoryName != null ) { + if ( sessionFactoryName != null ) { + BOOT_LOGGER.moreThanOneCfgXmlSuppliedSessionFactoryName( + this.sessionFactoryName, + sessionFactoryName, + this.sessionFactoryName ); } } else { - sessionFactoryName = incoming.getSessionFactoryName(); + this.sessionFactoryName = sessionFactoryName; } addConfigurationValues( incoming.getConfigurationValues() ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java index c6cde91de063..e51dab58de82 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/BootstrapContextImpl.java @@ -22,7 +22,7 @@ import org.hibernate.boot.spi.ClassLoaderAccess; import org.hibernate.boot.spi.ClassmateContext; import org.hibernate.boot.spi.MetadataBuildingOptions; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.PersistenceSettings; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.jpa.internal.MutableJpaComplianceImpl; import org.hibernate.jpa.spi.MutableJpaCompliance; @@ -36,7 +36,6 @@ import org.hibernate.resource.beans.spi.ManagedBeanRegistry; import org.hibernate.type.BasicType; import org.hibernate.type.spi.TypeConfiguration; -import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.Collection; @@ -45,12 +44,14 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.cfg.PersistenceSettings.SCANNER; +import static org.hibernate.cfg.PersistenceSettings.SCANNER_ARCHIVE_INTERPRETER; /** * @author Andrea Boriero */ public class BootstrapContextImpl implements BootstrapContext { - private static final Logger LOG = Logger.getLogger( BootstrapContextImpl.class ); private final StandardServiceRegistry serviceRegistry; private final MetadataBuildingOptions metadataBuildingOptions; @@ -92,20 +93,20 @@ public BootstrapContextImpl( classLoaderService = serviceRegistry.requireService( ClassLoaderService.class ); classLoaderAccess = new ClassLoaderAccessImpl( classLoaderService ); - final StrategySelector strategySelector = serviceRegistry.requireService( StrategySelector.class ); - final ConfigurationService configService = serviceRegistry.requireService( ConfigurationService.class ); + final var strategySelector = serviceRegistry.requireService( StrategySelector.class ); + final var configService = serviceRegistry.requireService( ConfigurationService.class ); jpaCompliance = new MutableJpaComplianceImpl( configService.getSettings() ); scanOptions = new StandardScanOptions( - (String) configService.getSettings().get( AvailableSettings.SCANNER_DISCOVERY ), + (String) configService.getSettings().get( PersistenceSettings.SCANNER_DISCOVERY ), false ); // ScanEnvironment must be set explicitly - scannerSetting = configService.getSettings().get( AvailableSettings.SCANNER ); + scannerSetting = configService.getSettings().get( SCANNER ); archiveDescriptorFactory = strategySelector.resolveStrategy( ArchiveDescriptorFactory.class, - configService.getSettings().get( AvailableSettings.SCANNER_ARCHIVE_INTERPRETER ) + configService.getSettings().get( SCANNER_ARCHIVE_INTERPRETER ) ); representationStrategySelector = ManagedTypeRepresentationResolverStandard.INSTANCE; @@ -296,53 +297,49 @@ public void addAttributeConverterDescriptor(ConverterDescriptor descriptor) attributeConverterDescriptorMap = new HashMap<>(); } - final Object old = attributeConverterDescriptorMap.put( descriptor.getAttributeConverterClass(), descriptor ); + final var attributeConverterClass = descriptor.getAttributeConverterClass(); + final Object old = attributeConverterDescriptorMap.put( attributeConverterClass, descriptor ); if ( old != null ) { throw new AssertionFailure( String.format( "AttributeConverter class [%s] registered multiple times", - descriptor.getAttributeConverterClass() + attributeConverterClass ) ); } } void injectJpaTempClassLoader(ClassLoader classLoader) { - if ( LOG.isTraceEnabled() && classLoader != getJpaTempClassLoader() ) { - LOG.tracef( "Injecting JPA temp ClassLoader [%s] into BootstrapContext; was [%s]", - classLoader, getJpaTempClassLoader() ); + if ( BOOT_LOGGER.isTraceEnabled() && classLoader != getJpaTempClassLoader() ) { + BOOT_LOGGER.injectingJpaTempClassLoader( classLoader, getJpaTempClassLoader() ); } this.classLoaderAccess.injectTempClassLoader( classLoader ); } void injectScanOptions(ScanOptions scanOptions) { - if ( LOG.isTraceEnabled() && scanOptions != this.scanOptions ) { - LOG.tracef( "Injecting ScanOptions [%s] into BootstrapContext; was [%s]", - scanOptions, this.scanOptions ); + if ( scanOptions != this.scanOptions ) { + BOOT_LOGGER.injectingScanOptions(scanOptions, this.scanOptions); } this.scanOptions = scanOptions; } void injectScanEnvironment(ScanEnvironment scanEnvironment) { - if ( LOG.isTraceEnabled() && scanEnvironment != this.scanEnvironment ) { - LOG.tracef( "Injecting ScanEnvironment [%s] into BootstrapContext; was [%s]", - scanEnvironment, this.scanEnvironment ); + if ( scanEnvironment != this.scanEnvironment ) { + BOOT_LOGGER.injectingScanEnvironment( scanEnvironment, this.scanEnvironment ); } this.scanEnvironment = scanEnvironment; } void injectScanner(Scanner scanner) { - if ( LOG.isTraceEnabled() && scanner != this.scannerSetting ) { - LOG.tracef( "Injecting Scanner [%s] into BootstrapContext; was [%s]", - scanner, scannerSetting ); + if ( scanner != this.scannerSetting ) { + BOOT_LOGGER.injectingScanner( scanner, scannerSetting ); } this.scannerSetting = scanner; } void injectArchiveDescriptorFactory(ArchiveDescriptorFactory factory) { - if ( LOG.isTraceEnabled() && factory != archiveDescriptorFactory ) { - LOG.tracef( "Injecting ArchiveDescriptorFactory [%s] into BootstrapContext; was [%s]", - factory, archiveDescriptorFactory ); + if ( factory != archiveDescriptorFactory ) { + BOOT_LOGGER.injectingArchiveDescriptorFactory( factory, archiveDescriptorFactory ); } this.archiveDescriptorFactory = factory; } @@ -372,9 +369,8 @@ public void addCacheRegionDefinition(CacheRegionDefinition cacheRegionDefinition public static ModelsContext createModelBuildingContext( ClassLoaderService classLoaderService, ConfigurationService configService) { - final ClassLoaderServiceLoading classLoading = new ClassLoaderServiceLoading( classLoaderService ); - - final ModelsConfiguration modelsConfiguration = new ModelsConfiguration(); + final var classLoading = new ClassLoaderServiceLoading( classLoaderService ); + final var modelsConfiguration = new ModelsConfiguration(); modelsConfiguration.setClassLoading( classLoading ); modelsConfiguration.setRegistryPrimer( ModelsHelper::preFillRegistries ); configService.getSettings().forEach( (key, value) -> { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java index f18206cd11a1..5b9ed55a9fe4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/ClassLoaderAccessImpl.java @@ -11,7 +11,7 @@ import org.hibernate.boot.spi.ClassLoaderAccess; import org.hibernate.service.ServiceRegistry; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * Standard implementation of ClassLoaderAccess @@ -19,7 +19,6 @@ * @author Steve Ebersole */ public class ClassLoaderAccessImpl implements ClassLoaderAccess { - private static final Logger LOG = Logger.getLogger( ClassLoaderAccessImpl.class ); private final ClassLoaderService classLoaderService; private ClassLoader jpaTempClassLoader; @@ -56,17 +55,10 @@ public Class classForName(String name) { else { // Could not determine that the given class is safe to load with live ClassLoader if ( jpaTempClassLoader == null ) { - LOG.tracef( - "No temp ClassLoader provided; using live ClassLoader to load potentially unsafe class: %s", - name - ); + BOOT_LOGGER.noTempClassLoaderProvidedUsingLiveClassLoader( name ); return classLoaderService.classForName( name ); } else { -// LOG.tracef( -// "Temp ClassLoader was provided, so we will use that: %s", -// name -// ); try { return jpaTempClassLoader.loadClass( name ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/internal/TypeDefinitionRegistryStandardImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/internal/TypeDefinitionRegistryStandardImpl.java index 9297d14ac4b8..21dea36f2019 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/internal/TypeDefinitionRegistryStandardImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/internal/TypeDefinitionRegistryStandardImpl.java @@ -12,8 +12,8 @@ import org.hibernate.boot.model.TypeDefinitionRegistry; import org.hibernate.type.descriptor.java.BasicJavaType; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; import static org.hibernate.internal.util.StringHelper.isEmpty; /** @@ -22,7 +22,6 @@ * @author Chris Cranford */ public class TypeDefinitionRegistryStandardImpl implements TypeDefinitionRegistry { - private static final Logger LOG = Logger.getLogger( TypeDefinitionRegistryStandardImpl.class ); private final TypeDefinitionRegistry parent; private final Map typeDefinitionMap = new HashMap<>(); @@ -37,7 +36,7 @@ public TypeDefinitionRegistryStandardImpl(TypeDefinitionRegistry parent) { @Override public TypeDefinition resolve(String typeName) { - final TypeDefinition localDefinition = typeDefinitionMap.get( typeName ); + final var localDefinition = typeDefinitionMap.get( typeName ); if ( localDefinition != null ) { return localDefinition; } @@ -50,11 +49,12 @@ else if ( parent != null ) { } @Override - public TypeDefinition resolveAutoApplied(BasicJavaType jtd) { + public TypeDefinition resolveAutoApplied(BasicJavaType basicJavaType) { // For now, check the definition map for an entry keyed by the JTD name. // Ultimately should maybe have TypeDefinition or the registry keep explicit // track of auto-applied definitions. - return jtd.getJavaType() == null ? null : typeDefinitionMap.get( jtd.getTypeName() ); + return basicJavaType.getJavaType() == null ? null + : typeDefinitionMap.get( basicJavaType.getTypeName() ); } @Override @@ -72,12 +72,14 @@ public TypeDefinitionRegistry register(TypeDefinition typeDefinition, Duplicatio throw new IllegalArgumentException( "TypeDefinition to register cannot define null #typeImplementorClass" ); } - if ( !isEmpty( typeDefinition.getName() ) ) { - register( typeDefinition.getName(), typeDefinition, duplicationStrategy ); + final String typeDefinitionName = typeDefinition.getName(); + if ( !isEmpty( typeDefinitionName ) ) { + register( typeDefinitionName, typeDefinition, duplicationStrategy ); } - if ( typeDefinition.getRegistrationKeys() != null ) { - for ( String registrationKey : typeDefinition.getRegistrationKeys() ) { + final String[] registrationKeys = typeDefinition.getRegistrationKeys(); + if ( registrationKeys != null ) { + for ( String registrationKey : registrationKeys ) { register( registrationKey, typeDefinition, duplicationStrategy ); } } @@ -92,10 +94,10 @@ private void register(String name, TypeDefinition typeDefinition, DuplicationStr } } else { - final TypeDefinition existing = typeDefinitionMap.put( name, typeDefinition ); + final var existing = typeDefinitionMap.put( name, typeDefinition ); if ( existing != null && existing != typeDefinition ) { if ( duplicationStrategy == DuplicationStrategy.OVERWRITE ) { - LOG.debugf( "Overwrote existing registration [%s] for type definition.", name ); + BOOT_LOGGER.overwroteExistingRegistrationForTypeDefinition( name ); } else { throw new IllegalArgumentException( diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/JaxbLogger.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/JaxbLogger.java index b8835bfc7638..8426c4f9b8b6 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/JaxbLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/JaxbLogger.java @@ -8,13 +8,24 @@ import org.hibernate.boot.BootLogging; import org.hibernate.internal.log.SubSystemLogging; +import org.hibernate.type.SerializationException; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; +import java.io.File; +import java.io.FileNotFoundException; import java.lang.invoke.MethodHandles; +import static org.jboss.logging.Logger.Level.DEBUG; +import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.TRACE; +import static org.jboss.logging.Logger.Level.WARN; + /** * @author Steve Ebersole */ @@ -28,4 +39,77 @@ public interface JaxbLogger extends BasicLogger { String LOGGER_NAME = BootLogging.NAME + ".jaxb"; JaxbLogger JAXB_LOGGER = Logger.getMessageLogger( MethodHandles.lookup(), JaxbLogger.class, LOGGER_NAME ); + + @LogMessage(level = DEBUG) + @Message(id = 90005501, value = "Unable to close StAX reader") + void unableToCloseStaxReader(@Cause Throwable e); + + @LogMessage(level = TRACE) + @Message(id = 90005502, value = "Performing JAXB binding of hbm.xml document: %s") + void performingJaxbBindingOfHbmXmlDocument(String origin); + + @LogMessage(level = TRACE) + @Message(id = 90005503, value = "Performing JAXB binding of orm.xml document: %s") + void performingJaxbBindingOfOrmXmlDocument(String origin); + + @LogMessage(level = INFO) + @Message(id = 90005504, value = "Reading mappings from file: %s") + void readingMappingsFromFile(String path); + + @LogMessage(level = INFO) + @Message(id = 90005505, value = "Reading mappings from cache file: %s") + void readingCachedMappings(File cachedFile); + + @LogMessage(level = WARN) + @Message(id = 90005506, value = "Could not deserialize cache file [%s]: %s") + void unableToDeserializeCache(String path, SerializationException error); + + @LogMessage(level = WARN) + @Message(id = 90005507, value = "I/O reported error writing cached file: [%s]: %s") + void unableToWriteCachedFile(String path, String message); + + @LogMessage(level = WARN) + @Message(id = 90005508, value = "Could not update cached file timestamp: [%s]") + @SuppressWarnings("unused") + void unableToUpdateCachedFileTimestamp(String path); + + @LogMessage(level = WARN) + @Message(id = 90005509, value = "I/O reported cached file could not be found: [%s]: %s") + void cachedFileNotFound(String path, FileNotFoundException error); + + @LogMessage(level = INFO) + @Message(id = 90005510, value = "Omitting cached file [%s] as the mapping file is newer") + void cachedFileObsolete(File cachedFile); + + @LogMessage(level = TRACE) + @Message(id = 90005511, value = "Writing cache file for: %s to: %s") + void writingCacheFile(String xmlPath, String serPath); + + @LogMessage(level = DEBUG) + @Message(id = 90005512, value = "Problem closing schema stream [%s]") + void problemClosingSchemaStream(String details); + + @LogMessage(level = TRACE) + @Message(id = 90005513, value = "In resolveEntity(%s, %s, %s, %s)") + void resolveEntityInvocation(String publicID, String systemID, String baseURI, String namespace); + + @LogMessage(level = TRACE) + @Message(id = 90005514, value = "Interpreting namespace: %s") + void interpretingNamespace(String namespace); + + @LogMessage(level = TRACE) + @Message(id = 90005515, value = "Checking public/system identifiers `%s`/`%s` as DTD references") + void checkingDtdReferences(String publicID, String systemID); + + @LogMessage(level = TRACE) + @Message(id = 90005516, value = "Recognized 'classpath:' identifier; attempting to resolve on classpath [%s]") + void recognizedClasspathIdentifierAttemptingToResolve(String systemID); + + @LogMessage(level = TRACE) + @Message(id = 90005517, value = "Unable to resolve [%s] on classpath") + void unableToResolveOnClasspath(String systemID); + + @LogMessage(level = TRACE) + @Message(id = 90005518, value = "Resolved [%s] on classpath") + void resolvedOnClasspath(String systemID); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java index 472f6492dd3e..98d232b88e0f 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/AbstractBinder.java @@ -22,17 +22,17 @@ import org.hibernate.boot.jaxb.spi.Binding; import org.hibernate.internal.util.StringHelper; -import org.jboss.logging.Logger; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; + /** * @author Steve Ebersole */ public abstract class AbstractBinder implements Binder { - private static final Logger LOG = Logger.getLogger( AbstractBinder.class ); private final LocalXmlResourceResolver xmlResourceResolver; @@ -53,7 +53,7 @@ public Binding bind(InputStream stream, Origin origin) { eventReader.close(); } catch (XMLStreamException e) { - LOG.debug( "Unable to close StAX reader", e ); + JAXB_LOGGER.unableToCloseStaxReader( e ); } } } @@ -98,7 +98,7 @@ private Binding doBind(XMLEventReader eventReader, Origin origi eventReader.close(); } catch (Exception e) { - LOG.debug( "Unable to close StAX reader", e ); + JAXB_LOGGER.unableToCloseStaxReader( e ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java index f32e19277329..0891dbca723d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/CacheableFileXmlSource.java @@ -17,7 +17,7 @@ import java.io.FileNotFoundException; import java.io.FileOutputStream; -import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; /** * Support for creating a mapping {@linkplain Binding binding} from "cached" XML files. @@ -73,17 +73,17 @@ public static Binding fromCacheableFile return new Binding<>( readSerFile( serFile ), origin ); } catch ( SerializationException e ) { - BOOT_LOGGER.unableToDeserializeCache( serFile.getName(), e ); + JAXB_LOGGER.unableToDeserializeCache( serFile.getName(), e ); } catch ( FileNotFoundException e ) { - BOOT_LOGGER.cachedFileNotFound( serFile.getName(), e ); + JAXB_LOGGER.cachedFileNotFound( serFile.getName(), e ); } } else { - BOOT_LOGGER.cachedFileObsolete( serFile ); + JAXB_LOGGER.cachedFileObsolete( serFile ); } - BOOT_LOGGER.readingMappingsFromFile( xmlFile.getPath() ); + JAXB_LOGGER.readingMappingsFromFile( xmlFile.getPath() ); final Binding binding = FileXmlSource.fromFile( xmlFile, binder ); writeSerFile( binding.getRoot(), xmlFile, serFile ); @@ -124,7 +124,7 @@ public static File determineCachedFile(File xmlFile, File serDirectory) { } private static T readSerFile(File serFile) throws SerializationException, FileNotFoundException { - BOOT_LOGGER.readingCachedMappings( serFile ); + JAXB_LOGGER.readingCachedMappings( serFile ); return SerializationHelper.deserialize( new FileInputStream( serFile ) ); } @@ -133,17 +133,17 @@ private static void writeSerFile( File xmlFile, File serFile) { try ( var fileOutputStream = new FileOutputStream( serFile ) ) { - if ( BOOT_LOGGER.isTraceEnabled() ) { - BOOT_LOGGER.writingCacheFile( xmlFile.getAbsolutePath(), serFile.getAbsolutePath() ); + if ( JAXB_LOGGER.isTraceEnabled() ) { + JAXB_LOGGER.writingCacheFile( xmlFile.getAbsolutePath(), serFile.getAbsolutePath() ); } SerializationHelper.serialize( jaxbModel, fileOutputStream ); final boolean success = serFile.setLastModified( System.currentTimeMillis() ); if ( !success ) { - BOOT_LOGGER.unableToUpdateCachedFileTimestamp( serFile.getAbsolutePath() ); + JAXB_LOGGER.unableToUpdateCachedFileTimestamp( serFile.getAbsolutePath() ); } } catch ( Exception e ) { - BOOT_LOGGER.unableToWriteCachedFile( serFile.getAbsolutePath(), e.getMessage() ); + JAXB_LOGGER.unableToWriteCachedFile( serFile.getAbsolutePath(), e.getMessage() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java index 86fada8b4732..866221ed23ab 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/MappingBinder.java @@ -24,18 +24,18 @@ import org.hibernate.boot.jaxb.spi.JaxbBindableMappingDescriptor; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.xsd.MappingXsdSupport; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.internal.util.config.ConfigurationException; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.spi.ServiceRegistryImplementor; -import org.jboss.logging.Logger; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import org.checkerframework.checker.nullness.qual.Nullable; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; +import static org.hibernate.cfg.AvailableSettings.VALIDATE_XML; import static org.hibernate.engine.config.spi.StandardConverters.BOOLEAN; /** @@ -45,7 +45,6 @@ * @author Steve Ebersole */ public class MappingBinder extends AbstractBinder { - private static final Logger LOG = Logger.getLogger( MappingBinder.class ); private final XMLEventFactory xmlEventFactory = XMLEventFactory.newInstance(); @@ -96,21 +95,20 @@ private MappingBinder( public MappingBinder( ResourceStreamLocator resourceStreamLocator, @Nullable Function settingsAccess) { - super( resourceStreamLocator == null ? MappingBinder.class.getClassLoader()::getResourceAsStream : resourceStreamLocator ); + super( resourceStreamLocator == null + ? MappingBinder.class.getClassLoader()::getResourceAsStream + : resourceStreamLocator ); if ( settingsAccess == null ) { this.optionsAccess = () -> VALIDATING; } else { - this.optionsAccess = () -> new Options() { - @Override - public boolean validateMappings() { - final Object setting = settingsAccess.apply( AvailableSettings.VALIDATE_XML ); - if ( setting == null ) { - return false; - } - return BOOLEAN.convert( setting ); + this.optionsAccess = () -> (Options) () -> { + final Object setting = settingsAccess.apply( VALIDATE_XML ); + if ( setting == null ) { + return false; } + return BOOLEAN.convert( setting ); }; } } @@ -119,7 +117,7 @@ public MappingBinder(ServiceRegistry serviceRegistry) { this( serviceRegistry.getService( ClassLoaderService.class ), (settingName) -> { - final ConfigurationService configurationService = + final var configurationService = serviceRegistry instanceof ServiceRegistryImplementor serviceRegistryImplementor ? serviceRegistryImplementor.fromRegistryOrChildren( ConfigurationService.class ) : serviceRegistry.getService( ConfigurationService.class ); @@ -163,13 +161,9 @@ protected Binding doBind( Origin origin) { final String rootElementLocalName = rootElementStartEvent.getName().getLocalPart(); if ( "hibernate-mapping".equals( rootElementLocalName ) ) { - if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Performing JAXB binding of hbm.xml document: %s", origin.toString() ); - } - - final XMLEventReader hbmReader = new HbmEventReader( staxEventReader, xmlEventFactory ); - final JaxbHbmHibernateMapping hbmBindings = jaxb( - hbmReader, + JAXB_LOGGER.performingJaxbBindingOfHbmXmlDocument( origin.toString() ); + final var hbmBindings = jaxb( + new HbmEventReader( staxEventReader, xmlEventFactory ), MappingXsdSupport.INSTANCE.hbmXsd().getSchema(), hbmJaxbContext(), origin @@ -181,11 +175,9 @@ protected Binding doBind( else { assert "entity-mappings".equals( rootElementLocalName ); try { - LOG.tracef( "Performing JAXB binding of orm.xml document: %s", origin.toString() ); - - final XMLEventReader reader = new MappingEventReader( staxEventReader, xmlEventFactory ); - final JaxbEntityMappingsImpl bindingRoot = jaxb( - reader, + JAXB_LOGGER.performingJaxbBindingOfOrmXmlDocument( origin.toString() ); + final var bindingRoot = jaxb( + new MappingEventReader( staxEventReader, xmlEventFactory ), MappingXsdSupport.latestDescriptor().getSchema(), mappingJaxbContext(), origin diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalSchemaLocator.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalSchemaLocator.java index 2e64663c309c..bf284d4cbd70 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalSchemaLocator.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalSchemaLocator.java @@ -5,14 +5,13 @@ package org.hibernate.boot.jaxb.internal.stax; import java.io.IOException; -import java.io.InputStream; import java.net.URL; -import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; -import org.jboss.logging.Logger; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; /** * Helper for resolving XML Schema references locally. @@ -22,7 +21,6 @@ * @author Steve Ebersole */ public class LocalSchemaLocator { - private static final Logger LOG = Logger.getLogger( LocalSchemaLocator.class ); private LocalSchemaLocator() { // Disallow direct instantiation @@ -35,7 +33,7 @@ private LocalSchemaLocator() { * */ public static URL resolveLocalSchemaUrl(String schemaResourceName) { - URL url = LocalSchemaLocator.class.getClassLoader().getResource( schemaResourceName ); + final URL url = LocalSchemaLocator.class.getClassLoader().getResource( schemaResourceName ); if ( url == null ) { throw new XmlInfrastructureException( "Unable to locate schema [" + schemaResourceName + "] via classpath" ); } @@ -48,11 +46,10 @@ public static Schema resolveLocalSchema(String schemaName){ public static Schema resolveLocalSchema(URL schemaUrl) { try { - InputStream schemaStream = schemaUrl.openStream(); + final var schemaStream = schemaUrl.openStream(); try { - StreamSource source = new StreamSource(schemaUrl.openStream()); - SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); - return schemaFactory.newSchema(source); + return SchemaFactory.newInstance( W3C_XML_SCHEMA_NS_URI ) + .newSchema( new StreamSource( schemaUrl.openStream() ) ); } catch ( Exception e ) { throw new XmlInfrastructureException( "Unable to load schema [" + schemaUrl.toExternalForm() + "]", e ); @@ -62,7 +59,7 @@ public static Schema resolveLocalSchema(URL schemaUrl) { schemaStream.close(); } catch ( IOException e ) { - LOG.debugf( "Problem closing schema stream - %s", e.toString() ); + JAXB_LOGGER.problemClosingSchemaStream( e.toString() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java index 03f5b713a7b3..1a8684d5b1f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/LocalXmlResourceResolver.java @@ -14,15 +14,13 @@ import org.hibernate.boot.xsd.MappingXsdSupport; import org.hibernate.boot.xsd.XsdDescriptor; -import org.jboss.logging.Logger; - +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; import static org.hibernate.internal.log.DeprecationLogger.DEPRECATION_LOGGER; /** * @author Steve Ebersole */ public class LocalXmlResourceResolver implements javax.xml.stream.XMLResolver { - private static final Logger LOG = Logger.getLogger( LocalXmlResourceResolver.class ); public static final String CLASSPATH_EXTENSION_URL_BASE = "classpath://"; @@ -34,10 +32,10 @@ public LocalXmlResourceResolver(ResourceStreamLocator resourceStreamLocator) { @Override public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { - LOG.tracef( "In resolveEntity(%s, %s, %s, %s)", publicID, systemID, baseURI, namespace ); + JAXB_LOGGER.resolveEntityInvocation( publicID, systemID, baseURI, namespace ); if ( namespace != null ) { - LOG.tracef( "Interpreting namespace: %s", namespace ); + JAXB_LOGGER.interpretingNamespace( namespace ); if ( MappingXsdSupport.latestDescriptor().getNamespaceUri().matches( namespace ) ) { return openUrlStream( MappingXsdSupport.latestDescriptor() ); } @@ -84,7 +82,7 @@ else if ( ConfigXsdSupport.cfgXsd().getNamespaceUri().matches( namespace ) ) { } if ( publicID != null || systemID != null ) { - LOG.tracef( "Checking public/system identifiers `%s`/`%s` as DTD references", publicID, systemID ); + JAXB_LOGGER.checkingDtdReferences( publicID, systemID ); if ( MAPPING_DTD.matches( publicID, systemID ) ) { return openUrlStream( MAPPING_DTD.localSchemaUrl ); @@ -116,15 +114,15 @@ else if ( ConfigXsdSupport.cfgXsd().getNamespaceUri().matches( namespace ) ) { if ( systemID != null ) { // technically, "classpath://..." identifiers should only be declared as SYSTEM identifiers if ( systemID.startsWith( CLASSPATH_EXTENSION_URL_BASE ) ) { - LOG.tracef( "Recognized 'classpath:' identifier; attempting to resolve on classpath [%s]", systemID ); + JAXB_LOGGER.recognizedClasspathIdentifierAttemptingToResolve( systemID ); final String path = systemID.substring( CLASSPATH_EXTENSION_URL_BASE.length() ); // todo : for this to truly work consistently, we need access to ClassLoaderService final InputStream stream = resolveInLocalNamespace( path ); if ( stream == null ) { - LOG.tracef( "Unable to resolve [%s] on classpath", systemID ); + JAXB_LOGGER.unableToResolveOnClasspath( systemID ); } else { - LOG.tracef( "Resolved [%s] on classpath", systemID ); + JAXB_LOGGER.resolvedOnClasspath( systemID ); } return stream; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java b/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java index f655469634b2..7b83063a49b2 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/convert/internal/AttributeConverterManager.java @@ -22,11 +22,10 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.models.spi.MemberDetails; -import org.jboss.logging.Logger; -import com.fasterxml.classmate.ResolvedType; import static java.util.Collections.emptyList; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; import static org.hibernate.boot.model.convert.internal.ConverterHelper.resolveAttributeType; import static org.hibernate.boot.model.convert.internal.ConverterHelper.resolveConverterClassParamTypes; import static org.hibernate.internal.util.StringHelper.join; @@ -38,7 +37,6 @@ * @author Steve Ebersole */ public class AttributeConverterManager implements ConverterAutoApplyHandler { - private static final Logger LOG = Logger.getLogger( AttributeConverterManager.class ); private Map, ConverterDescriptor> attributeConverterDescriptorsByClass; private Map, RegisteredConversion> registeredConversionsByDomainType; @@ -48,19 +46,18 @@ public RegisteredConversion findRegisteredConversion(Class domainType) { } public void addConverter(ConverterDescriptor descriptor) { - if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Registering AttributeConverter '%s'", - descriptor.getAttributeConverterClass().getName() ); + final var converterClass = descriptor.getAttributeConverterClass(); + if ( BOOT_LOGGER.isTraceEnabled() ) { + BOOT_LOGGER.registeringAttributeConverter( converterClass.getName() ); } if ( registeredConversionsByDomainType != null ) { final Class domainType = descriptor.getDomainValueResolvedType().getErasedType(); - final RegisteredConversion registeredConversion = registeredConversionsByDomainType.get( domainType ); + final var registeredConversion = registeredConversionsByDomainType.get( domainType ); if ( registeredConversion != null ) { // we can skip registering the converter, the RegisteredConversion will always take precedence - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Skipping registration of discovered AttributeConverter '%s' for auto-apply", - descriptor.getAttributeConverterClass().getName() ); + if ( BOOT_LOGGER.isDebugEnabled() ) { + BOOT_LOGGER.skippingRegistrationAttributeConverterForAutoApply( converterClass.getName() ); } return; } @@ -70,17 +67,13 @@ public void addConverter(ConverterDescriptor descriptor) { attributeConverterDescriptorsByClass = new ConcurrentHashMap<>(); } - final Object old = attributeConverterDescriptorsByClass.put( - descriptor.getAttributeConverterClass(), - descriptor - ); - + final Object old = attributeConverterDescriptorsByClass.put( converterClass, descriptor ); if ( old != null ) { throw new HibernateException( String.format( Locale.ENGLISH, "AttributeConverter class [%s] registered multiple times", - descriptor.getAttributeConverterClass() + converterClass ) ); } @@ -92,46 +85,40 @@ public void addRegistration(RegisteredConversion conversion, BootstrapContext co } final Class domainType = getDomainType( conversion, context ); + checkNotOverriding( conversion, domainType ); + // See if we have a matching entry in attributeConverterDescriptorsByClass. + // If so, remove it. The conversion being registered will always take precedence. + if ( attributeConverterDescriptorsByClass != null ) { + final var removed = attributeConverterDescriptorsByClass.remove( conversion.getConverterType() ); + if ( removed != null && BOOT_LOGGER.isDebugEnabled() ) { + BOOT_LOGGER.removedPotentiallyAutoApplicableConverterDueToRegistration( + removed.getAttributeConverterClass().getName() ); + } + } + registeredConversionsByDomainType.put( domainType, conversion ); + } + private void checkNotOverriding(RegisteredConversion conversion, Class domainType) { // make sure we are not overriding a previous conversion registration - final RegisteredConversion existingRegistration = - registeredConversionsByDomainType.get( domainType ); + final var existingRegistration = registeredConversionsByDomainType.get( domainType ); if ( existingRegistration != null ) { + final String converterTypeName = conversion.getConverterType().getName(); if ( !conversion.equals( existingRegistration ) ) { throw new AnnotationException( "Conflicting '@ConverterRegistration' descriptors for attribute converter '" - + conversion.getConverterType().getName() + "'" ); + + converterTypeName + "'" ); } else { - if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Skipping duplicate '@ConverterRegistration' for '%s'", - conversion.getConverterType().getName() ); - } + BOOT_LOGGER.skippingDuplicateConverterRegistration( converterTypeName ); } } - - // see if we have a matching entry in `attributeConverterDescriptorsByClass`. - // if so, remove it. The conversion being registered will always take precedence - if ( attributeConverterDescriptorsByClass != null ) { - final var removed = attributeConverterDescriptorsByClass.remove( conversion.getConverterType() ); - if ( removed != null && LOG.isDebugEnabled() ) { - LOG.debugf( "Removed potentially auto-applicable converter '%s' due to @ConverterRegistration", - removed.getAttributeConverterClass().getName() ); - } - } - - registeredConversionsByDomainType.put( domainType, conversion ); } private static Class getDomainType(RegisteredConversion conversion, BootstrapContext context) { - if ( conversion.getExplicitDomainType().equals( void.class ) ) { - // the registration did not define an explicit domain-type, so inspect the converter - final List converterParamTypes = - resolveConverterClassParamTypes( conversion.getConverterType(), context.getClassmateContext() ); - return converterParamTypes.get( 0 ).getErasedType(); - } - else { - return conversion.getExplicitDomainType(); - } + // the registration did not define an explicit domain-type, so inspect the converter + return conversion.getExplicitDomainType().equals( void.class ) + ? resolveConverterClassParamTypes( conversion.getConverterType(), context.getClassmateContext() ) + .get( 0 ).getErasedType() + : conversion.getExplicitDomainType(); } private Collection> converterDescriptors() { @@ -174,8 +161,8 @@ private ConverterDescriptor locateMatchingConverter( MetadataBuildingContext context) { if ( registeredConversionsByDomainType != null ) { // we had registered conversions - see if any of them match and, if so, use that conversion - final ResolvedType resolveAttributeType = resolveAttributeType( memberDetails, context ); - final RegisteredConversion registrationForDomainType = + final var resolveAttributeType = resolveAttributeType( memberDetails, context ); + final var registrationForDomainType = registeredConversionsByDomainType.get( resolveAttributeType.getErasedType() ); if ( registrationForDomainType != null ) { return registrationForDomainType.isAutoApply() @@ -226,10 +213,9 @@ private List> getMatches( Function> matcher) { final List> matches = new ArrayList<>(); - for ( ConverterDescriptor descriptor : converterDescriptors() ) { - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Checking auto-apply AttributeConverter [%s] (domain-type=%s) for match against %s : %s.%s (type=%s)", + for ( var descriptor : converterDescriptors() ) { + if ( BOOT_LOGGER.isTraceEnabled() ) { + BOOT_LOGGER.checkingAutoApplyAttributeConverter( descriptor.getAttributeConverterClass().getName(), descriptor.getDomainValueResolvedType().getSignature(), conversionSite.getSiteDescriptor(), @@ -238,8 +224,7 @@ private List> getMatches( memberDetails.getType().getName() ); } - final ConverterDescriptor match = - matcher.apply( descriptor.getAutoApplyDescriptor() ); + final var match = matcher.apply( descriptor.getAutoApplyDescriptor() ); if ( match != null ) { matches.add( descriptor ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java index 6afbdab51448..01a60c80ce20 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java @@ -60,8 +60,8 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co parameterResolvers = new HashMap<>(); for ( var explicitParameter : explicitParameters ) { final String parameterName = explicitParameter.name(); - final Class typeClassDetails = explicitParameter.type(); - final JdbcMapping jdbcMapping = resolveFilterParamType( typeClassDetails, context ); + final var typeClassDetails = explicitParameter.type(); + final var jdbcMapping = resolveFilterParamType( typeClassDetails, context ); if ( jdbcMapping == null ) { throw new MappingException( String.format( @@ -91,9 +91,7 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co parameterResolvers ); - if ( BOOT_LOGGER.isTraceEnabled() ) { -BOOT_LOGGER.bindingFilterDefinition( filterDefinition.getFilterName() ); - } + BOOT_LOGGER.bindingFilterDefinition( filterDefinition.getFilterName() ); context.getMetadataCollector().addFilterDefinition( filterDefinition ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java index fb6590a04bb2..2b32c9d27c5f 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/EntityHierarchyBuilder.java @@ -12,15 +12,14 @@ import org.hibernate.HibernateException; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmDiscriminatorSubclassEntityType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmEntityBaseDefinition; -import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmHibernateMapping; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmJoinedSubclassEntityType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmRootEntityType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmSubclassEntityBaseDefinition; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmUnionSubclassEntityType; import org.hibernate.boot.model.source.spi.EntitySource; -import org.hibernate.internal.util.StringHelper; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.internal.util.StringHelper.isNotEmpty; /** * Helper for dealing with entity inheritance hierarchies in {@code hbm.xml} @@ -39,7 +38,6 @@ * @author Steve Ebersole */ public class EntityHierarchyBuilder { - private static final Logger LOG = Logger.getLogger( EntityHierarchyBuilder.class ); private final List entityHierarchyList = new ArrayList<>(); @@ -58,11 +56,10 @@ public EntityHierarchyBuilder() { */ public List buildHierarchies() throws HibernateException { if ( toBeLinkedQueue != null && !toBeLinkedQueue.isEmpty() ) { - if ( LOG.isDebugEnabled() ) { + if ( BOOT_LOGGER.isDebugEnabled() ) { for ( var waitingListEntry : toBeLinkedQueue.entrySet() ) { - for ( ExtendsQueueEntry waitingEntry : waitingListEntry.getValue() ) { - LOG.debugf( - "Entity supertype named as extends [%s] for subclass [%s:%s] not found", + for ( var waitingEntry : waitingListEntry.getValue() ) { + BOOT_LOGGER.entitySupertypeExtendsNotFound( waitingListEntry.getKey(), waitingEntry.sourceMappingDocument.getOrigin(), waitingEntry.sourceMappingDocument.determineEntityName( waitingEntry.jaxbSubEntityMapping ) @@ -84,40 +81,32 @@ public List buildHierarchies() throws HibernateExcept * @param mappingDocument The {@code hbm.xml} document to index */ public void indexMappingDocument(MappingDocument mappingDocument) { - LOG.tracef( "Indexing mapping document [%s] for purpose of building entity hierarchy ordering", mappingDocument.getOrigin() ); - final JaxbHbmHibernateMapping mappingBinding = mappingDocument.getDocumentRoot(); + BOOT_LOGGER.indexingMappingDocumentForHierarchyOrdering( String.valueOf( mappingDocument.getOrigin() ) ); + final var mappingBinding = mappingDocument.getDocumentRoot(); // iterate all root class definitions at the hibernate-mapping level - for ( JaxbHbmRootEntityType jaxbRootEntity : mappingBinding.getClazz() ) { - + for ( var jaxbRootEntity : mappingBinding.getClazz() ) { // we can immediately handle elements in terms of creating the hierarchy entry - final RootEntitySourceImpl rootEntitySource = new RootEntitySourceImpl( mappingDocument, jaxbRootEntity ); + final var rootEntitySource = new RootEntitySourceImpl( mappingDocument, jaxbRootEntity ); entitySourceByNameMap.put( rootEntitySource.getEntityNamingSource().getEntityName(), rootEntitySource ); - - final EntityHierarchySourceImpl hierarchy = new EntityHierarchySourceImpl( - rootEntitySource, - mappingDocument - ); - entityHierarchyList.add( hierarchy ); - + entityHierarchyList.add( new EntityHierarchySourceImpl( rootEntitySource, mappingDocument ) ); linkAnyWaiting( mappingDocument, rootEntitySource ); - // process any of its nested sub-entity definitions processRootEntitySubEntityElements( mappingDocument, jaxbRootEntity, rootEntitySource ); } // iterate all discriminator-based subclass definitions at the hibernate-mapping level - for ( JaxbHbmDiscriminatorSubclassEntityType discriminatorSubclassEntityBinding : mappingBinding.getSubclass() ) { + for ( var discriminatorSubclassEntityBinding : mappingBinding.getSubclass() ) { processTopLevelSubClassBinding( mappingDocument, discriminatorSubclassEntityBinding ); } // iterate all joined-subclass definitions at the hibernate-mapping level - for ( JaxbHbmJoinedSubclassEntityType joinedSubclassEntityBinding : mappingBinding.getJoinedSubclass() ) { + for ( var joinedSubclassEntityBinding : mappingBinding.getJoinedSubclass() ) { processTopLevelSubClassBinding( mappingDocument, joinedSubclassEntityBinding ); } // iterate all union-subclass definitions at the hibernate-mapping level - for ( JaxbHbmUnionSubclassEntityType unionSubclassEntityBinding : mappingBinding.getUnionSubclass() ) { + for ( var unionSubclassEntityBinding : mappingBinding.getUnionSubclass() ) { processTopLevelSubClassBinding( mappingDocument, unionSubclassEntityBinding ); } } @@ -152,8 +141,8 @@ private void processElements( MappingDocument mappingDocument, List nestedSubEntityList, AbstractEntitySourceImpl container) { - for ( final JaxbHbmSubclassEntityBaseDefinition jaxbSubEntity : nestedSubEntityList ) { - final SubclassEntitySourceImpl subClassEntitySource = createSubClassEntitySource( + for ( final var jaxbSubEntity : nestedSubEntityList ) { + final var subClassEntitySource = createSubClassEntitySource( mappingDocument, jaxbSubEntity, container @@ -164,8 +153,7 @@ private void processElements( ); container.add( subClassEntitySource ); linkAnyWaiting( mappingDocument, subClassEntitySource ); - - // Re-run the sub element to handle subclasses within the subclass. + // Re-run the subelement to handle subclasses within the subclass. processSubEntityElements( mappingDocument, jaxbSubEntity, subClassEntitySource ); } } @@ -174,23 +162,15 @@ private SubclassEntitySourceImpl createSubClassEntitySource( MappingDocument mappingDocument, JaxbHbmSubclassEntityBaseDefinition jaxbSubEntity, EntitySource superEntity) { - if (jaxbSubEntity instanceof JaxbHbmJoinedSubclassEntityType) { - return new JoinedSubclassEntitySourceImpl( - mappingDocument, - JaxbHbmJoinedSubclassEntityType.class.cast( jaxbSubEntity ), - superEntity - ); - } - else { - return new SubclassEntitySourceImpl( mappingDocument, jaxbSubEntity, superEntity ); - } + return jaxbSubEntity instanceof JaxbHbmJoinedSubclassEntityType jaxbJoinedSubclass + ? new JoinedSubclassEntitySourceImpl( mappingDocument, jaxbJoinedSubclass, superEntity ) + : new SubclassEntitySourceImpl( mappingDocument, jaxbSubEntity, superEntity ); } private void processTopLevelSubClassBinding( MappingDocument mappingDocument, JaxbHbmSubclassEntityBaseDefinition jaxbSubEntityMapping) { - final AbstractEntitySourceImpl entityItExtends = locateExtendedEntitySource( mappingDocument, jaxbSubEntityMapping ); - + final var entityItExtends = locateExtendedEntitySource( mappingDocument, jaxbSubEntityMapping ); if ( entityItExtends == null ) { // we have not seen its declared super-type yet, add it to the queue to be linked up // later when (if) we do @@ -198,17 +178,15 @@ private void processTopLevelSubClassBinding( } else { // we have seen its super-type already - final SubclassEntitySourceImpl subEntitySource = createSubClassEntitySource( + final var subEntitySource = createSubClassEntitySource( mappingDocument, jaxbSubEntityMapping, entityItExtends ); entitySourceByNameMap.put( subEntitySource.getEntityNamingSource().getEntityName(), subEntitySource ); entityItExtends.add( subEntitySource ); - // this may have been a "middle type". So link any sub entities that may be waiting on it linkAnyWaiting( mappingDocument, subEntitySource ); - processSubEntityElements( mappingDocument, jaxbSubEntityMapping, subEntitySource ); } } @@ -216,17 +194,15 @@ private void processTopLevelSubClassBinding( private AbstractEntitySourceImpl locateExtendedEntitySource( MappingDocument mappingDocument, JaxbHbmSubclassEntityBaseDefinition jaxbSubEntityMapping) { - // NOTE : extends may refer to either an entity-name or a class-name, we need to check each - - // first check using entity-name - AbstractEntitySourceImpl entityItExtends = entitySourceByNameMap.get( jaxbSubEntityMapping.getExtends() ); + // NOTE: extends may refer to either an entity-name or a class-name, we need to check each + // first check using the entity name + var entityItExtends = entitySourceByNameMap.get( jaxbSubEntityMapping.getExtends() ); if ( entityItExtends == null ) { - // next, check using class name + // next, check using the class name entityItExtends = entitySourceByNameMap.get( mappingDocument.qualifyClassName( jaxbSubEntityMapping.getExtends() ) ); } - return entityItExtends; } @@ -253,31 +229,29 @@ private void addToToBeLinkedQueue( private void linkAnyWaiting( MappingDocument mappingDocument, AbstractEntitySourceImpl entitySource) { - if ( toBeLinkedQueue == null ) { - return; - } - - List waitingList = toBeLinkedQueue.remove( entitySource.jaxbEntityMapping().getEntityName() ); - if ( waitingList != null ) { - processWaitingSubEntityMappings( entitySource, waitingList ); - waitingList.clear(); - } - - if ( StringHelper.isNotEmpty( entitySource.jaxbEntityMapping().getName() ) ) { - final String entityClassName = entitySource.jaxbEntityMapping().getName(); - waitingList = toBeLinkedQueue.remove( entityClassName ); + if ( toBeLinkedQueue != null ) { + var waitingList = toBeLinkedQueue.remove( entitySource.jaxbEntityMapping().getEntityName() ); if ( waitingList != null ) { processWaitingSubEntityMappings( entitySource, waitingList ); waitingList.clear(); } - final String qualifiedEntityClassName = mappingDocument.qualifyClassName( entityClassName ); - if ( !entityClassName.equals( qualifiedEntityClassName ) ) { - waitingList = toBeLinkedQueue.remove( qualifiedEntityClassName ); + if ( isNotEmpty( entitySource.jaxbEntityMapping().getName() ) ) { + final String entityClassName = entitySource.jaxbEntityMapping().getName(); + waitingList = toBeLinkedQueue.remove( entityClassName ); if ( waitingList != null ) { processWaitingSubEntityMappings( entitySource, waitingList ); waitingList.clear(); } + + final String qualifiedEntityClassName = mappingDocument.qualifyClassName( entityClassName ); + if ( !entityClassName.equals( qualifiedEntityClassName ) ) { + waitingList = toBeLinkedQueue.remove( qualifiedEntityClassName ); + if ( waitingList != null ) { + processWaitingSubEntityMappings( entitySource, waitingList ); + waitingList.clear(); + } + } } } } @@ -285,19 +259,16 @@ private void linkAnyWaiting( private void processWaitingSubEntityMappings( AbstractEntitySourceImpl entitySource, List waitingList) { - for ( ExtendsQueueEntry entry : waitingList ) { - final SubclassEntitySourceImpl subEntitySource = createSubClassEntitySource( + for ( var entry : waitingList ) { + final var subEntitySource = createSubClassEntitySource( entry.sourceMappingDocument, entry.jaxbSubEntityMapping, entitySource ); - entitySourceByNameMap.put( subEntitySource.getEntityNamingSource().getEntityName(), subEntitySource ); entitySource.add( subEntitySource ); - // this may have been a "middle type". So link any sub entities that may be waiting on it linkAnyWaiting( entry.sourceMappingDocument, subEntitySource ); - processSubEntityElements( entry.sourceMappingDocument, entry.jaxbSubEntityMapping, subEntitySource ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java index 75f2f68df88d..bc25fd73670c 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FetchProfileBinder.java @@ -5,19 +5,19 @@ package org.hibernate.boot.model.source.internal.hbm; import org.hibernate.annotations.FetchMode; +import org.hibernate.boot.MappingException; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmFetchProfileType; import org.hibernate.mapping.FetchProfile; import org.hibernate.mapping.MetadataSource; -import org.jboss.logging.Logger; import static jakarta.persistence.FetchType.EAGER; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * @author Steve Ebersole */ public class FetchProfileBinder { - private static final Logger LOG = Logger.getLogger( FetchProfileBinder.class ); /** * Handling for a {@code } declaration. @@ -48,35 +48,50 @@ public static void processFetchProfile( HbmLocalMetadataBuildingContext context, JaxbHbmFetchProfileType fetchProfileBinding, String containingEntityName) { - FetchProfile profile = context.getMetadataCollector().getFetchProfile( fetchProfileBinding.getName() ); - if ( profile == null ) { - LOG.tracef( "Creating FetchProfile: %s", fetchProfileBinding.getName() ); - profile = new FetchProfile( fetchProfileBinding.getName(), MetadataSource.HBM ); - context.getMetadataCollector().addFetchProfile( profile ); - } - - for ( JaxbHbmFetchProfileType.JaxbHbmFetch fetchBinding : fetchProfileBinding.getFetch() ) { - String entityName = fetchBinding.getEntity(); + final var profile = fetchProfile( context, fetchProfileBinding ); + for ( var fetchBinding : fetchProfileBinding.getFetch() ) { + final String entityName = entityName( containingEntityName, fetchBinding ); if ( entityName == null ) { - entityName = containingEntityName; - } - if ( entityName == null ) { - throw new org.hibernate.boot.MappingException( + throw new MappingException( String.format( - "Unable to determine entity for fetch-profile fetch [%s:%s]", + "Unable to determine entity for fetch profile fetch [%s:%s]", profile.getName(), fetchBinding.getAssociation() ), context.getOrigin() ); } - String association = fetchBinding.getAssociation(); - profile.addFetch( new FetchProfile.Fetch(entityName, association, fetchMode(fetchBinding.getStyle().value()), EAGER ) ); + profile.addFetch( new FetchProfile.Fetch( + entityName, + fetchBinding.getAssociation(), + fetchMode( fetchBinding.getStyle().value() ), + EAGER + ) ); + } + } + + private static String entityName(String containingEntityName, JaxbHbmFetchProfileType.JaxbHbmFetch fetchBinding) { + final String entityName = fetchBinding.getEntity(); + return entityName == null ? containingEntityName : entityName; + } + + private static FetchProfile fetchProfile( + HbmLocalMetadataBuildingContext context, JaxbHbmFetchProfileType fetchProfileBinding) { + final var collector = context.getMetadataCollector(); + final var profile = collector.getFetchProfile( fetchProfileBinding.getName() ); + if ( profile == null ) { + BOOT_LOGGER.creatingFetchProfile( fetchProfileBinding.getName() ); + final var newProfile = new FetchProfile( fetchProfileBinding.getName(), MetadataSource.HBM ); + collector.addFetchProfile( newProfile ); + return newProfile; + } + else { + return profile; } } private static FetchMode fetchMode(String style) { - for ( FetchMode mode: FetchMode.values() ) { + for ( var mode: FetchMode.values() ) { if ( mode.name().equalsIgnoreCase( style ) ) { return mode; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java index 7e3f5527e943..8d6201e51602 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/FilterDefinitionBinder.java @@ -14,79 +14,71 @@ import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.jboss.logging.Logger; - import jakarta.xml.bind.JAXBElement; -import static org.hibernate.internal.util.StringHelper.isNotEmpty; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.internal.util.StringHelper.isNotBlank; /** * @author Steve Ebersole */ class FilterDefinitionBinder { - private static final Logger LOG = Logger.getLogger( FilterDefinitionBinder.class ); /** * Handling for a {@code } declaration. * * @param context Access to information relative to the mapping document containing this binding - * @param jaxbFilterDefinitionMapping The {@code } JAXB mapping + * @param filterDefinitionMapping The {@code } JAXB mapping */ - @SuppressWarnings("unchecked") static void processFilterDefinition( HbmLocalMetadataBuildingContext context, - JaxbHbmFilterDefinitionType jaxbFilterDefinitionMapping) { + JaxbHbmFilterDefinitionType filterDefinitionMapping) { Map parameterMap = null; - String condition = jaxbFilterDefinitionMapping.getCondition(); + final String condition = filterDefinitionMapping.getCondition(); + + final var collector = context.getMetadataCollector(); + final var basicTypeRegistry = collector.getTypeConfiguration().getBasicTypeRegistry(); - for ( Serializable content : jaxbFilterDefinitionMapping.getContent() ) { + for ( var content : filterDefinitionMapping.getContent() ) { if ( content instanceof String string ) { - final String contentString = string.trim(); - if ( isNotEmpty( contentString ) ) { - if ( condition != null && LOG.isDebugEnabled() ) { - LOG.debugf( - "filter-def [name=%s, origin=%s] defined multiple conditions, accepting arbitrary one", - jaxbFilterDefinitionMapping.getName(), + if ( isNotBlank( string ) ) { + if ( condition != null && BOOT_LOGGER.isDebugEnabled() ) { + BOOT_LOGGER.filterDefDefinedMultipleConditions( + filterDefinitionMapping.getName(), context.getOrigin().toString() ); } } } else { - final JaxbHbmFilterParameterType jaxbParameterMapping; - if ( content instanceof JaxbHbmFilterParameterType filterParameterType ) { - jaxbParameterMapping = filterParameterType; - } - else if ( content instanceof JAXBElement ) { - final JAXBElement jaxbElement = (JAXBElement) content; - jaxbParameterMapping = jaxbElement.getValue(); - } - else { - throw new MappingException( - "Unable to decipher filter-def content type [" + content.getClass().getName() + "]", - context.getOrigin() - ); - } - + final var parameterMapping = filterParameterType( context, content ); if ( parameterMap == null ) { parameterMap = new HashMap<>(); } - - parameterMap.put( - jaxbParameterMapping.getParameterName(), - context.getMetadataCollector().getTypeConfiguration().getBasicTypeRegistry().getRegisteredType( jaxbParameterMapping.getParameterValueTypeName() ) - ); + parameterMap.put( parameterMapping.getParameterName(), + basicTypeRegistry.getRegisteredType( parameterMapping.getParameterValueTypeName() ) ); } } - context.getMetadataCollector().addFilterDefinition( - new FilterDefinition( - jaxbFilterDefinitionMapping.getName(), - condition, - parameterMap - ) - ); + collector.addFilterDefinition( new FilterDefinition( filterDefinitionMapping.getName(), condition, parameterMap ) ); + + BOOT_LOGGER.processedFilterDefinition( filterDefinitionMapping.getName() ); + } - LOG.tracef( "Processed filter definition: %s", jaxbFilterDefinitionMapping.getName() ); + private static JaxbHbmFilterParameterType filterParameterType( + HbmLocalMetadataBuildingContext context, Serializable content) { + if ( content instanceof JaxbHbmFilterParameterType filterParameterType ) { + return filterParameterType; + } + else if ( content instanceof JAXBElement ) { + final var jaxbElement = (JAXBElement) content; + return jaxbElement.getValue(); + } + else { + throw new MappingException( + "Unable to decipher filter-def content type [" + content.getClass().getName() + "]", + context.getOrigin() + ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/HbmMetadataSourceProcessorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/HbmMetadataSourceProcessorImpl.java index 104cb63dc90e..14faa589b280 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/HbmMetadataSourceProcessorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/HbmMetadataSourceProcessorImpl.java @@ -16,7 +16,8 @@ import org.hibernate.boot.model.source.spi.MetadataSourceProcessor; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.jboss.logging.Logger; + +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * MetadataSourceProcessor implementation for processing {@code hbm.xml} mapping documents. @@ -24,7 +25,6 @@ * @author Steve Ebersole */ public class HbmMetadataSourceProcessorImpl implements MetadataSourceProcessor { - private static final Logger LOG = Logger.getLogger( HbmMetadataSourceProcessorImpl.class ); private final Collection mappingDocuments; @@ -127,9 +127,8 @@ public void processEntityHierarchies(Set processedEntityNames) { hierarchy_loop : for ( var entityHierarchy : entityHierarchies ) { for ( String entityName : entityHierarchy.getContainedEntityNames() ) { if ( processedEntityNames.contains( entityName ) ) { - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - "Skipping HBM processing of entity hierarchy [%s], as at least one entity [%s] has been processed", + if ( BOOT_LOGGER.isDebugEnabled() ) { + BOOT_LOGGER.skippingHbmProcessingOfEntityHierarchy( entityHierarchy.getRoot().getEntityNamingSource().getEntityName(), entityName ); @@ -137,7 +136,6 @@ public void processEntityHierarchies(Set processedEntityNames) { continue hierarchy_loop; } } - modelBinder.bindEntityHierarchy( entityHierarchy ); processedEntityNames.addAll( entityHierarchy.getContainedEntityNames() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java index 1ba24a845ef9..13de0acb5f69 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/IdentifierGeneratorDefinitionBinder.java @@ -7,19 +7,18 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmIdentifierGeneratorDefinitionType; import org.hibernate.boot.model.IdentifierGeneratorDefinition; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; + /** * @author Steve Ebersole */ public class IdentifierGeneratorDefinitionBinder { - private static final Logger LOG = Logger.getLogger( IdentifierGeneratorDefinitionBinder.class ); public static void processIdentifierGeneratorDefinition( HbmLocalMetadataBuildingContext context, JaxbHbmIdentifierGeneratorDefinitionType identifierGenerator) { - LOG.tracef( "Processing : %s", identifierGenerator.getName() ); - + BOOT_LOGGER.processingIdentifierGenerator( identifierGenerator.getName() ); context.getMetadataCollector().addIdentifierGenerator( new IdentifierGeneratorDefinition( identifierGenerator.getName(), diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java index b5648d670957..48066a096d24 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/MappingDocument.java @@ -24,8 +24,8 @@ import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.PersistentClass; -import org.jboss.logging.Logger; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; import static org.hibernate.boot.model.source.internal.hbm.Helper.collectToolingHints; /** @@ -34,7 +34,6 @@ * @author Steve Ebersole */ public class MappingDocument implements HbmLocalMetadataBuildingContext, MetadataSourceProcessor { - private static final Logger LOG = Logger.getLogger( MappingDocument.class ); private final JaxbHbmHibernateMapping documentRoot; private final Origin origin; @@ -181,7 +180,7 @@ public void processQueryRenames() { ? StringHelper.unqualify( name ) : renameBinding.getRename(); getMetadataCollector().addImport( rename, name ); - LOG.tracef( "Import (query rename): %s -> %s", rename, name ); + BOOT_LOGGER.importEntry( rename, name ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java index d63edb9eac01..35395711e612 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/TypeDefinitionBinder.java @@ -7,13 +7,14 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmTypeDefinitionType; import org.hibernate.boot.model.TypeDefinition; -import org.jboss.logging.Logger; + +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; +import static org.hibernate.boot.model.source.internal.hbm.ConfigParameterHelper.extractConfigParameters; /** * @author Steve Ebersole */ public class TypeDefinitionBinder { - private static final Logger LOG = Logger.getLogger( TypeDefinitionBinder.class ); /** * Handling for a {@code } declaration @@ -25,20 +26,17 @@ public static void processTypeDefinition( HbmLocalMetadataBuildingContext context, JaxbHbmTypeDefinitionType typeDefinitionBinding) { - final TypeDefinition definition = new TypeDefinition( + final var definition = new TypeDefinition( typeDefinitionBinding.getName(), context.getBootstrapContext().getClassLoaderService() .classForName( typeDefinitionBinding.getClazz() ), null, - ConfigParameterHelper.extractConfigParameters( typeDefinitionBinding ) + extractConfigParameters( typeDefinitionBinding ) ); - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Processed type definition : %s -> %s", - definition.getName(), - definition.getTypeImplementorClass().getName() - ); + if ( BOOT_LOGGER.isTraceEnabled() ) { + BOOT_LOGGER.processedTypeDefinition( definition.getName(), + definition.getTypeImplementorClass().getName() ); } context.getMetadataCollector().getTypeDefinitionRegistry().register( definition ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java index 4c6ed9e7837c..116baaf55d17 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java @@ -27,5 +27,5 @@ public interface StrategyRegistrationProvider { * * @return All {@link StrategyRegistration}s */ - Iterable getStrategyRegistrations(); + Iterable> getStrategyRegistrations(); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/AggregatedDialectSelector.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/AggregatedDialectSelector.java index 53f194da720d..ed23c9f64ab5 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/AggregatedDialectSelector.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/AggregatedDialectSelector.java @@ -17,7 +17,7 @@ public class AggregatedDialectSelector implements DialectSelector { public AggregatedDialectSelector(Iterable dialectSelectorProvider) { final List dialectSelectors = new ArrayList<>(); - for ( DialectSelector dialectSelector : dialectSelectorProvider ) { + for ( var dialectSelector : dialectSelectorProvider ) { dialectSelectors.add( dialectSelector ); } dialectSelectors.add( new DefaultDialectSelector() ); @@ -30,8 +30,8 @@ public Class resolve(final String name) { if ( name.isEmpty() ) { return null; } - for ( DialectSelector dialectSelector : dialectSelectors ) { - final Class dialectClass = dialectSelector.resolve( name ); + for ( var dialectSelector : dialectSelectors ) { + final var dialectClass = dialectSelector.resolve( name ); if ( dialectClass != null ) { return dialectClass; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java index 0f604e0f33e5..d4228f87ecf2 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java @@ -52,7 +52,8 @@ import org.hibernate.type.format.jaxb.JaxbXmlFormatMapper; import org.hibernate.type.format.jakartajson.JsonBJsonFormatMapper; -import org.jboss.logging.Logger; + +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * Builder for {@link StrategySelector} instances. @@ -60,7 +61,6 @@ * @author Steve Ebersole */ public class StrategySelectorBuilder { - private static final Logger LOG = Logger.getLogger( StrategySelectorBuilder.class ); private final List> explicitStrategyRegistrations = new ArrayList<>(); @@ -85,18 +85,15 @@ public void addExplicitStrategyRegistration(Class strategy, Class void addExplicitStrategyRegistration(StrategyRegistration strategyRegistration) { - if ( !strategyRegistration.getStrategyRole().isInterface() ) { - // not good form... - if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Registering non-interface strategy : %s", strategyRegistration.getStrategyRole().getName() ); - } + final var strategyRole = strategyRegistration.getStrategyRole(); + if ( BOOT_LOGGER.isTraceEnabled() && !strategyRole.isInterface() ) { + BOOT_LOGGER.registeringNonInterfaceStrategy( strategyRole.getName() ); } - - if ( ! strategyRegistration.getStrategyRole().isAssignableFrom( strategyRegistration.getStrategyImplementation() ) ) { + if ( !strategyRole.isAssignableFrom( strategyRegistration.getStrategyImplementation() ) ) { throw new StrategySelectionException( "Implementation class [" + strategyRegistration.getStrategyImplementation().getName() - + "] does not implement strategy interface [" - + strategyRegistration.getStrategyRole().getName() + "]" + + "] does not implement strategy interface [" + + strategyRole.getName() + "]" ); } explicitStrategyRegistrations.add( strategyRegistration ); @@ -111,13 +108,11 @@ public void addExplicitStrategyRegistration(StrategyRegistration strategy * @return The selector. */ public StrategySelector buildSelector(ClassLoaderService classLoaderService) { - final StrategySelectorImpl strategySelector = new StrategySelectorImpl( classLoaderService ); + final var strategySelector = new StrategySelectorImpl( classLoaderService ); // build the baseline... - strategySelector.registerStrategyLazily( - Dialect.class, - new AggregatedDialectSelector( classLoaderService.loadJavaServices( DialectSelector.class ) ) - ); + strategySelector.registerStrategyLazily( Dialect.class, + new AggregatedDialectSelector( classLoaderService.loadJavaServices( DialectSelector.class ) ) ); strategySelector.registerStrategyLazily( JtaPlatform.class, new DefaultJtaPlatformSelector() ); addTransactionCoordinatorBuilders( strategySelector ); addSqmMultiTableInsertStrategies( strategySelector ); @@ -129,14 +124,14 @@ public StrategySelector buildSelector(ClassLoaderService classLoaderService) { addXmlFormatMappers( strategySelector ); // apply auto-discovered registrations - for ( StrategyRegistrationProvider provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) { - for ( StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations() ) { + for ( var provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) { + for ( var discoveredStrategyRegistration : provider.getStrategyRegistrations() ) { applyFromStrategyRegistration( strategySelector, discoveredStrategyRegistration ); } } // apply customizations - for ( StrategyRegistration explicitStrategyRegistration : explicitStrategyRegistrations ) { + for ( var explicitStrategyRegistration : explicitStrategyRegistrations ) { applyFromStrategyRegistration( strategySelector, explicitStrategyRegistration ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java index df0b77682b88..bf20cd457d92 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorImpl.java @@ -5,10 +5,9 @@ package org.hibernate.boot.registry.selector.internal; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Map; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; @@ -21,7 +20,9 @@ import org.hibernate.boot.registry.selector.spi.NamedStrategyContributions; import org.hibernate.boot.registry.selector.spi.NamedStrategyContributor; -import org.jboss.logging.Logger; + +import static java.util.Collections.emptySet; +import static org.hibernate.boot.BootLogging.BOOT_LOGGER; /** * Standard implementation of the {@link StrategySelector} contract. @@ -32,7 +33,6 @@ * @author Steve Ebersole */ public class StrategySelectorImpl implements StrategySelector { - private static final Logger LOG = Logger.getLogger( StrategySelectorImpl.class ); private static final StrategyCreator STANDARD_STRATEGY_CREATOR = StrategySelectorImpl::create; @@ -49,9 +49,8 @@ public class StrategySelectorImpl implements StrategySelector { */ public StrategySelectorImpl(ClassLoaderService classLoaderService) { this.classLoaderService = classLoaderService; - - this.contributors = classLoaderService.loadJavaServices( NamedStrategyContributor.class ); - for ( NamedStrategyContributor contributor : contributors ) { + contributors = classLoaderService.loadJavaServices( NamedStrategyContributor.class ); + for ( var contributor : contributors ) { contributor.contributeStrategyImplementations( new StartupContributions() ); } } @@ -59,17 +58,17 @@ public StrategySelectorImpl(ClassLoaderService classLoaderService) { @Override @SuppressWarnings("unchecked") public Class selectStrategyImplementor(Class strategy, String name) { - final Map> namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy ); + final var namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy ); if ( namedStrategyImplementorMap != null ) { - final Class registered = namedStrategyImplementorMap.get( name ); + final var registered = namedStrategyImplementorMap.get( name ); if ( registered != null ) { return (Class) registered; } } - final LazyServiceResolver lazyServiceResolver = lazyStrategyImplementorByStrategyMap.get( strategy ); + final var lazyServiceResolver = lazyStrategyImplementorByStrategyMap.get( strategy ); if ( lazyServiceResolver != null ) { - final Class resolve = lazyServiceResolver.resolve( name ); + final var resolve = lazyServiceResolver.resolve( name ); if ( resolve != null ) { return (Class) resolve; } @@ -106,7 +105,8 @@ public T resolveDefaultableStrategy( Class strategy, Object strategyReference, Callable defaultResolver) { - return resolveStrategy( strategy, strategyReference, defaultResolver, (StrategyCreator) STANDARD_STRATEGY_CREATOR ); + return resolveStrategy( strategy, strategyReference, defaultResolver, + (StrategyCreator) STANDARD_STRATEGY_CREATOR ); } @Override @@ -125,16 +125,30 @@ public T resolveStrategy( @Override public Collection> getRegisteredStrategyImplementors(Class strategy) { - final LazyServiceResolver lazyServiceResolver = lazyStrategyImplementorByStrategyMap.get( strategy ); + final var lazyServiceResolver = lazyStrategyImplementorByStrategyMap.get( strategy ); if ( lazyServiceResolver != null ) { throw new StrategySelectionException( "Can't use this method on for strategy types which are embedded in the core library" ); } - final Map> registrations = namedStrategyImplementorByStrategyMap.get( strategy ); + final var registrations = namedStrategyImplementorByStrategyMap.get( strategy ); if ( registrations == null ) { - return Collections.emptySet(); + return emptySet(); + } + else { + final Set> implementors = new HashSet<>(); + for ( var registration : registrations.values() ) { + if ( !strategy.isAssignableFrom( registration ) ) { + throw new StrategySelectionException( + String.format( + "Registered strategy [%s] is not a subtype of [%s]", + registration.getName(), + strategy.getName() + ) + ); + } + implementors.add( registration.asSubclass( strategy ) ); + } + return implementors; } - //noinspection unchecked,rawtypes - return (Collection) new HashSet<>( registrations.values() ); } @SuppressWarnings("unchecked") @@ -149,27 +163,27 @@ public T resolveStrategy( return defaultResolver.call(); } catch (Exception e) { - throw new StrategySelectionException( "Default-resolver threw exception", e ); + throw new StrategySelectionException( "Default resolver threw exception", e ); } } - - if ( strategy.isInstance( strategyReference ) ) { + else if ( strategy.isInstance( strategyReference ) ) { return strategy.cast( strategyReference ); } - - final Class implementationClass = - strategyReference instanceof Class - ? (Class) strategyReference - : selectStrategyImplementor( strategy, strategyReference.toString() ); - - try { - return creator.create( implementationClass ); - } - catch (Exception e) { - throw new StrategySelectionException( - String.format( "Could not instantiate named strategy class [%s]", implementationClass.getName() ), - e - ); + else { + final var implementationClass = + strategyReference instanceof Class + ? (Class) strategyReference + : selectStrategyImplementor( strategy, strategyReference.toString() ); + try { + return creator.create( implementationClass ); + } + catch (Exception e) { + throw new StrategySelectionException( + String.format( "Could not instantiate named strategy class [%s]", + implementationClass.getName() ), + e + ); + } } } @@ -189,7 +203,7 @@ private static T create(Class strategyClass) { // Lifecycle public void registerStrategyLazily(Class strategy, LazyServiceResolver resolver) { - LazyServiceResolver previous = lazyStrategyImplementorByStrategyMap.put( strategy, resolver ); + final var previous = lazyStrategyImplementorByStrategyMap.put( strategy, resolver ); if ( previous != null ) { throw new HibernateException( "Detected a second LazyServiceResolver replacing an existing LazyServiceResolver implementation for strategy " + strategy.getName() ); } @@ -198,21 +212,18 @@ public void registerStrategyLazily(Class strategy, LazyServiceResolver private void contributeImplementation(Class strategy, Class implementation, String... names) { final var namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.computeIfAbsent( strategy, clazz -> new ConcurrentHashMap<>() ); - for ( String name : names ) { - final Class old = namedStrategyImplementorMap.put( name, implementation ); - if ( LOG.isTraceEnabled() ) { + final var old = namedStrategyImplementorMap.put( name, implementation ); + if ( BOOT_LOGGER.isTraceEnabled() ) { if ( old == null ) { - LOG.tracef( - "Strategy selector for %s: '%s' -> %s", + BOOT_LOGGER.strategySelectorMapping( strategy.getSimpleName(), name, implementation.getName() ); } else { - LOG.tracef( - "Strategy selector for %s: '%s' -> %s (replacing %s)", + BOOT_LOGGER.strategySelectorMappingReplacing( strategy.getSimpleName(), name, implementation.getName(), @@ -224,29 +235,28 @@ private void contributeImplementation(Class strategy, Class } private void removeImplementation(Class strategy, Class implementation) { - final Map> namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy ); + final var namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy ); if ( namedStrategyImplementorMap == null ) { - LOG.debug( "Named strategy map did not exist on call to unregister" ); - return; + BOOT_LOGGER.namedStrategyMapDidNotExistOnUnregister(); } - - final Iterator> itr = namedStrategyImplementorMap.values().iterator(); - while ( itr.hasNext() ) { - final Class registered = itr.next(); - if ( registered.equals( implementation ) ) { - itr.remove(); + else { + final var itr = namedStrategyImplementorMap.values().iterator(); + while ( itr.hasNext() ) { + if ( itr.next().equals( implementation ) ) { + itr.remove(); + } } - } - // try to clean up after ourselves... - if ( namedStrategyImplementorMap.isEmpty() ) { - namedStrategyImplementorByStrategyMap.remove( strategy ); + // try to clean up after ourselves... + if ( namedStrategyImplementorMap.isEmpty() ) { + namedStrategyImplementorByStrategyMap.remove( strategy ); + } } } @Override public void stop() { - for ( NamedStrategyContributor contributor : contributors ) { + for ( var contributor : contributors ) { contributor.clearStrategyImplementations( new ShutdownContributions() ); } } @@ -270,12 +280,12 @@ public void contributeStrategyImplementor(Class strategy, Class void registerStrategyImplementor(Class strategy, String name, Class implementation) { contributeImplementation( strategy, implementation, name ); } - @Override + @Override @Deprecated(forRemoval = true) public void unRegisterStrategyImplementor(Class strategy, Class implementation) { removeImplementation( strategy, implementation ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java index 61c0f1f75d16..2a194efd0ec0 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/xsd/LocalXsdResolver.java @@ -5,19 +5,18 @@ package org.hibernate.boot.xsd; import java.io.IOException; -import java.io.InputStream; import java.net.URL; -import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.hibernate.internal.util.xml.XsdException; -import org.jboss.logging.Logger; - import org.xml.sax.SAXException; +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI; +import static org.hibernate.boot.jaxb.JaxbLogger.JAXB_LOGGER; + /** * When Hibernate loads an XSD we fully expect that to be resolved from our * jar file via ClassLoader resource look-up. This class simplifies @@ -33,18 +32,10 @@ public static String latestJpaVerison() { } public static boolean isValidJpaVersion(String version) { - switch ( version ) { - case "1.0": - case "2.0": - case "2.1": - case "2.2": - case "3.0": - case "3.1": - case "3.2": - return true; - default: - return false; - } + return switch ( version ) { + case "1.0", "2.0", "2.1", "2.2", "3.0", "3.1", "3.2" -> true; + default -> false; + }; } public static URL resolveLocalXsdUrl(String resourceName) { @@ -87,11 +78,10 @@ public static Schema resolveLocalXsdSchema(String schemaResourceName) { throw new XsdException( "Unable to locate schema [" + schemaResourceName + "] via classpath", schemaResourceName ); } try { - InputStream schemaStream = url.openStream(); + final var schemaStream = url.openStream(); try { - StreamSource source = new StreamSource( url.openStream() ); - SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); - return schemaFactory.newSchema( source ); + return SchemaFactory.newInstance( W3C_XML_SCHEMA_NS_URI ) + .newSchema( new StreamSource( url.openStream() ) ); } catch ( SAXException | IOException e ) { throw new XsdException( "Unable to load schema [" + schemaResourceName + "]", e, schemaResourceName ); @@ -101,8 +91,7 @@ public static Schema resolveLocalXsdSchema(String schemaResourceName) { schemaStream.close(); } catch ( IOException e ) { - Logger.getLogger( LocalXsdResolver.class ) - .debugf( "Problem closing schema stream [%s]", e.toString() ); + JAXB_LOGGER.problemClosingSchemaStream( e.toString() ); } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/AuditStrategyRegistrationProvider.java b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/AuditStrategyRegistrationProvider.java index 64606bbc6cd4..bfe13803d79c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/AuditStrategyRegistrationProvider.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/AuditStrategyRegistrationProvider.java @@ -23,11 +23,11 @@ */ public class AuditStrategyRegistrationProvider implements StrategyRegistrationProvider { - private static final List STRATEGIES = new ArrayList<>(); + private static final List> STRATEGIES = new ArrayList<>(); static { STRATEGIES.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl<>( AuditStrategy.class, DefaultAuditStrategy.class, "default", @@ -37,7 +37,7 @@ public class AuditStrategyRegistrationProvider implements StrategyRegistrationPr ) ); STRATEGIES.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl<>( AuditStrategy.class, ValidityAuditStrategy.class, "validity", @@ -49,7 +49,7 @@ public class AuditStrategyRegistrationProvider implements StrategyRegistrationPr } @Override - public Iterable getStrategyRegistrations() { + public Iterable> getStrategyRegistrations() { return STRATEGIES; } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/ModifiedColumnNamingStrategyRegistrationProvider.java b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/ModifiedColumnNamingStrategyRegistrationProvider.java index 877cc7d0a241..bc49b1711f15 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/ModifiedColumnNamingStrategyRegistrationProvider.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/boot/internal/ModifiedColumnNamingStrategyRegistrationProvider.java @@ -19,11 +19,11 @@ */ public class ModifiedColumnNamingStrategyRegistrationProvider implements StrategyRegistrationProvider { @Override - public Iterable getStrategyRegistrations() { - final List registrations = new ArrayList<>(); + public Iterable> getStrategyRegistrations() { + final List> registrations = new ArrayList<>(); registrations.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl<>( ModifiedColumnNamingStrategy.class, LegacyModifiedColumnNamingStrategy.class, "default", "legacy" @@ -31,7 +31,7 @@ public Iterable getStrategyRegistrations() { ); registrations.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl<>( ModifiedColumnNamingStrategy.class, ImprovedModifiedColumnNamingStrategy.class, "improved" diff --git a/hibernate-hikaricp/src/main/java/org/hibernate/hikaricp/internal/StrategyRegistrationProviderImpl.java b/hibernate-hikaricp/src/main/java/org/hibernate/hikaricp/internal/StrategyRegistrationProviderImpl.java index 8e69ac7a71cb..60cf9c8068c8 100644 --- a/hibernate-hikaricp/src/main/java/org/hibernate/hikaricp/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-hikaricp/src/main/java/org/hibernate/hikaricp/internal/StrategyRegistrationProviderImpl.java @@ -4,13 +4,13 @@ */ package org.hibernate.hikaricp.internal; -import java.util.Collections; - import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import static java.util.Collections.singleton; + /** * Provides the {@link HikariCPConnectionProvider} to the * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. @@ -20,8 +20,8 @@ public final class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - public Iterable getStrategyRegistrations() { - final SimpleStrategyRegistrationImpl strategyRegistration = new SimpleStrategyRegistrationImpl<>( + public Iterable> getStrategyRegistrations() { + return singleton( new SimpleStrategyRegistrationImpl<>( ConnectionProvider.class, HikariCPConnectionProvider.class, "hikari", @@ -29,7 +29,6 @@ public Iterable getStrategyRegistrations() { HikariCPConnectionProvider.class.getSimpleName(), // for consistency's sake "org.hibernate.connection.HikariCPConnectionProvider" - ); - return Collections.singleton( strategyRegistration ); + ) ); } } diff --git a/hibernate-jcache/src/main/java/org/hibernate/cache/jcache/internal/StrategyRegistrationProviderImpl.java b/hibernate-jcache/src/main/java/org/hibernate/cache/jcache/internal/StrategyRegistrationProviderImpl.java index c6b702608eef..fdf9ae66f945 100644 --- a/hibernate-jcache/src/main/java/org/hibernate/cache/jcache/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-jcache/src/main/java/org/hibernate/cache/jcache/internal/StrategyRegistrationProviderImpl.java @@ -4,14 +4,14 @@ */ package org.hibernate.cache.jcache.internal; -import java.util.Collections; - import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cache.jcache.ConfigSettings; import org.hibernate.cache.spi.RegionFactory; +import static java.util.Collections.singleton; + /** * Makes the JCache RegionFactory available to the Hibernate * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service @@ -22,9 +22,9 @@ public final class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - @SuppressWarnings("unchecked") - public Iterable getStrategyRegistrations() { - final SimpleStrategyRegistrationImpl simpleStrategyRegistration = new SimpleStrategyRegistrationImpl( + public Iterable> getStrategyRegistrations() { + + return singleton( new SimpleStrategyRegistrationImpl<>( RegionFactory.class, JCacheRegionFactory.class, ConfigSettings.SIMPLE_FACTORY_NAME, @@ -32,8 +32,6 @@ public Iterable getStrategyRegistrations() { JCacheRegionFactory.class.getSimpleName(), // legacy impl class name "org.hibernate.cache.jcache.JCacheRegionFactory" - ); - - return Collections.singleton( simpleStrategyRegistration ); + ) ); } } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/cache/StrategyRegistrationProviderImpl.java b/hibernate-testing/src/main/java/org/hibernate/testing/cache/StrategyRegistrationProviderImpl.java index a2fd89334f82..c3d96dd2d144 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/cache/StrategyRegistrationProviderImpl.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/cache/StrategyRegistrationProviderImpl.java @@ -4,13 +4,13 @@ */ package org.hibernate.testing.cache; -import java.util.Collections; - import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cache.spi.RegionFactory; +import static java.util.Collections.singletonList; + /** * Makes the JCache RegionFactory available to the Hibernate * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service @@ -20,10 +20,9 @@ */ public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - @SuppressWarnings("unchecked") - public Iterable getStrategyRegistrations() { - return Collections.singletonList( - new SimpleStrategyRegistrationImpl( + public Iterable> getStrategyRegistrations() { + return singletonList( + new SimpleStrategyRegistrationImpl<>( RegionFactory.class, CachingRegionFactory.class, "testing",