Updated for various code warnings

This commit addresses a number of deprications and other code warnings.
There are still many more to address, but this is a start.
This commit is contained in:
Michael Minella
2017-04-21 16:20:46 -05:00
parent a2a856e64b
commit 263e978a1f
128 changed files with 658 additions and 680 deletions

View File

@@ -107,10 +107,7 @@ public abstract class AbstractMethodInvokingDelegator<T> implements Initializing
try {
invoker.prepare();
}
catch (ClassNotFoundException e) {
throw new DynamicMethodInvocationException(e);
}
catch (NoSuchMethodException e) {
catch (ClassNotFoundException | NoSuchMethodException e) {
throw new DynamicMethodInvocationException(e);
}
@@ -132,8 +129,8 @@ public abstract class AbstractMethodInvokingDelegator<T> implements Initializing
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(targetObject);
Assert.hasLength(targetMethod);
Assert.notNull(targetObject, "targetObject must not be null");
Assert.hasLength(targetMethod, "targetMethod must not be empty");
Assert.state(targetClassDeclaresTargetMethod(),
"target class must declare a method with matching name and parameter types");
}
@@ -148,7 +145,7 @@ public abstract class AbstractMethodInvokingDelegator<T> implements Initializing
Method[] memberMethods = invoker.getTargetClass().getMethods();
Method[] declaredMethods = invoker.getTargetClass().getDeclaredMethods();
List<Method> allMethods = new ArrayList<Method>();
List<Method> allMethods = new ArrayList<>();
allMethods.addAll(Arrays.asList(memberMethods));
allMethods.addAll(Arrays.asList(declaredMethods));

View File

