Nullability refinements on private and static methods

Based on IntelliJ IDEA 2017.3 introspection results.

Issue: SPR-15756
This commit is contained in:
Juergen Hoeller
2017-09-22 18:22:12 +02:00
parent 60f47f4489
commit 7ae59d0c2a
88 changed files with 319 additions and 300 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2017 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.
@@ -19,6 +19,7 @@ package org.springframework.jdbc;
import java.sql.SQLException;
import org.springframework.dao.UncategorizedDataAccessException;
import org.springframework.lang.Nullable;
/**
* Exception thrown when we can't classify a SQLException into
@@ -31,6 +32,7 @@ import org.springframework.dao.UncategorizedDataAccessException;
public class UncategorizedSQLException extends UncategorizedDataAccessException {
/** SQL that led to the problem */
@Nullable
private final String sql;
@@ -40,9 +42,10 @@ public class UncategorizedSQLException extends UncategorizedDataAccessException
* @param sql the offending SQL statement
* @param ex the root cause
*/
public UncategorizedSQLException(String task, String sql, SQLException ex) {
super(task + "; uncategorized SQLException for SQL [" + sql + "]; SQL state [" +
ex.getSQLState() + "]; error code [" + ex.getErrorCode() + "]; " + ex.getMessage(), ex);
public UncategorizedSQLException(String task, @Nullable String sql, SQLException ex) {
super(task + "; uncategorized SQLException" + (sql != null ? " for SQL [" + sql + "]" : "") +
"; SQL state [" + ex.getSQLState() + "]; error code [" + ex.getErrorCode() + "]; " +
ex.getMessage(), ex);
this.sql = sql;
}
@@ -55,8 +58,9 @@ public class UncategorizedSQLException extends UncategorizedDataAccessException
}
/**
* Return the SQL that led to the problem.
* Return the SQL that led to the problem (if known).
*/
@Nullable
public String getSql() {
return this.sql;
}

View File

