Apply 'instanceof pattern matching' in spring-jdbc

This commit is contained in:
Sam Brannen 2022-12-07 16:49:22 -05:00
parent 73a18046c3
commit 114d6a9256
15 changed files with 80 additions and 86 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -655,8 +655,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
if (psc instanceof ParameterDisposer) {
((ParameterDisposer) psc).cleanupParameters();
if (psc instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
String sql = getSql(psc);
psc = null;
@ -668,8 +668,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
finally {
if (closeResources) {
if (psc instanceof ParameterDisposer) {
((ParameterDisposer) psc).cleanupParameters();
if (psc instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
JdbcUtils.closeStatement(ps);
DataSourceUtils.releaseConnection(con, getDataSource());
@ -724,8 +724,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
finally {
JdbcUtils.closeResultSet(rs);
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
if (pss instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
}
}
@ -839,8 +839,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
Connection con = ps.getConnection();
return new ResultSetSpliterator<>(rs, rowMapper).stream().onClose(() -> {
JdbcUtils.closeResultSet(rs);
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
if (pss instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
JdbcUtils.closeStatement(ps);
DataSourceUtils.releaseConnection(con, getDataSource());
@ -969,8 +969,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
return rows;
}
finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
if (pss instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
}
}, true));
@ -1035,8 +1035,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
try {
int batchSize = pss.getBatchSize();
InterruptibleBatchPreparedStatementSetter ipss =
(pss instanceof InterruptibleBatchPreparedStatementSetter ?
(InterruptibleBatchPreparedStatementSetter) pss : null);
(pss instanceof InterruptibleBatchPreparedStatementSetter ibpss ? ibpss : null);
if (JdbcUtils.supportsBatchUpdates(ps.getConnection())) {
for (int i = 0; i < batchSize; i++) {
pss.setValues(ps, i);
@ -1064,8 +1063,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
if (pss instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
}
});
@ -1154,8 +1153,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
return result1;
}
finally {
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
if (pss instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
}
});
@ -1193,8 +1192,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
if (csc instanceof ParameterDisposer) {
((ParameterDisposer) csc).cleanupParameters();
if (csc instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
String sql = getSql(csc);
csc = null;
@ -1205,8 +1204,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
throw translateException("CallableStatementCallback", sql, ex);
}
finally {
if (csc instanceof ParameterDisposer) {
((ParameterDisposer) csc).cleanupParameters();
if (csc instanceof ParameterDisposer parameterDisposer) {
parameterDisposer.cleanupParameters();
}
JdbcUtils.closeStatement(cs);
DataSourceUtils.releaseConnection(con, getDataSource());
@ -1345,14 +1344,14 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
else {
Object out = cs.getObject(sqlColIndex);
if (out instanceof ResultSet) {
if (out instanceof ResultSet resultSet) {
if (outParam.isResultSetSupported()) {
results.putAll(processResultSet((ResultSet) out, outParam));
results.putAll(processResultSet(resultSet, outParam));
}
else {
String rsName = outParam.getName();
SqlReturnResultSet rsParam = new SqlReturnResultSet(rsName, getColumnMapRowMapper());
results.putAll(processResultSet((ResultSet) out, rsParam));
results.putAll(processResultSet(resultSet, rsParam));
if (logger.isTraceEnabled()) {
logger.trace("Added default SqlReturnResultSet parameter named '" + rsName + "'");
}
@ -1543,18 +1542,13 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
/**
* Determine SQL from potential provider object.
* @param sqlProvider object which is potentially an SqlProvider
* @param obj object which is potentially an SqlProvider
* @return the SQL string, or {@code null} if not known
* @see SqlProvider
*/
@Nullable
private static String getSql(Object sqlProvider) {
if (sqlProvider instanceof SqlProvider) {
return ((SqlProvider) sqlProvider).getSql();
}
else {
return null;
}
private static String getSql(Object obj) {
return (obj instanceof SqlProvider sqlProvider ? sqlProvider.getSql() : null);
}
private static <T> T result(@Nullable T result) {
@ -1613,8 +1607,8 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// If return value is a JDBC Statement, apply statement settings
// (fetch size, max rows, transaction timeout).
if (retVal instanceof Statement) {
applyStatementSettings(((Statement) retVal));
if (retVal instanceof Statement statement) {
applyStatementSettings(statement);
}
return retVal;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -206,8 +206,8 @@ public class PreparedStatementCreatorFactory {
Set<String> names = new HashSet<>();
for (int i = 0; i < parameters.size(); i++) {
Object param = parameters.get(i);
if (param instanceof SqlParameterValue) {
names.add(((SqlParameterValue) param).getName());
if (param instanceof SqlParameterValue sqlParameterValue) {
names.add(sqlParameterValue.getName());
}
else {
names.add("Parameter #" + i);
@ -252,9 +252,9 @@ public class PreparedStatementCreatorFactory {
SqlParameter declaredParameter;
// SqlParameterValue overrides declared parameter meta-data, in particular for
// independence from the declared parameter position in case of named parameters.
if (in instanceof SqlParameterValue paramValue) {
in = paramValue.getValue();
declaredParameter = paramValue;
if (in instanceof SqlParameterValue sqlParameterValue) {
in = sqlParameterValue.getValue();
declaredParameter = sqlParameterValue;
}
else {
if (declaredParameters.size() <= i) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -193,9 +193,9 @@ public class SingleColumnRowMapper<T> implements RowMapper<T> {
return value.toString();
}
else if (Number.class.isAssignableFrom(requiredType)) {
if (value instanceof Number) {
if (value instanceof Number number) {
// Convert original Number to target Number class.
return NumberUtils.convertNumberToTargetClass(((Number) value), (Class<Number>) requiredType);
return NumberUtils.convertNumberToTargetClass(number, (Class<Number>) requiredType);
}
else {
// Convert stringified value to target Number class.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -569,8 +569,8 @@ public class CallMetaDataContext {
if (callParameterName == null) {
if (logger.isDebugEnabled()) {
Object value = parameterValue;
if (value instanceof SqlParameterValue) {
value = ((SqlParameterValue) value).getValue();
if (value instanceof SqlParameterValue sqlParameterValue) {
value = sqlParameterValue.getValue();
}
if (value != null) {
logger.debug("Unable to locate the corresponding IN or IN-OUT parameter for \"" +

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -105,8 +105,8 @@ public abstract class AbstractSqlParameterSource implements SqlParameterSource {
StringJoiner result = new StringJoiner(", ", getClass().getSimpleName() + " {", "}");
for (String parameterName : parameterNames) {
Object value = getValue(parameterName);
if (value instanceof SqlParameterValue) {
value = ((SqlParameterValue) value).getValue();
if (value instanceof SqlParameterValue sqlParameterValue) {
value = sqlParameterValue.getValue();
}
String typeName = getTypeName(parameterName);
if (typeName == null) {

View File

@ -291,11 +291,11 @@ public abstract class NamedParameterUtils {
actualSql.append(originalSql, lastIndex, startIndex);
if (paramSource != null && paramSource.hasValue(paramName)) {
Object value = paramSource.getValue(paramName);
if (value instanceof SqlParameterValue) {
value = ((SqlParameterValue) value).getValue();
if (value instanceof SqlParameterValue sqlParameterValue) {
value = sqlParameterValue.getValue();
}
if (value instanceof Iterable) {
Iterator<?> entryIter = ((Iterable<?>) value).iterator();
if (value instanceof Iterable<?> iterable) {
Iterator<?> entryIter = iterable.iterator();
int k = 0;
while (entryIter.hasNext()) {
if (k > 0) {

View File

@ -177,11 +177,11 @@ public class SqlLobValue implements DisposableSqlTypeValue {
if (this.content instanceof byte[] || this.content == null) {
this.lobCreator.setBlobAsBytes(ps, paramIndex, (byte[]) this.content);
}
else if (this.content instanceof String) {
this.lobCreator.setBlobAsBytes(ps, paramIndex, ((String) this.content).getBytes());
else if (this.content instanceof String string) {
this.lobCreator.setBlobAsBytes(ps, paramIndex, string.getBytes());
}
else if (this.content instanceof InputStream) {
this.lobCreator.setBlobAsBinaryStream(ps, paramIndex, (InputStream) this.content, this.length);
else if (this.content instanceof InputStream inputStream) {
this.lobCreator.setBlobAsBinaryStream(ps, paramIndex, inputStream, this.length);
}
else {
throw new IllegalArgumentException(
@ -192,11 +192,11 @@ public class SqlLobValue implements DisposableSqlTypeValue {
if (this.content instanceof String || this.content == null) {
this.lobCreator.setClobAsString(ps, paramIndex, (String) this.content);
}
else if (this.content instanceof InputStream) {
this.lobCreator.setClobAsAsciiStream(ps, paramIndex, (InputStream) this.content, this.length);
else if (this.content instanceof InputStream inputStream) {
this.lobCreator.setClobAsAsciiStream(ps, paramIndex, inputStream, this.length);
}
else if (this.content instanceof Reader) {
this.lobCreator.setClobAsCharacterStream(ps, paramIndex, (Reader) this.content, this.length);
else if (this.content instanceof Reader reader) {
this.lobCreator.setClobAsCharacterStream(ps, paramIndex, reader, this.length);
}
else {
throw new IllegalArgumentException(

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -162,11 +162,11 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
* @see org.springframework.transaction.jta.JtaTransactionManager
*/
public void setDataSource(@Nullable DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
if (dataSource instanceof TransactionAwareDataSourceProxy tadsp) {
// If we got a TransactionAwareDataSourceProxy, we need to perform transactions
// for its underlying target DataSource, else data access code won't see
// properly exposed transactions (i.e. transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
this.dataSource = tadsp.getTargetDataSource();
}
else {
this.dataSource = dataSource;

View File

@ -438,8 +438,8 @@ public abstract class DataSourceUtils {
*/
public static Connection getTargetConnection(Connection con) {
Connection conToUse = con;
while (conToUse instanceof ConnectionProxy) {
conToUse = ((ConnectionProxy) conToUse).getTargetConnection();
while (conToUse instanceof ConnectionProxy connectionProxy) {
conToUse = connectionProxy.getTargetConnection();
}
return conToUse;
}
@ -455,9 +455,9 @@ public abstract class DataSourceUtils {
private static int getConnectionSynchronizationOrder(DataSource dataSource) {
int order = CONNECTION_SYNCHRONIZATION_ORDER;
DataSource currDs = dataSource;
while (currDs instanceof DelegatingDataSource) {
while (currDs instanceof DelegatingDataSource delegatingDataSource) {
order--;
currDs = ((DelegatingDataSource) currDs).getTargetDataSource();
currDs = delegatingDataSource.getTargetDataSource();
}
return order;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -239,8 +239,8 @@ public class TransactionAwareDataSourceProxy extends DelegatingDataSource {
// If return value is a Statement, apply transaction timeout.
// Applies to createStatement, prepareStatement, prepareCall.
if (retVal instanceof Statement) {
DataSourceUtils.applyTransactionTimeout((Statement) retVal, this.targetDataSource);
if (retVal instanceof Statement statement) {
DataSourceUtils.applyTransactionTimeout(statement, this.targetDataSource);
}
return retVal;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -216,9 +216,9 @@ public class EmbeddedDatabaseFactory {
protected void shutdownDatabase() {
if (this.dataSource != null) {
if (logger.isInfoEnabled()) {
if (this.dataSource instanceof SimpleDriverDataSource) {
if (this.dataSource instanceof SimpleDriverDataSource simpleDriverDataSource) {
logger.info(String.format("Shutting down embedded database: url='%s'",
((SimpleDriverDataSource) this.dataSource).getUrl()));
simpleDriverDataSource.getUrl()));
}
else {
logger.info(String.format("Shutting down embedded database '%s'", this.databaseName));

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -299,8 +299,8 @@ public abstract class ScriptUtils {
}
}
catch (Exception ex) {
if (ex instanceof ScriptException) {
throw (ScriptException) ex;
if (ex instanceof ScriptException scriptException) {
throw scriptException;
}
throw new UncategorizedScriptException(
"Failed to execute database script from resource [" + resource + "]", ex);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -161,10 +161,10 @@ public class SqlFunction<T> extends MappingSqlQuery<T> {
*/
public int run(Object... parameters) {
Object obj = super.findObject(parameters);
if (!(obj instanceof Number)) {
if (!(obj instanceof Number number)) {
throw new TypeMismatchDataAccessException("Could not convert result object [" + obj + "] to int");
}
return ((Number) obj).intValue();
return number.intValue();
}
/**

View File

@ -213,10 +213,10 @@ public abstract class JdbcUtils {
if (obj instanceof String) {
return obj;
}
else if (obj instanceof Number) {
else if (obj instanceof Number number) {
// Defensively convert any Number to an Integer (as needed by our
// ConversionService's IntegerToEnumConverterFactory) for use as index
return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class);
return NumberUtils.convertNumberToTargetClass(number, Integer.class);
}
else {
// e.g. on Postgres: getObject returns a PGObject but we need a String
@ -405,8 +405,8 @@ public abstract class JdbcUtils {
"Could not access DatabaseMetaData method '" + metaDataMethodName + "'", ex);
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof SQLException) {
throw (SQLException) ex.getTargetException();
if (ex.getTargetException() instanceof SQLException sqlException) {
throw sqlException;
}
throw new MetaDataAccessException(
"Invocation of DatabaseMetaData method '" + metaDataMethodName + "' failed", ex);

View File

@ -216,8 +216,8 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep
// Try to find SQLException with actual error code, looping through the causes.
// E.g. applicable to java.sql.DataTruncation as of JDK 1.6.
SQLException current = sqlEx;
while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) {
current = (SQLException) current.getCause();
while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException sqlException) {
current = sqlException;
}
errorCode = Integer.toString(current.getErrorCode());
}