@@ -62,7 +62,7 @@ ItemWriter<T> {
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.notEmpty(fieldsUsedAsTargetMethodArguments);
Assert.notEmpty(fieldsUsedAsTargetMethodArguments, "fieldsUsedAsTargetMethodArguments must not be empty");
}
/**

View File

@@ -16,7 +16,15 @@
package org.springframework.batch.item.data;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.mongodb.util.JSON;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.InitializingBean;
@@ -30,13 +38,6 @@ import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* Restartable {@link ItemReader} that reads documents from MongoDB
@@ -117,7 +118,7 @@ public class MongoItemReader<T> extends AbstractPaginatedDataItemReader<T> imple
* {@link List} of values to be substituted in for each of the
* parameters in the query.
*
* @param parameterValues
* @param parameterValues values
*/
public void setParameterValues(List<Object> parameterValues) {
this.parameterValues = parameterValues;
@@ -163,11 +164,11 @@ public class MongoItemReader<T> extends AbstractPaginatedDataItemReader<T> imple
@SuppressWarnings("unchecked")
protected Iterator<T> doPageRead() {
Pageable pageRequest = new PageRequest(page, pageSize, sort);
Pageable pageRequest = PageRequest.of(page, pageSize, sort);
String populatedQuery = replacePlaceholders(query, parameterValues);
Query mongoQuery = null;
Query mongoQuery;
if(StringUtils.hasText(fields)) {
mongoQuery = new BasicQuery(populatedQuery, fields);
@@ -222,12 +223,12 @@ public class MongoItemReader<T> extends AbstractPaginatedDataItemReader<T> imple
}
private Sort convertToSort(Map<String, Sort.Direction> sorts) {
List<Sort.Order> sortValues = new ArrayList<Sort.Order>();
List<Sort.Order> sortValues = new ArrayList<>();
for (Map.Entry<String, Sort.Direction> curSort : sorts.entrySet()) {
sortValues.add(new Sort.Order(curSort.getValue(), curSort.getKey()));
}
return new Sort(sortValues);
return Sort.by(sortValues);
}
}

View File

@@ -20,7 +20,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
/**
* <p>
@@ -29,19 +28,16 @@ import org.neo4j.ogm.session.SessionFactory;
*
* @author Michael Minella
*/
public class Neo4jItemReader<T> extends AbstractNeo4jItemReader {
public class Neo4jItemReader<T> extends AbstractNeo4jItemReader<T> {
@SuppressWarnings("unchecked")
@Override
protected Iterator<T> doPageRead() {
SessionFactory factory = getSessionFactory();
Session session = getSessionFactory().openSession();
Iterable<T> queryResults;
Session session = factory.openSession();
queryResults = session.query(getTargetType(),
generateLimitCypherQuery(),
getParameterValues());
Iterable<T> queryResults = session.query(getTargetType(),
generateLimitCypherQuery(),
getParameterValues());
if(queryResults != null) {
return queryResults.iterator();

View File

@@ -127,7 +127,7 @@ public class RepositoryItemReader<T> extends AbstractItemCountingItemStreamItemR
* Specifies what method on the repository to call. This method must take
* {@link org.springframework.data.domain.Pageable} as the <em>last</em> argument.
*
* @param methodName
* @param methodName name of the method to invoke
*/
public void setMethodName(String methodName) {
this.methodName = methodName;
@@ -187,15 +187,16 @@ public class RepositoryItemReader<T> extends AbstractItemCountingItemStreamItemR
* Available for overriding as needed.
*
* @return the list of items that make up the page
* @throws Exception
* @throws Exception Based on what the underlying method throws or related to the
* calling of the method
*/
@SuppressWarnings("unchecked")
protected List<T> doPageRead() throws Exception {
Pageable pageRequest = new PageRequest(page, pageSize, sort);
Pageable pageRequest = PageRequest.of(page, pageSize, sort);
MethodInvoker invoker = createMethodInvoker(repository, methodName);
List<Object> parameters = new ArrayList<Object>();
List<Object> parameters = new ArrayList<>();
if(arguments != null && arguments.size() > 0) {
parameters.addAll(arguments);
@@ -224,23 +225,20 @@ public class RepositoryItemReader<T> extends AbstractItemCountingItemStreamItemR
}
private Sort convertToSort(Map<String, Sort.Direction> sorts) {
List<Sort.Order> sortValues = new ArrayList<Sort.Order>();
List<Sort.Order> sortValues = new ArrayList<>();
for (Map.Entry<String, Sort.Direction> curSort : sorts.entrySet()) {
sortValues.add(new Sort.Order(curSort.getValue(), curSort.getKey()));
}
return new Sort(sortValues);
return Sort.by(sortValues);
}
private Object doInvoke(MethodInvoker invoker) throws Exception{
try {
invoker.prepare();
}
catch (ClassNotFoundException e) {
throw new DynamicMethodInvocationException(e);
}
catch (NoSuchMethodException e) {
catch (ClassNotFoundException | NoSuchMethodException e) {
throw new DynamicMethodInvocationException(e);
}

View File

@@ -246,7 +246,7 @@ implements InitializingBean {
/**
* Moves the cursor in the ResultSet to the position specified by the row
* parameter by traversing the ResultSet.
* @param row
* @param row The index of the row to move to
*/
private void moveCursorToRow(int row) {
try {

View File

@@ -143,10 +143,7 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
* @return true or false
*/
public boolean isCloseSuppressionActive(Connection connection) {
if (connection == null) {
return false;
}
return connection.equals(closeSuppressedConnection);
return connection != null && connection.equals(closeSuppressedConnection);
}
/**
@@ -240,6 +237,7 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
* @param target the original Connection to wrap
* @return the wrapped Connection
*/
@SuppressWarnings("rawtypes")
protected Connection getCloseSuppressingConnectionProxy(Connection target) {
return (Connection) Proxy.newProxyInstance(ConnectionProxy.class.getClassLoader(),
new Class[] { ConnectionProxy.class }, new CloseSuppressingInvocationHandler(target, this));
@@ -265,29 +263,27 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on ConnectionProxy interface coming in...
if (method.getName().equals("equals")) {
// Only consider equal when proxies are identical.
return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
}
else if (method.getName().equals("hashCode")) {
// Use hashCode of Connection proxy.
return new Integer(System.identityHashCode(proxy));
}
else if (method.getName().equals("close")) {
// Handle close method: don't pass the call on if we are
// suppressing close calls.
if (dataSource.completeCloseCall((Connection) proxy)) {
return null;
}
else {
target.close();
return null;
}
}
else if (method.getName().equals("getTargetConnection")) {
// Handle getTargetConnection method: return underlying
// Connection.
return this.target;
switch (method.getName()) {
case "equals":
// Only consider equal when proxies are identical.
return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE);
case "hashCode":
// Use hashCode of Connection proxy.
return System.identityHashCode(proxy);
case "close":
// Handle close method: don't pass the call on if we are
// suppressing close calls.
if (dataSource.completeCloseCall((Connection) proxy)) {
return null;
}
else {
target.close();
return null;
}
case "getTargetConnection":
// Handle getTargetConnection method: return underlying
// Connection.
return this.target;
}
// Invoke method on target Connection.
@@ -306,10 +302,7 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
*/
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
if (iface.isAssignableFrom(SmartDataSource.class) || iface.isAssignableFrom(dataSource.getClass())) {
return true;
}
return false;
return iface.isAssignableFrom(SmartDataSource.class) || iface.isAssignableFrom(dataSource.getClass());
}
/**
@@ -334,7 +327,7 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource);
Assert.notNull(dataSource, "DataSource is required");
}
/**
@@ -348,14 +341,8 @@ public class ExtendedConnectionDataSourceProxy implements SmartDataSource, Initi
try {
invoker.prepare();
return (Logger) invoker.invoke();
} catch (ClassNotFoundException cnfe) {
throw new SQLFeatureNotSupportedException(cnfe);
} catch (NoSuchMethodException nsme) {
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException nsme) {
throw new SQLFeatureNotSupportedException(nsme);
} catch (IllegalAccessException iae) {
throw new SQLFeatureNotSupportedException(iae);
} catch (InvocationTargetException ite) {
throw new SQLFeatureNotSupportedException(ite);
}
}
}

View File

@@ -115,7 +115,7 @@ public class HibernateCursorItemReader<T> extends AbstractItemCountingItemStream
*
* @param queryProvider Hibernate query provider
*/
public void setQueryProvider(HibernateQueryProvider queryProvider) {
public void setQueryProvider(HibernateQueryProvider<T> queryProvider) {
helper.setQueryProvider(queryProvider);
}

View File

@@ -40,6 +40,7 @@ import org.springframework.util.StringUtils;
* @author Dave Syer
*
*/
@SuppressWarnings("rawtype")
public class HibernateItemReaderHelper<T> implements InitializingBean {
private SessionFactory sessionFactory;
@@ -48,7 +49,7 @@ public class HibernateItemReaderHelper<T> implements InitializingBean {
private String queryName = "";
private HibernateQueryProvider queryProvider;
private HibernateQueryProvider<T> queryProvider;
private boolean useStatelessSession = true;
@@ -73,7 +74,7 @@ public class HibernateItemReaderHelper<T> implements InitializingBean {
/**
* @param queryProvider Hibernate query provider
*/
public void setQueryProvider(HibernateQueryProvider queryProvider) {
public void setQueryProvider(HibernateQueryProvider<T> queryProvider) {
this.queryProvider = queryProvider;
}

View File

@@ -108,7 +108,7 @@ public class HibernatePagingItemReader<T> extends AbstractPagingItemReader<T>
*
* @param queryProvider Hibernate query provider
*/
public void setQueryProvider(HibernateQueryProvider queryProvider) {
public void setQueryProvider(HibernateQueryProvider<T> queryProvider) {
helper.setQueryProvider(queryProvider);
}

View File

@@ -31,6 +31,7 @@ public interface ItemPreparedStatementSetter<T> {
/**
* Set parameter values on the given PreparedStatement as determined from
* the provided item.
* @param item the item to obtain the values from
* @param ps the PreparedStatement to invoke setter methods on
* @throws SQLException if a SQLException is encountered (i.e. there is no
* need to catch SQLException)

View File

@@ -142,7 +142,7 @@ public class JdbcBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
public void afterPropertiesSet() {
Assert.notNull(namedParameterJdbcTemplate, "A DataSource or a NamedParameterJdbcTemplate is required.");
Assert.notNull(sql, "An SQL statement is required.");
List<String> namedParameters = new ArrayList<String>();
List<String> namedParameters = new ArrayList<>();
parameterCount = JdbcParameterUtils.countParameterPlaceholders(sql, namedParameters);
if (namedParameters.size() > 0) {
if (parameterCount != namedParameters.size()) {
@@ -158,7 +158,7 @@ public class JdbcBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
/* (non-Javadoc)
* @see org.springframework.batch.item.ItemWriter#write(java.util.List)
*/
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void write(final List<? extends T> items) throws Exception {

View File

@@ -68,7 +68,7 @@ public class JdbcCursorItemReader<T> extends AbstractCursorItemReader<T> {
/**
* Set the RowMapper to be used for all calls to read().
*
* @param rowMapper
* @param rowMapper the mapper used to map each item
*/
public void setRowMapper(RowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
@@ -79,7 +79,7 @@ public class JdbcCursorItemReader<T> extends AbstractCursorItemReader<T> {
* should be a complete and valid SQL statement, as it will be run directly
* without any modification.
*
* @param sql
* @param sql SQL statement
*/
public void setSql(String sql) {
this.sql = sql;
@@ -89,7 +89,7 @@ public class JdbcCursorItemReader<T> extends AbstractCursorItemReader<T> {
* Set the PreparedStatementSetter to use if any parameter values that need
* to be set in the supplied query.
*
* @param preparedStatementSetter
* @param preparedStatementSetter PreparedStatementSetter responsible for filling out the statement
*/
public void setPreparedStatementSetter(PreparedStatementSetter preparedStatementSetter) {
this.preparedStatementSetter = preparedStatementSetter;

View File

@@ -163,14 +163,14 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.notNull(dataSource);
Assert.notNull(dataSource, "DataSource may not be null");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
if (fetchSize != VALUE_NOT_SET) {
jdbcTemplate.setFetchSize(fetchSize);
}
jdbcTemplate.setMaxRows(getPageSize());
namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
Assert.notNull(queryProvider);
Assert.notNull(queryProvider, "QueryProvider may not be null");
queryProvider.init(dataSource);
this.firstPageSql = queryProvider.generateFirstPageQuery(getPageSize());
this.remainingPagesSql = queryProvider.generateRemainingPagesQuery(getPageSize());
@@ -180,7 +180,7 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
@SuppressWarnings("unchecked")
protected void doReadPage() {
if (results == null) {
results = new CopyOnWriteArrayList<T>();
results = new CopyOnWriteArrayList<>();
}
else {
results.clear();
@@ -253,7 +253,7 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
startAfterValues = (Map<String, Object>) executionContext.get(getExecutionContextKey(START_AFTER_VALUE));
if(startAfterValues == null) {
startAfterValues = new LinkedHashMap<String, Object>();
startAfterValues = new LinkedHashMap<>();
}
}
@@ -285,7 +285,7 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
}
private Map<String, Object> getParameterMap(Map<String, Object> values, Map<String, Object> sortKeyValues) {
Map<String, Object> parameterMap = new LinkedHashMap<String, Object>();
Map<String, Object> parameterMap = new LinkedHashMap<>();
if (values != null) {
parameterMap.putAll(values);
}
@@ -301,14 +301,14 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
}
private List<Object> getParameterList(Map<String, Object> values, Map<String, Object> sortKeyValue) {
SortedMap<String, Object> sm = new TreeMap<String, Object>();
SortedMap<String, Object> sm = new TreeMap<>();
if (values != null) {
sm.putAll(values);
}
List<Object> parameterList = new ArrayList<Object>();
List<Object> parameterList = new ArrayList<>();
parameterList.addAll(sm.values());
if (sortKeyValue != null && sortKeyValue.size() > 0) {
List<Map.Entry<String, Object>> keys = new ArrayList<Map.Entry<String,Object>>(sortKeyValue.entrySet());
List<Map.Entry<String, Object>> keys = new ArrayList<>(sortKeyValue.entrySet());
for(int i = 0; i < keys.size(); i++) {
for(int j = 0; j < i; j++) {
@@ -328,7 +328,7 @@ public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> impleme
private class PagingRowMapper implements RowMapper<T> {
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
startAfterValues = new LinkedHashMap<String, Object>();
startAfterValues = new LinkedHashMap<>();
for (Map.Entry<String, Order> sortKey : queryProvider.getSortKeys().entrySet()) {
startAfterValues.put(sortKey.getKey(), rs.getObject(sortKey.getKey()));
}

View File

@@ -45,6 +45,8 @@ public class JdbcParameterUtils {
* suite the batch processing requirements.
*
* @param sql String to search in. Returns 0 if the given String is <code>null</code>.
* @param namedParameterHolder holder for the named parameters
* @return the number of named parameter placeholders
*/
public static int countParameterPlaceholders(String sql, List<String> namedParameterHolder ) {
if (sql == null) {

View File

@@ -89,7 +89,7 @@ public class JpaPagingItemReader<T> extends AbstractPagingItemReader<T> {
private EntityManager entityManager;
private final Map<String, Object> jpaPropertyMap = new HashMap<String, Object>();
private final Map<String, Object> jpaPropertyMap = new HashMap<>();
private String queryString;
@@ -136,7 +136,7 @@ public class JpaPagingItemReader<T> extends AbstractPagingItemReader<T> {
* particular transaction. (e.g. Hibernate with a JTA transaction). NOTE: may cause
* problems in guaranteeing the object consistency in the EntityManagerFactory.
*
* @param transacted
* @param transacted indicator
*/
public void setTransacted(boolean transacted) {
this.transacted = transacted;
@@ -147,12 +147,8 @@ public class JpaPagingItemReader<T> extends AbstractPagingItemReader<T> {
super.afterPropertiesSet();
if (queryProvider == null) {
Assert.notNull(entityManagerFactory);
Assert.hasLength(queryString);
}
// making sure that the appropriate (JPA) query provider is set
else {
Assert.isTrue(queryProvider != null, "JPA query provider must be set");
Assert.notNull(entityManagerFactory, "EntityManager is required when queryProvider is null");
Assert.hasLength(queryString, "Query string is required when queryProvider is null");
}
}
@@ -209,7 +205,7 @@ public class JpaPagingItemReader<T> extends AbstractPagingItemReader<T> {
}
if (results == null) {
results = new CopyOnWriteArrayList<T>();
results = new CopyOnWriteArrayList<>();
}
else {
results.clear();

View File

@@ -16,8 +16,8 @@
package org.springframework.batch.item.database;
import javax.sql.DataSource;
import java.util.Map;
import javax.sql.DataSource;
/**
@@ -34,6 +34,7 @@ public interface PagingQueryProvider {
* Initialize the query provider using the provided {@link DataSource} if necessary.
*
* @param dataSource DataSource to use for any initialization
* @throws Exception for errors when initializing
*/
void init(DataSource dataSource) throws Exception;

View File

@@ -81,7 +81,7 @@ public class StoredProcedureItemReader<T> extends AbstractCursorItemReader<T> {
/**
* Set the RowMapper to be used for all calls to read().
*
* @param rowMapper
* @param rowMapper the RowMapper to use to map the results
*/
public void setRowMapper(RowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
@@ -92,7 +92,7 @@ public class StoredProcedureItemReader<T> extends AbstractCursorItemReader<T> {
* should be a complete and valid SQL statement, as it will be run directly
* without any modification.
*
* @param sprocedureName
* @param sprocedureName the SQL used to call the statement
*/
public void setProcedureName(String sprocedureName) {
this.procedureName = sprocedureName;
@@ -102,7 +102,7 @@ public class StoredProcedureItemReader<T> extends AbstractCursorItemReader<T> {
* Set the PreparedStatementSetter to use if any parameter values that need
* to be set in the supplied query.
*
* @param preparedStatementSetter
* @param preparedStatementSetter used to populate the SQL
*/
public void setPreparedStatementSetter(PreparedStatementSetter preparedStatementSetter) {
this.preparedStatementSetter = preparedStatementSetter;
@@ -120,6 +120,8 @@ public class StoredProcedureItemReader<T> extends AbstractCursorItemReader<T> {
/**
* Set whether this stored procedure is a function.
*
* @param function indicator
*/
public void setFunction(boolean function) {
this.function = function;

View File

@@ -45,7 +45,7 @@ public class HibernateCursorItemReaderBuilder<T> {
private int fetchSize;
private HibernateQueryProvider queryProvider;
private HibernateQueryProvider<T> queryProvider;
private String queryString;
@@ -124,7 +124,7 @@ public class HibernateCursorItemReaderBuilder<T> {
* @return this instance for method chaining
* @see HibernateCursorItemReader#setQueryProvider(HibernateQueryProvider)
*/
public HibernateCursorItemReaderBuilder<T> queryProvider(HibernateQueryProvider queryProvider) {
public HibernateCursorItemReaderBuilder<T> queryProvider(HibernateQueryProvider<T> queryProvider) {
this.queryProvider = queryProvider;
return this;

View File

@@ -167,6 +167,7 @@ public class JdbcBatchItemWriterBuilder<T> {
*
* @return a {@link JdbcBatchItemWriter}
*/
@SuppressWarnings("unchecked")
public JdbcBatchItemWriter<T> build() {
Assert.state(this.dataSource != null || this.namedParameterJdbcTemplate != null,
"Either a DataSource or a NamedParameterJdbcTemplate is required");

View File

@@ -35,7 +35,7 @@ import org.hibernate.StatelessSession;
* @since 2.1
*
*/
public abstract class AbstractHibernateQueryProvider implements HibernateQueryProvider {
public abstract class AbstractHibernateQueryProvider<T> implements HibernateQueryProvider<T> {
private StatelessSession statelessSession;
private Session statefulSession;

View File

@@ -43,7 +43,7 @@ public abstract class AbstractJpaQueryProvider implements JpaQueryProvider, Init
* {@link HibernateQueryProvider} to participate in a user's managed transaction.
* </p>
*
* @param entityManager
* @param entityManager EntityManager to use
*/
@Override
public void setEntityManager(EntityManager entityManager) {

View File

@@ -33,7 +33,7 @@ import org.springframework.batch.item.ItemReader;
* @since 2.1
*
*/
public interface HibernateQueryProvider {
public interface HibernateQueryProvider<T> {
/**
* <p>
@@ -43,7 +43,7 @@ public interface HibernateQueryProvider {
*
* @return created query
*/
Query createQuery();
Query<T> createQuery();
/**
* <p>

View File

@@ -16,6 +16,12 @@
package org.springframework.batch.item.database.support;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.batch.item.database.JdbcParameterUtils;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.PagingQueryProvider;
@@ -23,12 +29,6 @@ import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract SQL Paging Query Provider to serve as a base class for all provided
* SQL paging query providers.
@@ -182,7 +182,7 @@ public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvi
*/
@Override
public void init(DataSource dataSource) throws Exception {
Assert.notNull(dataSource);
Assert.notNull(dataSource, "A DataSource is required");
Assert.hasLength(selectClause, "selectClause must be specified");
Assert.hasLength(fromClause, "fromClause must be specified");
Assert.notEmpty(sortKeys, "sortKey must be specified");

View File

@@ -152,7 +152,7 @@ InitializingBean {
/**
* Setter for resource. Represents a file that can be written.
*
* @param resource
* @param resource the resource to be written to
*/
@Override
public void setResource(Resource resource) {
@@ -208,7 +208,7 @@ InitializingBean {
* update. Setting this to false means that it will always start at the
* beginning on a restart.
*
* @param saveState
* @param saveState if true, state will be persisted
*/
public void setSaveState(boolean saveState) {
this.saveState = saveState;
@@ -448,14 +448,14 @@ InitializingBean {
}
/**
* @param append
* @param append if true, append to previously created file
*/
public void setAppendAllowed(boolean append) {
this.append = append;
}
/**
* @param executionContext
* @param executionContext state from which to restore writing from
*/
public void restoreFrom(ExecutionContext executionContext) {
lastMarkedByteOffsetPosition = executionContext.getLong(getExecutionContextKey(RESTART_DATA_NAME));
@@ -470,14 +470,14 @@ InitializingBean {
}
/**
* @param shouldDeleteIfExists
* @param shouldDeleteIfExists indicator
*/
public void setDeleteIfExists(boolean shouldDeleteIfExists) {
this.shouldDeleteIfExists = shouldDeleteIfExists;
}
/**
* @param encoding
* @param encoding file encoding
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
@@ -527,7 +527,7 @@ InitializingBean {
}
/**
* @param line
* @param line String to be written to the file
* @throws IOException
*/
public void write(String line) throws IOException {
@@ -542,7 +542,7 @@ InitializingBean {
/**
* Truncate the output at the last known good point.
*
* @throws IOException
* @throws IOException if unable to work with file
*/
public void truncate() throws IOException {
fileChannel.truncate(lastMarkedByteOffsetPosition);
@@ -552,7 +552,7 @@ InitializingBean {
/**
* Creates the buffered writer for the output file channel based on
* configuration information.
* @throws IOException
* @throws IOException if unable to initialize buffer
*/
private void initializeBufferedWriter() throws IOException {
@@ -574,7 +574,8 @@ InitializingBean {
}
}
Assert.state(outputBufferedWriter != null);
Assert.state(outputBufferedWriter != null,
"Unable to initialize buffered writer");
// in case of restarting reset position to last committed point
if (restarted) {
checkFileSize();
@@ -596,12 +597,7 @@ InitializingBean {
try {
final FileChannel channel = fileChannel;
if (transactional) {
TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, new Runnable() {
@Override
public void run() {
closeStream();
}
});
TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, () -> closeStream());
writer.setEncoding(encoding);
writer.setForceSync(forceSync);

View File

@@ -380,7 +380,7 @@ public class FlatFileItemReaderBuilder<T> {
* Builds the {@link FlatFileItemReader}.
*
* @return a {@link FlatFileItemReader}
* @throws Exception
* @throws Exception if an error occurs during construction
*/
public FlatFileItemReader<T> build() throws Exception {
if(this.saveState) {
@@ -574,7 +574,7 @@ public class FlatFileItemReaderBuilder<T> {
* Returns a {@link DelimitedLineTokenizer}
*
* @return {@link DelimitedLineTokenizer}
* @throws Exception
* @throws Exception if an error occurs during construction
*/
public DelimitedLineTokenizer build() throws Exception {
Assert.notNull(this.fieldSetFactory, "A FieldSetFactory is required.");

View File

@@ -16,6 +16,15 @@
package org.springframework.batch.item.file.mapping;
import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.support.DefaultPropertyEditorRegistrar;
import org.springframework.beans.BeanWrapperImpl;
@@ -32,15 +41,6 @@ import org.springframework.util.ReflectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.DataBinder;
import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* {@link FieldSetMapper} implementation based on bean property paths. The
* {@link FieldSet} to be mapped should have field name meta data corresponding
@@ -198,7 +198,7 @@ public class BeanWrapperFieldSetMapper<T> extends DefaultPropertyEditorRegistrar
* {@link #initBinder(DataBinder)} and
* {@link #registerCustomEditors(PropertyEditorRegistry)}.
*
* @param target
* @param target Object to bind to
* @return a {@link DataBinder} that can be used to bind properties to the
* target.
*/
@@ -243,9 +243,8 @@ public class BeanWrapperFieldSetMapper<T> extends DefaultPropertyEditorRegistrar
}
/**
* @param bean
* @param properties
* @return
* @param bean Object to get properties for
* @param properties Properties to retrieve
*/
private Properties getBeanProperties(Object bean, Properties properties) {
@@ -254,9 +253,9 @@ public class BeanWrapperFieldSetMapper<T> extends DefaultPropertyEditorRegistrar
// Map from field names to property names
DistanceHolder distanceKey = new DistanceHolder(cls, distanceLimit);
if (!propertiesMatched.containsKey(distanceKey)) {
propertiesMatched.putIfAbsent(distanceKey, new ConcurrentHashMap<String, String>());
propertiesMatched.putIfAbsent(distanceKey, new ConcurrentHashMap<>());
}
Map<String, String> matches = new HashMap<String, String>(propertiesMatched.get(distanceKey));
Map<String, String> matches = new HashMap<>(propertiesMatched.get(distanceKey));
@SuppressWarnings({ "unchecked", "rawtypes" })
Set<String> keys = new HashSet(properties.keySet());
@@ -285,7 +284,7 @@ public class BeanWrapperFieldSetMapper<T> extends DefaultPropertyEditorRegistrar
}
}
propertiesMatched.replace(distanceKey, new ConcurrentHashMap<String, String>(matches));
propertiesMatched.replace(distanceKey, new ConcurrentHashMap<>(matches));
return properties;
}
@@ -378,7 +377,7 @@ public class BeanWrapperFieldSetMapper<T> extends DefaultPropertyEditorRegistrar
* {@link #mapFieldSet(FieldSet)} will fail of the FieldSet contains fields
* that cannot be mapped to the bean.
*
* @param strict
* @param strict indicator
*/
public void setStrict(boolean strict) {
this.strict = strict;

View File

@@ -35,6 +35,7 @@ public interface FieldSetMapper<T> {
* Method used to map data obtained from a {@link FieldSet} into an object.
*
* @param fieldSet the {@link FieldSet} to map
* @return the populated object
* @throws BindException if there is a problem with the binding
*/
T mapFieldSet(FieldSet fieldSet) throws BindException;

View File

@@ -45,6 +45,8 @@ public class DefaultRecordSeparatorPolicy extends SimpleRecordSeparatorPolicy {
/**
* Convenient constructor with quote character as parameter.
*
* @param quoteCharacter value used to indicate a quoted string
*/
public DefaultRecordSeparatorPolicy(String quoteCharacter) {
this(quoteCharacter, CONTINUATION);
@@ -53,6 +55,9 @@ public class DefaultRecordSeparatorPolicy extends SimpleRecordSeparatorPolicy {
/**
* Convenient constructor with quote character and continuation marker as
* parameters.
*
* @param quoteCharacter value used to indicate a quoted string
* @param continuation value used to indicate a line continuation
*/
public DefaultRecordSeparatorPolicy(String quoteCharacter, String continuation) {
super();

View File

@@ -38,7 +38,7 @@ public class SuffixRecordSeparatorPolicy extends DefaultRecordSeparatorPolicy {
/**
* Lines ending in this terminator String signal the end of a record.
*
* @param suffix
* @param suffix suffix to indicate the end of a record
*/
public void setSuffix(String suffix) {
this.suffix = suffix;
@@ -48,7 +48,7 @@ public class SuffixRecordSeparatorPolicy extends DefaultRecordSeparatorPolicy {
* Flag to indicate that the decision to terminate a record should ignore
* whitespace at the end of the line.
*
* @param ignoreWhitespace
* @param ignoreWhitespace indicator
*/
public void setIgnoreWhitespace(boolean ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;

View File

@@ -77,7 +77,7 @@ public abstract class AbstractLineTokenizer implements LineTokenizer {
* Setter for column names. Optional, but if set, then all lines must have
* as many or fewer tokens.
*
* @param names
* @param names names of each column
*/
public void setNames(String[] names) {
this.names = names==null ? null : Arrays.asList(names).toArray(new String[names.length]);

View File

@@ -29,10 +29,6 @@ public enum Alignment {
private String code;
private String label;
/**
* @param code
* @param label
*/
private Alignment(String code, String label) {
Assert.notNull(code, "'code' must not be null");

View File

@@ -102,8 +102,8 @@ public class DefaultFieldSet implements FieldSet {
* @see FieldSet#readString(String)
*/
public DefaultFieldSet(String[] tokens, String[] names) {
Assert.notNull(tokens);
Assert.notNull(names);
Assert.notNull(tokens, "Tokens must not be null");
Assert.notNull(names, "Names must not be null");
if (tokens.length != names.length) {
throw new IllegalArgumentException("Field names must be same length as values: names="
+ Arrays.asList(names) + ", values=" + Arrays.asList(tokens));

View File

@@ -80,7 +80,7 @@ public class DelimitedLineTokenizer extends AbstractLineTokenizer
* @param delimiter the desired delimiter. This is required
*/
public DelimitedLineTokenizer(String delimiter) {
Assert.notNull(delimiter);
Assert.notNull(delimiter, "A delimiter is required");
Assert.state(!delimiter.equals(String.valueOf(DEFAULT_QUOTE_CHARACTER)), "[" + DEFAULT_QUOTE_CHARACTER
+ "] is not allowed as delimiter for tokenizers.");
@@ -91,7 +91,7 @@ public class DelimitedLineTokenizer extends AbstractLineTokenizer
/**
* Setter for the delimiter character.
*
* @param delimiter
* @param delimiter the String used as a delimiter
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
@@ -106,7 +106,7 @@ public class DelimitedLineTokenizer extends AbstractLineTokenizer
* @param includedFields the included fields to set
*/
public void setIncludedFields(int[] includedFields) {
this.includedFields = new HashSet<Integer>();
this.includedFields = new HashSet<>();
for (int i : includedFields) {
this.includedFields.add(i);
}
@@ -139,7 +139,7 @@ public class DelimitedLineTokenizer extends AbstractLineTokenizer
@Override
protected List<String> doTokenize(String line) {
List<String> tokens = new ArrayList<String>();
List<String> tokens = new ArrayList<>();
// line is never null in current implementation
// line is checked in parent: AbstractLineTokenizer.tokenize()
@@ -281,6 +281,6 @@ public class DelimitedLineTokenizer extends AbstractLineTokenizer
@Override
public void afterPropertiesSet() throws Exception {
Assert.state(null != delimiter && 0 != delimiter.length());
Assert.hasLength(this.delimiter, "A delimiter is required");
}
}

View File

@@ -50,7 +50,7 @@ public abstract class ExtractorLineAggregator<T> implements LineAggregator<T> {
*/
@Override
public String aggregate(T item) {
Assert.notNull(item);
Assert.notNull(item, "Item is required");
Object[] fields = this.fieldExtractor.extract(item);
//

View File

@@ -78,7 +78,7 @@ public class FormatterLineAggregator<T> extends ExtractorLineAggregator<T> {
@Override
protected String doAggregate(Object[] fields) {
Assert.notNull(format);
Assert.notNull(format, "A format is required");
String value = String.format(locale, format, fields);

View File

@@ -162,7 +162,7 @@ public class LdifReader extends AbstractItemCountingItemStreamItemReader<LdapAtt
public void afterPropertiesSet() throws Exception {
Assert.notNull(resource, "A resource is required to parse.");
Assert.notNull(ldifParser);
Assert.notNull(ldifParser, "A parser is required");
}
}

View File

@@ -171,7 +171,7 @@ public class MappingLdifReader<T> extends AbstractItemCountingItemStreamItemRead
public void afterPropertiesSet() throws Exception {
Assert.notNull(resource, "A resource is required to parse.");
Assert.notNull(ldifParser);
Assert.notNull(ldifParser, "A parser is required");
}
}

View File

@@ -51,7 +51,7 @@ public final class FileUtils {
*/
public static void setUpOutputFile(File file, boolean restarted, boolean append, boolean overwriteOutputFile) {
Assert.notNull(file);
Assert.notNull(file, "An output file is required");
try {
if (!restarted) {

View File

@@ -352,7 +352,7 @@ ResourceAwareItemWriterItemStream<T>, InitializingBean {
*/
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(marshaller);
Assert.notNull(marshaller, "A Marshaller is required");
if (rootTagName.contains("{")) {
rootTagNamespace = rootTagName.replaceAll("\\{(.*)\\}.*", "$1");
rootTagName = rootTagName.replaceAll("\\{.*\\}(.*)", "$1");

View File

@@ -16,17 +16,18 @@
package org.springframework.batch.item.xml;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* This class provides a little bit of indirection to avoid ugly conditional object creation. It is unfortunately
@@ -69,10 +70,10 @@ public abstract class StaxUtils {
Class<?> clzz = ClassUtils.forName(staxSourceClassNameOnSpringOxm30, defaultClassLoader);
// javax.xml.transform.Source
staxUtilsSourceMethodOnSpring30 = ClassUtils.getStaticMethod(clzz, "createStaxSource", new Class[]{ XMLEventReader.class});
staxUtilsSourceMethodOnSpring30 = ClassUtils.getStaticMethod(clzz, "createStaxSource", XMLEventReader.class);
// javax.xml.transform.Result
staxUtilsResultMethodOnSpring30 = ClassUtils.getStaticMethod(clzz, "createStaxResult", new Class[]{XMLEventWriter.class});
staxUtilsResultMethodOnSpring30 = ClassUtils.getStaticMethod(clzz, "createStaxResult", XMLEventWriter.class);
} else if (hasSpringWs15StaxSupport) {
// javax.xml.transform.Source
@@ -126,7 +127,7 @@ public abstract class StaxUtils {
}
public static XMLEventWriter getXmlEventWriter(Result r) throws Exception {
Method m = r.getClass().getDeclaredMethod("getXMLEventWriter", new Class[]{});
Method m = r.getClass().getDeclaredMethod("getXMLEventWriter");
boolean accessible = m.isAccessible();
m.setAccessible(true);
Object result = m.invoke(r);
@@ -135,7 +136,7 @@ public abstract class StaxUtils {
}
public static XMLEventReader getXmlEventReader(Source s) throws Exception {
Method m = s.getClass().getDeclaredMethod("getXMLEventReader", new Class[]{});
Method m = s.getClass().getDeclaredMethod("getXMLEventReader");
boolean accessible = m.isAccessible();
m.setAccessible(true);
Object result = m.invoke(s);

View File

@@ -49,7 +49,7 @@ public abstract class CheckpointSupport extends ItemStreamSupport{
* @param checkpointKey key to store the checkpoint object with in the {@link ExecutionContext}
*/
public CheckpointSupport(String checkpointKey) {
Assert.hasText(checkpointKey);
Assert.hasText(checkpointKey, "checkpointKey is required");
this.checkpointKey = checkpointKey;
}
@@ -72,7 +72,7 @@ public abstract class CheckpointSupport extends ItemStreamSupport{
* Used to open a batch artifact with previously saved checkpoint information.
*
* @param checkpoint previously saved checkpoint object
* @throws Exception
* @throws Exception thrown by the implementation
*/
protected abstract void doOpen(Serializable checkpoint) throws Exception;
@@ -94,7 +94,7 @@ public abstract class CheckpointSupport extends ItemStreamSupport{
* batch artifact.
*
* @return the current state of the batch artifact
* @throws Exception
* @throws Exception thrown by the implementation
*/
protected abstract Serializable doCheckpoint() throws Exception;
@@ -113,7 +113,7 @@ public abstract class CheckpointSupport extends ItemStreamSupport{
/**
* Used to close the underlying batch artifact
*
* @throws Exception
* @throws Exception thrown by the underlying implementation
*/
protected abstract void doClose() throws Exception;

View File

@@ -54,6 +54,8 @@ public interface RepeatContext extends AttributeAccessor {
/**
* Public accessor for the complete flag.
*
* @return indicator if the repeat is complete
*/
boolean isCompleteOnly();
@@ -66,6 +68,8 @@ public interface RepeatContext extends AttributeAccessor {
/**
* Public accessor for the termination flag. If this flag is set then the
* complete flag will also be.
*
* @return indicates if the repeat should terminate
*/
boolean isTerminateOnly();

View File

@@ -43,12 +43,7 @@ public class RethrowOnThresholdExceptionHandler implements ExceptionHandler {
protected final Log logger = LogFactory.getLog(RethrowOnThresholdExceptionHandler.class);
private Classifier<? super Throwable, IntegerHolder> exceptionClassifier = new Classifier<Throwable, IntegerHolder>() {
@Override
public RethrowOnThresholdExceptionHandler.IntegerHolder classify(Throwable classifiable) {
return ZERO;
}
};
private Classifier<? super Throwable, IntegerHolder> exceptionClassifier = (Classifier<Throwable, IntegerHolder>) classifiable -> ZERO;
private boolean useParent = false;
@@ -82,7 +77,7 @@ public class RethrowOnThresholdExceptionHandler implements ExceptionHandler {
for (Entry<Class<? extends Throwable>, Integer> entry : thresholds.entrySet()) {
typeMap.put(entry.getKey(), new IntegerHolder(entry.getValue()));
}
exceptionClassifier = new SubclassClassifier<Throwable, IntegerHolder>(typeMap, ZERO);
exceptionClassifier = new SubclassClassifier<>(typeMap, ZERO);
}
/**
@@ -123,7 +118,7 @@ public class RethrowOnThresholdExceptionHandler implements ExceptionHandler {
private final int value;
/**
* @param value
* @param value value within holder
*/
public IntegerHolder(int value) {
this.value = value;

View File

@@ -16,8 +16,14 @@
package org.springframework.batch.repeat.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.repeat.CompletionPolicy;
import org.springframework.batch.repeat.RepeatCallback;
import org.springframework.batch.repeat.RepeatContext;
@@ -30,11 +36,6 @@ import org.springframework.batch.repeat.exception.ExceptionHandler;
import org.springframework.batch.repeat.policy.DefaultResultCompletionPolicy;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Simple implementation and base class for batch templates implementing
* {@link RepeatOperations}. Provides a framework including interceptors and
@@ -76,7 +77,7 @@ public class RepeatTemplate implements RepeatOperations {
* Set the listeners for this template, registering them for callbacks at
* appropriate times in the iteration.
*
* @param listeners
* @param listeners listeners to be used
*/
public void setListeners(RepeatListener[] listeners) {
this.listeners = Arrays.asList(listeners).toArray(new RepeatListener[listeners.length]);
@@ -85,10 +86,10 @@ public class RepeatTemplate implements RepeatOperations {
/**
* Register an additional listener.
*
* @param listener
* @param listener a single listener to be added to the list
*/
public void registerListener(RepeatListener listener) {
List<RepeatListener> list = new ArrayList<RepeatListener>(Arrays.asList(listeners));
List<RepeatListener> list = new ArrayList<>(Arrays.asList(listeners));
list.add(listener);
listeners = list.toArray(new RepeatListener[list.size()]);
}
@@ -121,7 +122,7 @@ public class RepeatTemplate implements RepeatOperations {
* @throws IllegalArgumentException if the argument is null
*/
public void setCompletionPolicy(CompletionPolicy terminationPolicy) {
Assert.notNull(terminationPolicy);
Assert.notNull(terminationPolicy, "CompletionPolicy is required");
this.completionPolicy = terminationPolicy;
}
@@ -172,8 +173,7 @@ public class RepeatTemplate implements RepeatOperations {
// processing takes place.
boolean running = !isMarkedComplete(context);
for (int i = 0; i < listeners.length; i++) {
RepeatListener interceptor = listeners[i];
for (RepeatListener interceptor : listeners) {
interceptor.open(context);
running = running && !isMarkedComplete(context);
if (!running)
@@ -188,7 +188,7 @@ public class RepeatTemplate implements RepeatOperations {
Collection<Throwable> throwables = state.getThrowables();
// Keep a separate list of exceptions we handled that need to be
// rethrown
Collection<Throwable> deferred = new ArrayList<Throwable>();
Collection<Throwable> deferred = new ArrayList<>();
try {
@@ -361,6 +361,7 @@ public class RepeatTemplate implements RepeatOperations {
* @param callback the callback to execute.
* @param state maintained by the implementation.
* @return a finished result.
* @throws Throwable any Throwable emitted during the iteration
*
* @see #isComplete(RepeatContext)
* @see #createInternalState(RepeatContext)

View File

@@ -83,7 +83,7 @@ public class TaskExecutorRepeatTemplate extends RepeatTemplate {
* @throws IllegalArgumentException if the argument is null
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
Assert.notNull(taskExecutor);
Assert.notNull(taskExecutor, "A TaskExecutor is required");
this.taskExecutor = taskExecutor;
}
@@ -99,7 +99,7 @@ public class TaskExecutorRepeatTemplate extends RepeatTemplate {
protected RepeatStatus getNextResult(RepeatContext context, RepeatCallback callback, RepeatInternalState state)
throws Throwable {
ExecutingRunnable runnable = null;
ExecutingRunnable runnable;
ResultQueue<ResultHolder> queue = ((ResultQueueInternalState) state).getResultQueue();

View File

@@ -57,7 +57,7 @@ public class MethodInvokerUtils {
Assert.isTrue(!paramsRequired, errorMsg);
// if no method was found for the given parameters, and the
// parameters aren't required, then try with no params
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, new Class[] {});
method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName);
Assert.notNull(method, errorMsg);
}
return new SimpleMethodInvoker(object, method);
@@ -66,8 +66,8 @@ public class MethodInvokerUtils {
/**
* Create a String representation of the array of parameter types.
*
* @param paramTypes
* @return String
* @param paramTypes types of the parameters to be used
* @return String a String representation of those types
*/
public static String getParamTypesString(Class<?>... paramTypes) {
StringBuilder paramTypesList = new StringBuilder("(");
@@ -116,22 +116,19 @@ public class MethodInvokerUtils {
final Class<?> targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource()
.getTargetClass() : target.getClass();
if (mi != null) {
ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatible with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
String errorMsg = "The method [" + method.getName() + "] on target class ["
+ targetClass.getSimpleName() + "] is incompatible with the signature ["
+ getParamTypesString(expectedParamTypes) + "] expected for the annotation ["
+ annotationType.getSimpleName() + "].";
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
Assert.isTrue(paramTypes.length == expectedParamTypes.length, errorMsg);
for (int i = 0; i < paramTypes.length; i++) {
Assert.isTrue(expectedParamTypes[i].isAssignableFrom(paramTypes[i]), errorMsg);
}
}
}
@@ -162,17 +159,14 @@ public class MethodInvokerUtils {
// Proxy with no target cannot have annotations
return null;
}
final AtomicReference<Method> annotatedMethod = new AtomicReference<Method>();
ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class ["
+ targetClass.getSimpleName() + "] with the annotation type ["
+ annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
final AtomicReference<Method> annotatedMethod = new AtomicReference<>();
ReflectionUtils.doWithMethods(targetClass, method -> {
Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
if (annotation != null) {
Assert.isNull(annotatedMethod.get(), "found more than one method on target class ["
+ targetClass.getSimpleName() + "] with the annotation type ["
+ annotationType.getSimpleName() + "].");
annotatedMethod.set(method);
}
});
Method method = annotatedMethod.get();
@@ -192,20 +186,17 @@ public class MethodInvokerUtils {
* @return a MethodInvoker that calls a method on the delegate
*/
public static <C, T> MethodInvoker getMethodInvokerForSingleArgument(Object target) {
final AtomicReference<Method> methodHolder = new AtomicReference<Method>();
ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
final AtomicReference<Method> methodHolder = new AtomicReference<>();
ReflectionUtils.doWithMethods(target.getClass(), method -> {
if (method.getParameterTypes() == null || method.getParameterTypes().length != 1) {
return;
}
if (method.getReturnType().equals(Void.TYPE) || ReflectionUtils.isEqualsMethod(method)) {
return;
}
Assert.state(methodHolder.get() == null,
"More than one non-void public method detected with single argument.");
methodHolder.set(method);
});
Method method = methodHolder.get();
return new SimpleMethodInvoker(target, method);

View File

@@ -15,13 +15,13 @@
*/
package org.springframework.batch.support;
import org.springframework.core.annotation.AnnotationUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import org.springframework.core.annotation.AnnotationUtils;
/**
* Provides reflection based utilities for Spring Batch that are not available
* via Spring Core
@@ -41,10 +41,11 @@ public class ReflectionUtils {
* @param annotationType The type of annotation to look for
* @return a set of {@link java.lang.reflect.Method} instances if any are found, an empty set if not.
*/
@SuppressWarnings("rawtypes")
public static final Set<Method> findMethod(Class clazz, Class<? extends Annotation> annotationType) {
Method [] declaredMethods = org.springframework.util.ReflectionUtils.getAllDeclaredMethods(clazz);
Set<Method> results = new HashSet<Method>();
Set<Method> results = new HashSet<>();
for (Method curMethod : declaredMethods) {
Annotation annotation = AnnotationUtils.findAnnotation(curMethod, annotationType);

View File

@@ -65,7 +65,7 @@ public class SimpleMethodInvoker implements MethodInvoker {
this.method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
if (this.method == null) {
// try with no params
this.method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, new Class[] {});
this.method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName);
}
if (this.method == null) {
throw new IllegalArgumentException("No methods found for name: [" + methodName + "] in class: ["