@@ -41,6 +41,7 @@ import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.SQLWarningException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.jdbc.datasource.ConnectionProxy;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcAccessor;
@@ -329,9 +330,10 @@ 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.
String sql = getSql(action);
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("ConnectionCallback", getSql(action), ex);
throw translateException("ConnectionCallback", sql, ex);
}
finally {
DataSourceUtils.releaseConnection(con, getDataSource());
@@ -378,11 +380,12 @@ 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.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
@@ -446,12 +449,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {
return nonNull(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(sql, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public Map<String, Object> queryForMap(String sql) throws DataAccessException {
return nonNull(queryForObject(sql, getColumnMapRowMapper()));
return result(queryForObject(sql, getColumnMapRowMapper()));
}
@Override
@@ -479,7 +482,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public SqlRowSet queryForRowSet(String sql) throws DataAccessException {
return nonNull(query(sql, new SqlRowSetResultSetExtractor()));
return result(query(sql, new SqlRowSetResultSetExtractor()));
}
@Override
@@ -612,7 +615,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
ps = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("PreparedStatementCallback", sql, ex);
throw translateException("PreparedStatementCallback", sql, ex);
}
finally {
if (psc instanceof ParameterDisposer) {
@@ -728,27 +731,27 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public <T> List<T> query(PreparedStatementCreator psc, RowMapper<T> rowMapper) throws DataAccessException {
return nonNull(query(psc, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(psc, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> List<T> query(String sql, @Nullable PreparedStatementSetter pss, RowMapper<T> rowMapper) throws DataAccessException {
return nonNull(query(sql, pss, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(sql, pss, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> List<T> query(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper) throws DataAccessException {
return nonNull(query(sql, args, argTypes, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(sql, args, argTypes, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> List<T> query(String sql, @Nullable Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
return nonNull(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException {
return nonNull(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
return result(query(sql, args, new RowMapperResultSetExtractor<>(rowMapper)));
}
@Override
@@ -794,12 +797,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return nonNull(queryForObject(sql, args, argTypes, getColumnMapRowMapper()));
return result(queryForObject(sql, args, argTypes, getColumnMapRowMapper()));
}
@Override
public Map<String, Object> queryForMap(String sql, @Nullable Object... args) throws DataAccessException {
return nonNull(queryForObject(sql, args, getColumnMapRowMapper()));
return result(queryForObject(sql, args, getColumnMapRowMapper()));
}
@Override
@@ -829,12 +832,12 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
@Override
public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes) throws DataAccessException {
return nonNull(query(sql, args, argTypes, new SqlRowSetResultSetExtractor()));
return result(query(sql, args, argTypes, new SqlRowSetResultSetExtractor()));
}
@Override
public SqlRowSet queryForRowSet(String sql, @Nullable Object... args) throws DataAccessException {
return nonNull(query(sql, args, new SqlRowSetResultSetExtractor()));
return result(query(sql, args, new SqlRowSetResultSetExtractor()));
}
protected int update(final PreparedStatementCreator psc, @Nullable final PreparedStatementSetter pss)
@@ -882,7 +885,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
try {
RowMapperResultSetExtractor<Map<String, Object>> rse =
new RowMapperResultSetExtractor<>(getColumnMapRowMapper(), 1);
generatedKeys.addAll(nonNull(rse.extractData(keys)));
generatedKeys.addAll(result(rse.extractData(keys)));
}
finally {
JdbcUtils.closeResultSet(keys);
@@ -1057,7 +1060,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
cs = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("CallableStatementCallback", sql, ex);
throw translateException("CallableStatementCallback", sql, ex);
}
finally {
if (csc instanceof ParameterDisposer) {
@@ -1384,6 +1387,20 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
/**
* Translate the given {@link SQLException} into a generic {@link DataAccessException}.
* @param task readable text describing the task being attempted
* @param sql SQL query or update that caused the problem (may be {@code null})
* @param ex the offending {@code SQLException}
* @return a DataAccessException wrapping the {@code SQLException} (never {@code null})
* @since 5.0
* @see #getExceptionTranslator()
*/
protected DataAccessException translateException(String task, @Nullable String sql, SQLException ex) {
DataAccessException dae = getExceptionTranslator().translate(task, sql, ex);
return (dae != null ? dae : new UncategorizedSQLException(task, sql, ex));
}
/**
* Determine SQL from potential provider object.
@@ -1401,7 +1418,7 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
}
}
private static <T> T nonNull(@Nullable T result) {
private static <T> T result(@Nullable T result) {
Assert.state(result != null, "No result");
return result;
}

View File

@@ -26,7 +26,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.util.Assert;
/**
* Factory used to create a {@link CallMetaDataProvider} implementation
@@ -130,7 +129,6 @@ public class CallMetaDataProviderFactory {
}
return provider;
});
Assert.state(result != null, "No CallMetaDataProvider");
return result;
}
catch (MetaDataAccessException ex) {

View File

@@ -24,7 +24,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.util.Assert;
/**
* Factory used to create a {@link TableMetaDataProvider} implementation
@@ -77,7 +76,6 @@ public class TableMetaDataProviderFactory {
}
return provider;
});
Assert.state(result != null, "No TableMetaDataProvider");
return result;
}
catch (MetaDataAccessException ex) {

View File

@@ -76,6 +76,7 @@ public abstract class JdbcDaoSupport extends DaoSupport {
/**
* Return the JDBC DataSource used by this DAO.
*/
@Nullable
public final DataSource getDataSource() {
return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null);
}

View File

@@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -64,26 +65,26 @@ public abstract class AbstractFallbackSQLExceptionTranslator implements SQLExcep
* {@link #getFallbackTranslator() fallback translator} if necessary.
*/
@Override
@Nullable
public DataAccessException translate(@Nullable String task, @Nullable String sql, SQLException ex) {
@NonNull
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
Assert.notNull(ex, "Cannot translate a null SQLException");
if (task == null) {
task = "";
}
if (sql == null) {
sql = "";
DataAccessException dae = doTranslate(task, sql, ex);
if (dae != null) {
// Specific exception match found.
return dae;
}
DataAccessException dex = doTranslate(task, sql, ex);
if (dex != null) {
// Specific exception match found.
return dex;
}
// Looking for a fallback...
SQLExceptionTranslator fallback = getFallbackTranslator();
if (fallback != null) {
return fallback.translate(task, sql, ex);
dae = fallback.translate(task, sql, ex);
if (dae != null) {
// Fallback exception match found.
return dae;
}
}
// We couldn't identify it more precisely.
return new UncategorizedSQLException(task, sql, ex);
}
@@ -94,13 +95,13 @@ public abstract class AbstractFallbackSQLExceptionTranslator implements SQLExcep
* is allowed to return {@code null} to indicate that no exception match has
* been found and that fallback translation should kick in.
* @param task readable text describing the task being attempted
* @param sql SQL query or update that caused the problem
* @param sql SQL query or update that caused the problem (if known)
* @param ex the offending {@code SQLException}
* @return the DataAccessException, wrapping the {@code SQLException};
* or {@code null} if no exception match found
*/
@Nullable
protected abstract DataAccessException doTranslate(String task, String sql, SQLException ex);
protected abstract DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex);
/**
@@ -112,8 +113,8 @@ public abstract class AbstractFallbackSQLExceptionTranslator implements SQLExcep
* @param ex the offending {@code SQLException}
* @return the message {@code String} to use
*/
protected String buildMessage(String task, String sql, SQLException ex) {
return task + "; SQL [" + sql + "]; " + ex.getMessage();
protected String buildMessage(String task, @Nullable String sql, SQLException ex) {
return task + "; " + (sql != null ? "SQL [" + sql : "]; " + "") + ex.getMessage();
}
}

View File

@@ -97,11 +97,12 @@ public class DatabaseStartupValidator implements InitializingBean {
*/
@Override
public void afterPropertiesSet() {
if (this.dataSource == null) {
throw new IllegalArgumentException("dataSource is required");
DataSource dataSource = this.dataSource;
if (dataSource == null) {
throw new IllegalArgumentException("Property 'dataSource' is required");
}
if (this.validationQuery == null) {
throw new IllegalArgumentException("validationQuery is required");
throw new IllegalArgumentException("Property 'validationQuery' is required");
}
try {
@@ -114,10 +115,10 @@ public class DatabaseStartupValidator implements InitializingBean {
Connection con = null;
Statement stmt = null;
try {
con = this.dataSource.getConnection();
con = dataSource.getConnection();
if (con == null) {
throw new CannotGetJdbcConnectionException("Failed to execute validation query: " +
"DataSource returned null from getConnection(): " + this.dataSource);
"DataSource returned null from getConnection(): " + dataSource);
}
stmt = con.createStatement();
stmt.execute(this.validationQuery);

View File

@@ -132,6 +132,7 @@ public abstract class JdbcUtils {
* @throws SQLException if thrown by the JDBC API
* @see #getResultSetValue(ResultSet, int)
*/
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType) throws SQLException {
if (requiredType == null) {
return getResultSetValue(rs, index);
@@ -310,7 +311,6 @@ public abstract class JdbcUtils {
* the DatabaseMetaDataCallback's {@code processMetaData} method
* @throws MetaDataAccessException if meta data access failed
*/
@Nullable
public static Object extractDatabaseMetaData(DataSource dataSource, DatabaseMetaDataCallback action)
throws MetaDataAccessException {
@@ -350,7 +350,6 @@ public abstract class JdbcUtils {
* @see java.sql.DatabaseMetaData
*/
@SuppressWarnings("unchecked")
@Nullable
public static <T> T extractDatabaseMetaData(DataSource dataSource, final String metaDataMethodName)
throws MetaDataAccessException {

View File

@@ -169,7 +169,7 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep
@Override
@Nullable
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
SQLException sqlEx = ex;
if (sqlEx instanceof BatchUpdateException && sqlEx.getNextException() != null) {
SQLException nestedSqlEx = sqlEx.getNextException();
@@ -232,11 +232,11 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep
// Next, look for grouped error codes.
if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new BadSqlGrammarException(task, sql, sqlEx);
return new BadSqlGrammarException(task, (sql != null ? sql : ""), sqlEx);
}
else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
return new InvalidResultSetAccessException(task, sql, sqlEx);
return new InvalidResultSetAccessException(task, (sql != null ? sql : ""), sqlEx);
}
else if (Arrays.binarySearch(this.sqlErrorCodes.getDuplicateKeyCodes(), errorCode) >= 0) {
logTranslation(task, sql, sqlEx, false);
@@ -397,12 +397,12 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep
}
}
private void logTranslation(String task, String sql, SQLException sqlEx, boolean custom) {
private void logTranslation(String task, @Nullable String sql, SQLException sqlEx, boolean custom) {
if (logger.isDebugEnabled()) {
String intro = custom ? "Custom translation of" : "Translating";
logger.debug(intro + " SQLException with SQL state '" + sqlEx.getSQLState() +
"', error code '" + sqlEx.getErrorCode() + "', message [" + sqlEx.getMessage() +
"]; SQL was [" + sql + "] for task [" + task + "]");
"', error code '" + sqlEx.getErrorCode() + "', message [" + sqlEx.getMessage() + "]" +
(sql != null ? "; SQL was [" + sql + "]": "") + " for task [" + task + "]");
}
}

View File

@@ -32,6 +32,7 @@ import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ConcurrentReferenceHashMap;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
/**
* Factory for creating {@link SQLErrorCodes} based on the
@@ -211,7 +212,7 @@ public class SQLErrorCodesFactory {
// We could not find it - got to look it up.
try {
String name = JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName");
if (name != null) {
if (StringUtils.hasLength(name)) {
return registerDatabase(dataSource, name);
}
}

View File

@@ -64,7 +64,7 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException
@Override
@Nullable
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
if (ex instanceof SQLTransientException) {
if (ex instanceof SQLTransientConnectionException) {
return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
@@ -90,7 +90,7 @@ public class SQLExceptionSubclassTranslator extends AbstractFallbackSQLException
return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
}
else if (ex instanceof SQLSyntaxErrorException) {
return new BadSqlGrammarException(task, sql, ex);
return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
}
else if (ex instanceof SQLFeatureNotSupportedException) {
return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);

View File

@@ -46,12 +46,15 @@ public interface SQLExceptionTranslator {
* check (and subsequent cast) is considered reliable when expecting JDBC-based
* access to have happened.
* @param task readable text describing the task being attempted
* @param sql SQL query or update that caused the problem (may be {@code null})
* @param sql SQL query or update that caused the problem (if known)
* @param ex the offending {@code SQLException}
* @return the DataAccessException, wrapping the {@code SQLException}
* @return the DataAccessException wrapping the {@code SQLException},
* or {@code null} if no translation could be applied
* (in a custom translator; the default translators always throw an
* {@link org.springframework.jdbc.UncategorizedSQLException} in such a case)
* @see org.springframework.dao.DataAccessException#getRootCause()
*/
@Nullable
DataAccessException translate(@Nullable String task, @Nullable String sql, SQLException ex);
DataAccessException translate(String task, @Nullable String sql, SQLException ex);
}

View File

@@ -89,7 +89,7 @@ public class SQLStateSQLExceptionTranslator extends AbstractFallbackSQLException
@Override
@Nullable
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
// First, the getSQLState check...
String sqlState = getSqlState(ex);
if (sqlState != null && sqlState.length() >= 2) {
@@ -98,7 +98,7 @@ public class SQLStateSQLExceptionTranslator extends AbstractFallbackSQLException
logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
}
if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
return new BadSqlGrammarException(task, sql, ex);
return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
}
else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);