rationalize diverse ways to split strings

+ a couple of other code cleanups

Signed-off-by: Gavin King <gavin@hibernate.org>
This commit is contained in:
Gavin King 2024-08-30 11:20:13 +02:00
parent 6787da71af
commit 72e42817e3
40 changed files with 160 additions and 214 deletions

View File

@ -48,6 +48,7 @@ import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.query.SemanticException;
import org.hibernate.query.sqm.IntervalType;
import org.hibernate.dialect.NullOrdering;
@ -169,7 +170,7 @@ public class CockroachLegacyDialect extends Dialect {
// What the DB select returns is similar to "CockroachDB CCL v21.2.10 (x86_64-unknown-linux-gnu, built 2022/05/02 17:38:58, go1.16.6)"
Matcher m = CRDB_VERSION_PATTERN.matcher( versionString == null ? "" : versionString );
if ( m.find() ) {
String[] versionParts = m.group().substring( 1 ).split( "\\." );
String[] versionParts = StringHelper.split( ".", m.group().substring( 1 ) );
// if we got to this point, there is at least a major version, so no need to check [].length > 0
int majorVersion = Integer.parseInt( versionParts[0] );
int minorVersion = versionParts.length > 1 ? Integer.parseInt( versionParts[1] ) : 0;

View File

@ -46,6 +46,7 @@ import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.metamodel.mapping.EntityMappingType;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.query.sqm.FetchClauseType;
@ -189,7 +190,7 @@ public class H2LegacyDialect extends Dialect {
return 0;
}
final String[] bits = databaseVersion.split("[. ]");
final String[] bits = StringHelper.split( ". ", databaseVersion );
return bits.length > 2 ? Integer.parseInt( bits[2] ) : 0;
}

View File

@ -173,7 +173,7 @@ public class MySQLLegacyDialect extends Dialect {
protected static DatabaseVersion createVersion(DialectResolutionInfo info) {
final String versionString = info.getDatabaseVersion();
final String[] components = versionString.split( "\\." );
final String[] components = StringHelper.split( ".", versionString );
if ( components.length >= 3 ) {
try {
final int majorVersion = Integer.parseInt( components[0] );

View File

@ -58,6 +58,7 @@ import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.mapping.Column;
@ -184,7 +185,7 @@ public class SingleStoreDialect extends Dialect {
private static DatabaseVersion createVersion(DialectResolutionInfo info) {
final String versionString = info.getDatabaseVersion();
if ( versionString != null ) {
final String[] components = versionString.split( "\\." );
final String[] components = StringHelper.split( ".", versionString );
if ( components.length >= 3 ) {
try {
final int majorVersion = Integer.parseInt( components[0] );

View File

@ -13,6 +13,7 @@ import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.spi.ClassLoaderAccess;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import jakarta.validation.groups.Default;
@ -72,7 +73,7 @@ public class GroupsPerOperation {
if ( property instanceof String ) {
String stringProperty = (String) property;
String[] groupNames = stringProperty.split( "," );
String[] groupNames = StringHelper.split( ",", stringProperty );
if ( groupNames.length == 1 && groupNames[0].isEmpty() ) {
return EMPTY_GROUPS;
}

View File

@ -10,6 +10,7 @@ import java.util.Locale;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
/**
@ -35,7 +36,7 @@ public enum ValidationMode {
modes.add( ValidationMode.AUTO );
}
else {
for ( String modeInString : modeProperty.toString().split( "," ) ) {
for ( String modeInString : StringHelper.split( ",", modeProperty.toString() ) ) {
modes.add( getMode(modeInString) );
}
}

View File

@ -9,7 +9,6 @@ package org.hibernate.boot.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -17,7 +16,6 @@ import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
@ -62,19 +60,17 @@ import org.hibernate.mapping.Table;
import org.hibernate.mapping.UserDefinedObjectType;
import org.hibernate.mapping.UserDefinedType;
import org.hibernate.metamodel.mapping.DiscriminatorType;
import org.hibernate.procedure.spi.NamedCallableQueryMemento;
import org.hibernate.query.internal.NamedObjectRepositoryImpl;
import org.hibernate.query.named.NamedObjectRepository;
import org.hibernate.query.sql.spi.NamedNativeQueryMemento;
import org.hibernate.query.sqm.function.SqmFunctionDescriptor;
import org.hibernate.query.sqm.function.SqmFunctionRegistry;
import org.hibernate.query.sqm.spi.NamedSqmQueryMemento;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.tool.schema.Action;
import org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator;
import org.hibernate.type.spi.TypeConfiguration;
import static org.hibernate.cfg.AvailableSettings.EVENT_LISTENER_PREFIX;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* Container for configuration data collected during binding the metamodel.
@ -84,7 +80,6 @@ import static org.hibernate.cfg.AvailableSettings.EVENT_LISTENER_PREFIX;
* @author Gail Badner
*/
public class MetadataImpl implements MetadataImplementor, Serializable {
private static final Pattern LISTENER_SEPARATION_PATTERN = Pattern.compile( "\\s*,\\s*" );
private final UUID uuid;
private final MetadataBuildingOptions metadataBuildingOptions;
@ -370,30 +365,6 @@ public class MetadataImpl implements MetadataImplementor, Serializable {
);
}
private Map<String, NamedSqmQueryMemento<?>> buildNamedSqmMementos(SessionFactoryImplementor sessionFactory) {
final HashMap<String, NamedSqmQueryMemento<?>> map = new HashMap<>();
if ( namedQueryMap != null ) {
namedQueryMap.forEach( (key, value) -> map.put( key, value.resolve( sessionFactory ) ) );
}
return map;
}
private Map<String, NamedNativeQueryMemento<?>> buildNamedNativeMementos(SessionFactoryImplementor sessionFactory) {
final HashMap<String, NamedNativeQueryMemento<?>> map = new HashMap<>();
if ( namedNativeQueryMap != null ) {
namedNativeQueryMap.forEach( (key, value) -> map.put( key, value.resolve( sessionFactory ) ) );
}
return map;
}
private Map<String, NamedCallableQueryMemento> buildProcedureCallMementos(SessionFactoryImplementor sessionFactory) {
final Map<String, NamedCallableQueryMemento> map = new HashMap<>();
if ( namedProcedureCallMap != null ) {
namedProcedureCallMap.forEach( (key, value) -> map.put( key, value.resolve( sessionFactory ) ) );
}
return map;
}
@Override
public void orderColumns(boolean forceOrdering) {
final ColumnOrderingStrategy columnOrderingStrategy = metadataBuildingOptions.getColumnOrderingStrategy();
@ -544,7 +515,7 @@ public class MetadataImpl implements MetadataImplementor, Serializable {
String listeners,
EventType<T> eventType) {
final EventListenerGroup<T> eventListenerGroup = eventListenerRegistry.getEventListenerGroup( eventType );
for ( String listenerImpl : LISTENER_SEPARATION_PATTERN.split( listeners ) ) {
for ( String listenerImpl : splitAtCommas( listeners ) ) {
@SuppressWarnings("unchecked")
T listener = (T) instantiate( listenerImpl, classLoaderService );
if ( !eventType.baseListenerInterface().isInstance( listener ) ) {

View File

@ -3370,7 +3370,7 @@ public class HbmXmlTransformer {
if ( isNotEmpty( s ) ) {
s = s.toLowerCase( Locale.ROOT ).replaceAll( " ", "" );
final String[] split = s.split( "," );
final String[] split = StringHelper.split( ",", s );
for ( String hbmCascade : split ) {
if ( hbmCascade.contains( "all" ) ) {
cascadeType.setCascadeAll( new JaxbEmptyTypeImpl() );

View File

@ -134,7 +134,7 @@ public class QualifiedNameParser {
boolean schemaWasQuoted = false;
boolean nameWasQuoted;
final String[] tokens = text.split( "\\." );
final String[] tokens = StringHelper.split( ".", text );
if ( tokens.length == 0 || tokens.length == 1 ) {
// we have just a local name...
name = text;

View File

@ -12,6 +12,8 @@ import java.util.Set;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmBasicAttributeType;
import org.hibernate.boot.model.source.spi.SizeSource;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* ColumnAndFormulaSource implementation handling basic attribute mappings.
*
@ -69,7 +71,7 @@ public class BasicAttributeColumnsAndFormulasSource
@Override
public Set<String> getIndexConstraintNames() {
return CommaSeparatedStringHelper.split( basicAttributeMapping.getIndex() );
return Set.of( splitAtCommas( basicAttributeMapping.getIndex() ) );
}
@Override
@ -79,6 +81,6 @@ public class BasicAttributeColumnsAndFormulasSource
@Override
public Set<String> getUniqueKeyConstraintNames() {
return CommaSeparatedStringHelper.split( basicAttributeMapping.getUniqueKey() );
return Set.of( splitAtCommas( basicAttributeMapping.getUniqueKey() ) );
}
}

View File

@ -7,6 +7,8 @@
package org.hibernate.boot.model.source.internal.hbm;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmColumnType;
@ -15,6 +17,8 @@ import org.hibernate.boot.model.source.spi.ColumnSource;
import org.hibernate.boot.model.source.spi.JdbcDataType;
import org.hibernate.boot.model.source.spi.SizeSource;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* @author Steve Ebersole
*/
@ -65,14 +69,12 @@ class ColumnSourceImpl
this.columnElement = columnElement;
this.nullable = nullable;
this.indexConstraintNames = CommaSeparatedStringHelper.splitAndCombine(
indexConstraintNames,
columnElement.getIndex()
);
this.ukConstraintNames = CommaSeparatedStringHelper.splitAndCombine(
ukConstraintNames,
columnElement.getUniqueKey()
);
this.indexConstraintNames =
splitAndCombine( indexConstraintNames,
columnElement.getIndex() );
this.ukConstraintNames =
splitAndCombine( ukConstraintNames,
columnElement.getUniqueKey() );
}
@Override
@ -154,4 +156,15 @@ class ColumnSourceImpl
public Set<String> getUniqueKeyConstraintNames() {
return ukConstraintNames;
}
public static Set<String> splitAndCombine(Set<String> stringSet, String values) {
if ( values == null || values.isEmpty() ) {
return stringSet;
}
else {
HashSet<String> set = new HashSet<>( stringSet );
Collections.addAll( set, splitAtCommas( values ) );
return set;
}
}
}

View File

@ -1,54 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.boot.model.source.internal.hbm;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.hibernate.internal.util.StringHelper;
/**
* @author Steve Ebersole
* @author Sanne Grinovero
*/
public final class CommaSeparatedStringHelper {
private static final Pattern COMMA_SEPARATED_PATTERN = Pattern.compile( "\\s*,\\s*" );
private CommaSeparatedStringHelper() {
}
public static Set<String> split(String values) {
if ( values == null || values.isEmpty() ) {
return Collections.emptySet();
}
return COMMA_SEPARATED_PATTERN.splitAsStream( values ).collect( Collectors.toSet() );
}
public static Set<String> splitAndCombine(Set<String> x, String values) {
if ( x.isEmpty() && ( values == null || values.isEmpty() ) ) {
return Collections.emptySet();
}
HashSet<String> set = new HashSet<>( x );
if ( values != null && !values.isEmpty() ) {
Collections.addAll( set, COMMA_SEPARATED_PATTERN.split( values ) );
}
return set;
}
public static List<String> parseCommaSeparatedString(String incomingString) {
if ( StringHelper.isEmpty( incomingString ) ) {
return Collections.emptyList();
}
return COMMA_SEPARATED_PATTERN.splitAsStream( incomingString ).collect( Collectors.toList() );
}
}

View File

@ -11,6 +11,8 @@ import java.util.Set;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmManyToOneType;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* ColumnAndFormulaSource implementation handling many-to-one attribute mappings.
*
@ -57,7 +59,7 @@ public class ManyToOneAttributeColumnsAndFormulasSource extends RelationalValueS
@Override
public Set<String> getIndexConstraintNames() {
return CommaSeparatedStringHelper.split( manyToOneMapping.getIndex() );
return Set.of( splitAtCommas( manyToOneMapping.getIndex() ) );
}
@Override
@ -67,6 +69,6 @@ public class ManyToOneAttributeColumnsAndFormulasSource extends RelationalValueS
@Override
public Set<String> getUniqueKeyConstraintNames() {
return CommaSeparatedStringHelper.split( manyToOneMapping.getUniqueKey() );
return Set.of( splitAtCommas( manyToOneMapping.getUniqueKey() ) );
}
}

View File

@ -6,6 +6,8 @@
*/
package org.hibernate.boot.model.source.spi;
import org.hibernate.internal.util.StringHelper;
/**
* An attribute path is, generally speaking, the path of attribute names back
* to a "root" (which is either an entity or a persistent collection). The
@ -45,7 +47,7 @@ public class AttributePath extends AbstractAttributeKey {
}
AttributePath attributePath = new AttributePath();
for ( String part : path.split( "\\." ) ) {
for ( String part : StringHelper.split( ".", path ) ) {
attributePath = attributePath.append( part );
}
return attributePath;

View File

@ -28,6 +28,7 @@ import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNativeQueryScalarReturnType;
import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmResultSetMappingType;
import org.hibernate.boot.spi.InFlightMetadataCollector;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Component;
@ -510,7 +511,7 @@ public class HbmResultSetMappingDescriptor implements NamedResultSetMappingDescr
MetadataBuildingContext context) {
this.parent = parent;
this.propertyPath = hbmPropertyMapping.getName();
this.propertyPathParts = propertyPath.split( "\\." );
this.propertyPathParts = StringHelper.split( ".", propertyPath );
this.columnAliases = extractColumnAliases( hbmPropertyMapping, context );
if ( columnAliases.size() > 1 ) {
@ -818,7 +819,7 @@ public class HbmResultSetMappingDescriptor implements NamedResultSetMappingDescr
final FetchParentMemento ownerMemento = hbmFetchParent.resolveParentMemento( resolutionContext );
final String[] parts = propertyPath.split( "\\." );
final String[] parts = StringHelper.split( ".", propertyPath );
NavigablePath navigablePath;
if ( ownerMemento.getFetchableContainer() instanceof PluralAttributeMapping ) {
navigablePath = ownerMemento.getNavigablePath().append( CollectionPart.Nature.ELEMENT.getName() );

View File

@ -15,6 +15,7 @@ import java.util.Map;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.metamodel.RuntimeMetamodels;
import org.hibernate.metamodel.mapping.BasicValuedModelPart;
@ -338,7 +339,7 @@ public class SqlResultSetMappingDescriptor implements NamedResultSetMappingDescr
String columnName) {
this.entityName = entityName;
this.propertyPath = propertyPath;
this.propertyPathParts = propertyPath.split( "\\." );
this.propertyPathParts = StringHelper.split( ".", propertyPath );
this.navigablePath = entityPath;
this.columnNames = new ArrayList<>();
columnNames.add( columnName );

View File

@ -48,6 +48,7 @@ import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.query.SemanticException;
import org.hibernate.query.sqm.IntervalType;
@ -186,7 +187,7 @@ public class CockroachDialect extends Dialect {
// What the DB select returns is similar to "CockroachDB CCL v21.2.10 (x86_64-unknown-linux-gnu, built 2022/05/02 17:38:58, go1.16.6)"
Matcher m = CRDB_VERSION_PATTERN.matcher( versionString == null ? "" : versionString );
if ( m.find() ) {
String[] versionParts = m.group().substring( 1 ).split( "\\." );
String[] versionParts = StringHelper.split( ".", m.group().substring( 1 ) );
// if we got to this point, there is at least a major version, so no need to check [].length > 0
int majorVersion = Integer.parseInt( versionParts[0] );
int minorVersion = versionParts.length > 1 ? Integer.parseInt( versionParts[1] ) : 0;

View File

@ -7,6 +7,8 @@
package org.hibernate.dialect;
import org.hibernate.internal.util.StringHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@ -48,7 +50,7 @@ class CockroachDialectQueryHints {
}
private IndexHint parseIndexHints(String hint) {
var parts = hint.split( "@" );
var parts = StringHelper.split( "@", hint );
if ( parts.length == 2 ) {
return new IndexHint( parts[0], hint );
}

View File

@ -206,7 +206,7 @@ import static java.lang.Math.log;
import static org.hibernate.cfg.AvailableSettings.NON_CONTEXTUAL_LOB_CREATION;
import static org.hibernate.cfg.AvailableSettings.STATEMENT_BATCH_SIZE;
import static org.hibernate.cfg.AvailableSettings.USE_GET_GENERATED_KEYS;
import static org.hibernate.internal.util.StringHelper.parseCommaSeparatedString;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
import static org.hibernate.internal.util.collections.ArrayHelper.EMPTY_STRING_ARRAY;
import static org.hibernate.type.SqlTypes.ARRAY;
import static org.hibernate.type.SqlTypes.BIGINT;
@ -666,7 +666,7 @@ public abstract class Dialect implements ConversionContext, TypeContributor, Fun
* @see java.sql.DatabaseMetaData#getSQLKeywords()
*/
protected void registerKeywords(DialectResolutionInfo info) {
for ( String keyword : parseCommaSeparatedString( info.getSQLKeywords() ) ) {
for ( String keyword : splitAtCommas( info.getSQLKeywords() ) ) {
registerKeyword( keyword );
}
}

View File

@ -41,6 +41,7 @@ import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtractor;
import org.hibernate.exception.spi.ViolatedConstraintNameExtractor;
import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.metamodel.mapping.EntityMappingType;
import org.hibernate.metamodel.spi.RuntimeModelCreationContext;
import org.hibernate.persister.entity.mutation.EntityMutationTarget;
@ -164,7 +165,7 @@ public class H2Dialect extends Dialect {
return 0;
}
final String[] bits = databaseVersion.split("[. \\-]");
final String[] bits = StringHelper.split( ". -", databaseVersion );
return bits.length > 2 ? Integer.parseInt( bits[2] ) : 0;
}

View File

@ -14,6 +14,7 @@ import java.sql.Statement;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolutionInfo;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import static org.hibernate.cfg.DialectSpecificSettings.HANA_MAX_LOB_PREFETCH_SIZE;
@ -86,7 +87,7 @@ public class HANAServerConfiguration {
if ( versionString == null ) {
return HANADialect.MINIMUM_VERSION;
}
final String[] components = versionString.split( "\\." );
final String[] components = StringHelper.split( ".", versionString );
if ( components.length >= 3 ) {
try {
majorVersion = Integer.parseInt( components[0] );

View File

@ -21,6 +21,7 @@ import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DB2StructJdbcType;
import org.hibernate.dialect.XmlHelper;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.AggregateColumn;
import org.hibernate.mapping.Column;
import org.hibernate.metamodel.mapping.EmbeddableMappingType;
@ -283,7 +284,7 @@ public class DB2AggregateSupport extends AggregateSupportImpl {
this.customWriteExpressionEnd = "";
}
else {
final String[] parts = customWriteExpression.split( "\\?" );
final String[] parts = StringHelper.split( "?", customWriteExpression );
assert parts.length == 2;
this.customWriteExpressionStart = parts[0];
this.customWriteExpressionEnd = parts[1];

View File

@ -18,6 +18,7 @@ import org.hibernate.dialect.DatabaseVersion;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.OracleArrayJdbcType;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.AggregateColumn;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.UserDefinedArrayType;
@ -538,7 +539,7 @@ public class OracleAggregateSupport extends AggregateSupportImpl {
this.customWriteExpressionEnd = "";
}
else {
final String[] parts = customWriteExpression.split( "\\?" );
final String[] parts = StringHelper.split( "?", customWriteExpression );
assert parts.length == 2;
this.customWriteExpressionStart = parts[0];
this.customWriteExpressionEnd = parts[1];

View File

@ -10,6 +10,7 @@ import java.util.LinkedHashMap;
import java.util.Map;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.AggregateColumn;
import org.hibernate.mapping.Column;
import org.hibernate.metamodel.mapping.JdbcMapping;
@ -304,7 +305,7 @@ public class PostgreSQLAggregateSupport extends AggregateSupportImpl {
this.customWriteExpressionEnd = "";
}
else {
final String[] parts = customWriteExpression.split( "\\?" );
final String[] parts = StringHelper.split( ".", customWriteExpression );
assert parts.length == 2;
this.customWriteExpressionStart = parts[0];
this.customWriteExpressionEnd = parts[1];

View File

@ -12,13 +12,9 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.hibernate.HibernateException;
import org.hibernate.boot.model.source.internal.hbm.CommaSeparatedStringHelper;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.cursor.internal.StandardRefCursorSupport;
import org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData;
@ -27,6 +23,8 @@ import org.hibernate.engine.jdbc.env.spi.SQLStateType;
import org.hibernate.tool.schema.extract.spi.ExtractionContext;
import org.hibernate.tool.schema.extract.spi.SequenceInformation;
import static java.util.stream.StreamSupport.stream;
/**
* Standard implementation of ExtractedDatabaseMetaData
*
@ -200,10 +198,6 @@ public class ExtractedDatabaseMetaDataImpl implements ExtractedDatabaseMetaData
return this;
}
private Set<String> parseKeywords(String extraKeywordsString) {
return CommaSeparatedStringHelper.split( extraKeywordsString );
}
public Builder setConnectionSchemaName(String connectionSchemaName) {
this.connectionSchemaName = connectionSchemaName;
return this;
@ -279,28 +273,10 @@ public class ExtractedDatabaseMetaDataImpl implements ExtractedDatabaseMetaData
* @return sequence information List
*/
private List<SequenceInformation> sequenceInformationList() {
final JdbcEnvironment jdbcEnvironment = this.jdbcEnvironment;
final Dialect dialect = this.jdbcEnvironment.getDialect();
Connection connection = null;
try {
connection = connectionAccess.obtainConnection();
final Connection c = connection;
Iterable<SequenceInformation> sequenceInformationIterable = dialect
.getSequenceInformationExtractor()
.extractMetadata( new ExtractionContext.EmptyExtractionContext() {
@Override
public Connection getJdbcConnection() {
return c;
}
@Override
public JdbcEnvironment getJdbcEnvironment() {
return jdbcEnvironment;
}
}
);
return StreamSupport.stream( sequenceInformationIterable.spliterator(), false )
return stream( sequenceInformation( connection, jdbcEnvironment ).spliterator(), false )
.collect( Collectors.toList() );
}
catch (SQLException e) {
@ -311,11 +287,26 @@ public class ExtractedDatabaseMetaDataImpl implements ExtractedDatabaseMetaData
try {
connectionAccess.releaseConnection( connection );
}
catch (SQLException throwables) {
catch (SQLException exception) {
//ignored
}
}
}
}
private static Iterable<SequenceInformation> sequenceInformation(Connection connection, JdbcEnvironment jdbcEnvironment)
throws SQLException {
return jdbcEnvironment.getDialect().getSequenceInformationExtractor().extractMetadata(
new ExtractionContext.EmptyExtractionContext() {
@Override
public Connection getJdbcConnection() {
return connection;
}
@Override
public JdbcEnvironment getJdbcEnvironment() {
return jdbcEnvironment;
}
}
);
}
}

View File

@ -20,7 +20,6 @@ import org.hibernate.dialect.DatabaseVersion;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.batch.spi.BatchBuilder;
import org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.engine.jdbc.connections.internal.DatabaseConnectionInfoImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.DatabaseConnectionInfo;
@ -37,6 +36,7 @@ import org.hibernate.event.internal.EmptyEventManager;
import org.hibernate.event.spi.EventManager;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.log.ConnectionInfoLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jpa.internal.MutableJpaComplianceImpl;
import org.hibernate.jpa.spi.JpaCompliance;
@ -112,7 +112,7 @@ public class JdbcEnvironmentInitiator implements StandardServiceInitiator<JdbcEn
getExplicitDatabaseVersion( configurationValues, explicitDatabaseMajorVersion, explicitDatabaseMinorVersion );
if ( explicitDatabaseMajorVersion == null && explicitDatabaseMinorVersion == null && explicitDatabaseVersion != null ) {
final String[] parts = explicitDatabaseVersion.split( "\\." );
final String[] parts = StringHelper.split( ".", explicitDatabaseVersion );
try {
final int potentialMajor = Integer.parseInt( parts[0] );
if ( parts.length > 1 ) {

View File

@ -10,16 +10,17 @@ import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.hibernate.engine.jdbc.env.internal.NormalizingIdentifierHelperImpl;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.jboss.logging.Logger;
import static java.util.Collections.addAll;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* Builder for IdentifierHelper instances. Mainly here to allow progressive
* building of the immutable (after instantiation) IdentifierHelper.
@ -60,18 +61,12 @@ public class IdentifierHelperBuilder {
* @throws SQLException Any access to DatabaseMetaData can case SQLException; just re-throw.
*/
public void applyReservedWords(DatabaseMetaData metaData) throws SQLException {
if ( metaData == null ) {
return;
if ( metaData != null
// Important optimisation: skip loading all keywords
// from the DB when autoQuoteKeywords is disabled
&& autoQuoteKeywords ) {
addAll( reservedWords, splitAtCommas( metaData.getSQLKeywords() ) );
}
//Important optimisation: skip loading all keywords from the DB when autoQuoteKeywords is disabled
if ( autoQuoteKeywords ) {
this.reservedWords.addAll( parseKeywords( metaData.getSQLKeywords() ) );
}
}
private static List<String> parseKeywords(String extraKeywordsString) {
return StringHelper.parseCommaSeparatedString( extraKeywordsString );
}
public void applyIdentifierCasing(DatabaseMetaData metaData) throws SQLException {
@ -95,13 +90,13 @@ public class IdentifierHelperBuilder {
}
if ( metaData.storesUpperCaseIdentifiers() ) {
this.unquotedCaseStrategy = IdentifierCaseStrategy.UPPER;
unquotedCaseStrategy = IdentifierCaseStrategy.UPPER;
}
else if ( metaData.storesLowerCaseIdentifiers() ) {
this.unquotedCaseStrategy = IdentifierCaseStrategy.LOWER;
unquotedCaseStrategy = IdentifierCaseStrategy.LOWER;
}
else {
this.unquotedCaseStrategy = IdentifierCaseStrategy.MIXED;
unquotedCaseStrategy = IdentifierCaseStrategy.MIXED;
}
}
@ -122,13 +117,13 @@ public class IdentifierHelperBuilder {
}
if ( metaData.storesMixedCaseQuotedIdentifiers() ) {
this.quotedCaseStrategy = IdentifierCaseStrategy.MIXED;
quotedCaseStrategy = IdentifierCaseStrategy.MIXED;
}
else if ( metaData.storesLowerCaseQuotedIdentifiers() ) {
this.quotedCaseStrategy = IdentifierCaseStrategy.LOWER;
quotedCaseStrategy = IdentifierCaseStrategy.LOWER;
}
else {
this.quotedCaseStrategy = IdentifierCaseStrategy.UPPER;
quotedCaseStrategy = IdentifierCaseStrategy.UPPER;
}
}
}
@ -192,7 +187,7 @@ public class IdentifierHelperBuilder {
public void applyReservedWords(Collection<String> words) {
//No use when autoQuoteKeywords is disabled
if ( autoQuoteKeywords ) {
this.reservedWords.addAll( words );
reservedWords.addAll( words );
}
}

View File

@ -13,6 +13,7 @@ import java.sql.SQLException;
import java.util.LinkedHashSet;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.jboss.logging.Logger;
@ -127,7 +128,7 @@ public class TypeInfo {
if ( value == null || value.length() == 0 ) {
return ArrayHelper.EMPTY_STRING_ARRAY;
}
return value.split( "," );
return StringHelper.split( ",", value );
}
public String getTypeName() {

View File

@ -14,8 +14,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.hibernate.boot.model.source.internal.hbm.CommaSeparatedStringHelper;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.loader.internal.AliasConstantsHelper;
@ -29,6 +29,8 @@ public final class StringHelper {
public static final String WHITESPACE = " \n\r\f\t";
public static final String[] EMPTY_STRINGS = ArrayHelper.EMPTY_STRING_ARRAY;
private static final Pattern COMMA_SEPARATED_PATTERN = Pattern.compile( "\\s*,\\s*" );
private StringHelper() { /* static methods only - hide constructor */
}
@ -843,8 +845,10 @@ public final class StringHelper {
return value;
}
public static List<String> parseCommaSeparatedString(String incomingString) {
return CommaSeparatedStringHelper.parseCommaSeparatedString( incomingString );
public static String[] splitAtCommas(String incomingString) {
return incomingString==null || incomingString.isBlank()
? EMPTY_STRINGS
: COMMA_SEPARATED_PATTERN.split( incomingString );
}
public static <T> String join(Collection<T> values, Renderer<T> renderer) {

View File

@ -12,6 +12,7 @@ import java.util.Collection;
import java.util.Objects;
import org.hibernate.Incubating;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.spi.DotIdentifierSequence;
/**
@ -41,7 +42,7 @@ public class SelectablePath implements Serializable, DotIdentifierSequence {
if ( path == null || path.isEmpty() ) {
return null;
}
final String[] parts = path.split( "\\." );
final String[] parts = StringHelper.split( ".", path );
SelectablePath selectablePath = new SelectablePath( parts[0] );
for ( int i = 1; i < parts.length; i++ ) {
selectablePath = selectablePath.append( parts[i] );

View File

@ -25,6 +25,7 @@ import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.util.IndexedConsumer;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Component;
@ -2474,7 +2475,7 @@ public class ToOneAttributeMapping
Object value = domainValue;
ManagedMappingType managedType = entityType;
final String[] pathParts = attributePath.split( "\\." );
final String[] pathParts = StringHelper.split( ".", attributePath );
for ( int i = 0; i < pathParts.length; i++ ) {
assert managedType != null;

View File

@ -14,7 +14,7 @@ import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.hibernate.engine.FetchTiming;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.mapping.ForeignKeyDescriptor;
import org.hibernate.metamodel.mapping.EmbeddableMappingType;
@ -60,7 +60,7 @@ public class ImplicitFetchBuilderEntity implements ImplicitFetchBuilder {
else {
associationKeyPropertyName = fetchable.getReferencedPropertyName();
NavigablePath path = relativePath.getValue();
for ( String part : associationKeyPropertyName.split( "\\." ) ) {
for ( String part : StringHelper.split( ".", associationKeyPropertyName ) ) {
path = path.append( part );
}
associationKeyFetchPath = path;

View File

@ -13,7 +13,6 @@ import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.model.relational.Database;
@ -48,6 +47,8 @@ import org.hibernate.tool.schema.spi.ScriptSourceInput;
import org.hibernate.tool.schema.spi.ScriptTargetOutput;
import org.hibernate.tool.schema.spi.SqlScriptCommandExtractor;
import static org.hibernate.internal.util.StringHelper.splitAtCommas;
/**
* Helper methods.
*
@ -56,7 +57,6 @@ import org.hibernate.tool.schema.spi.SqlScriptCommandExtractor;
public class Helper {
private static final CoreMessageLogger log = CoreLogging.messageLogger( Helper.class );
private static final Pattern COMMA_PATTERN = Pattern.compile( "\\s*,\\s*" );
public static ScriptSourceInput interpretScriptSourceSetting(
Object scriptSourceSetting, //Reader or String URL
@ -69,7 +69,7 @@ public class Helper {
final String scriptSourceSettingString = scriptSourceSetting.toString();
log.debugf( "Attempting to resolve script source setting : %s", scriptSourceSettingString );
final String[] paths = COMMA_PATTERN.split( scriptSourceSettingString );
final String[] paths = splitAtCommas( scriptSourceSettingString );
if ( paths.length == 1 ) {
return interpretScriptSourceSetting( scriptSourceSettingString, classLoaderService, charsetName );
}

View File

@ -32,6 +32,7 @@ import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.hibernate.engine.jdbc.internal.Formatter;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.Index;
import org.hibernate.mapping.Table;
@ -666,8 +667,8 @@ public class SchemaCreatorImpl implements SchemaCreator {
String defaultImportFile,
GenerationTarget[] targets) {
final String[] importFiles =
getString( HBM2DDL_IMPORT_FILES, options.getConfigurationValues(), defaultImportFile )
.split( "," );
StringHelper.split( ",",
getString( HBM2DDL_IMPORT_FILES, options.getConfigurationValues(), defaultImportFile ) );
final String charsetName = getCharsetName( options );
final ClassLoaderService classLoaderService = getClassLoaderService();
for ( String currentFile : importFiles ) {

View File

@ -16,6 +16,7 @@ import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.hibernate.engine.jdbc.internal.Formatter;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.mapping.ForeignKey;
@ -320,7 +321,7 @@ public class SchemaTruncatorImpl implements SchemaTruncator {
SchemaCreatorImpl.DEFAULT_IMPORT_FILE
);
for ( String currentFile : importFiles.split( "," ) ) {
for ( String currentFile : StringHelper.split( ",", importFiles ) ) {
final String resourceName = currentFile.trim();
if ( resourceName.isEmpty() ) {
//skip empty resource names

View File

@ -10,7 +10,6 @@ import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
@ -26,6 +25,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static java.util.stream.StreamSupport.stream;
import static org.hibernate.testing.transaction.TransactionUtil.doInAutoCommit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -75,11 +75,27 @@ public class OracleDialectSequenceInformationTest extends BaseNonConfigCoreFunct
return TransactionUtil.doWithJDBC(
sessionFactory().getServiceRegistry(),
connection -> {
JdbcEnvironment jdbcEnvironment = sessionFactory().getJdbcServices().getJdbcEnvironment();
SequenceInformationExtractorOracleDatabaseImpl sequenceExtractor = SequenceInformationExtractorOracleDatabaseImpl.INSTANCE;
Iterable<SequenceInformation> sequenceInformations = sequenceExtractor.extractMetadata(
new ExtractionContext.EmptyExtractionContext() {
final JdbcEnvironment jdbcEnvironment =
sessionFactory().getJdbcServices().getJdbcEnvironment();
// lets skip system sequences
Optional<SequenceInformation> foundSequence =
stream( sequenceInformation( connection, jdbcEnvironment ).spliterator(), false )
.filter( sequence -> isSameSequence( sequenceName, sequence ) )
.findFirst();
assertTrue( sequenceName + " not found", foundSequence.isPresent() );
return foundSequence.get();
}
);
}
private static boolean isSameSequence(String sequenceName, SequenceInformation sequence) {
return sequenceName.equals( sequence.getSequenceName().getSequenceName().getText().toUpperCase() );
}
private static Iterable<SequenceInformation> sequenceInformation(Connection connection, JdbcEnvironment jdbcEnvironment)
throws SQLException {
return SequenceInformationExtractorOracleDatabaseImpl.INSTANCE.extractMetadata(
new ExtractionContext.EmptyExtractionContext() {
@Override
public Connection getJdbcConnection() {
return connection;
@ -89,22 +105,6 @@ public class OracleDialectSequenceInformationTest extends BaseNonConfigCoreFunct
public JdbcEnvironment getJdbcEnvironment() {
return jdbcEnvironment;
}
} );
// lets skip system sequences
Optional<SequenceInformation> foundSequence = StreamSupport.stream(
sequenceInformations.spliterator(),
false
)
.filter( sequence -> sequenceName.equals( sequence.getSequenceName()
.getSequenceName()
.getText()
.toUpperCase() ) )
.findFirst();
assertTrue( sequenceName + " not found", foundSequence.isPresent() );
return foundSequence.get();
}
);
}

View File

@ -129,7 +129,7 @@ public final class Context {
String ormXmlOption = options.get( HibernateProcessor.ORM_XML_OPTION );
if ( ormXmlOption != null ) {
ormXmlFiles = new ArrayList<>();
for ( String ormFile : ormXmlOption.split( "," ) ) {
for ( String ormFile : ormXmlOption.split( ",\\s*" ) ) {
if ( !ormFile.startsWith("/") ) {
ormFile = "/" + ormFile;
}

View File

@ -276,7 +276,7 @@ public class HibernateProcessor extends AbstractProcessor {
context.setSuppressedWarnings(new String[] {"deprecation", "rawtypes"});
}
else {
context.setSuppressedWarnings( suppressedWarnings.replace(" ","").split(",") );
context.setSuppressedWarnings( suppressedWarnings.replace(" ","").split(",\\s*") );
}
}

View File

@ -240,13 +240,13 @@ public abstract class ProcessorSessionFactory extends MockSessionFactory {
}
try (Reader reader = filer.getResource(StandardLocation.SOURCE_OUTPUT, ENTITY_INDEX, value)
.openReader(true); BufferedReader buffered = new BufferedReader(reader) ) {
return Set.of(buffered.readLine().split(" "));
return Set.of(split(" ", buffered.readLine()));
}
catch (IOException e) {
}
try (Reader reader = filer.getResource(StandardLocation.CLASS_PATH, ENTITY_INDEX, '.' + value)
.openReader(true); BufferedReader buffered = new BufferedReader(reader) ) {
return Set.of(buffered.readLine().split(" "));
return Set.of(split(" ", buffered.readLine()));
}
catch (IOException e) {
}