diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java index 5ffe0c36d..402b0b920 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java @@ -17,7 +17,6 @@ package org.springframework.batch.core.job.flow.support.state; import java.util.ArrayList; import java.util.Collection; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -89,12 +88,7 @@ public class SplitState extends AbstractState implements FlowHolder { for (final Flow flow : flows) { - final FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public FlowExecution call() throws Exception { - return flow.start(executor); - } - }); + final FutureTask task = new FutureTask<>(() -> flow.start(executor)); tasks.add(task); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandler.java b/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandler.java index 53d43835f..25f55aa78 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandler.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandler.java @@ -18,7 +18,6 @@ package org.springframework.batch.core.partition.support; import java.util.HashSet; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -129,12 +128,9 @@ public class TaskExecutorPartitionHandler extends AbstractPartitionHandler imple * @return the task executing the given step */ protected FutureTask createTask(final Step step, final StepExecution stepExecution) { - return new FutureTask<>(new Callable<>() { - @Override - public StepExecution call() throws Exception { - step.execute(stepExecution); - return stepExecution; - } + return new FutureTask<>(() -> { + step.execute(stepExecution); + return stepExecution; }); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDao.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDao.java index 86972ec26..ab76d53e0 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDao.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcExecutionContextDao.java @@ -37,7 +37,6 @@ import org.springframework.batch.core.repository.ExecutionContextSerializer; import org.springframework.batch.item.ExecutionContext; import org.springframework.core.serializer.Serializer; import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.jdbc.support.lob.LobHandler; @@ -289,18 +288,15 @@ public class JdbcExecutionContextDao extends AbstractJdbcBatchMetadataDao implem longContext = null; } - getJdbcTemplate().update(getQuery(sql), new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, shortContext); - if (longContext != null) { - lobHandler.getLobCreator().setClobAsString(ps, 2, longContext); - } - else { - ps.setNull(2, getClobTypeToUse()); - } - ps.setLong(3, executionId); + getJdbcTemplate().update(getQuery(sql), ps -> { + ps.setString(1, shortContext); + if (longContext != null) { + lobHandler.getLobCreator().setClobAsString(ps, 2, longContext); } + else { + ps.setNull(2, getClobTypeToUse()); + } + ps.setLong(3, executionId); }); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDao.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDao.java index cfae69280..c0b5cf4a3 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDao.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobExecutionDao.java @@ -373,12 +373,9 @@ public class JdbcJobExecutionDao extends AbstractJdbcBatchMetadataDao implements public Set findRunningJobExecutions(String jobName) { final Set result = new HashSet<>(); - RowCallbackHandler handler = new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - JobExecutionRowMapper mapper = new JobExecutionRowMapper(); - result.add(mapper.mapRow(rs, 0)); - } + RowCallbackHandler handler = rs -> { + JobExecutionRowMapper mapper = new JobExecutionRowMapper(); + result.add(mapper.mapRow(rs, 0)); }; getJdbcTemplate().query(getQuery(GET_RUNNING_EXECUTIONS), handler, jobName); @@ -455,27 +452,24 @@ public class JdbcJobExecutionDao extends AbstractJdbcBatchMetadataDao implements */ protected JobParameters getJobParameters(Long executionId) { final Map> map = new HashMap<>(); - RowCallbackHandler handler = new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - String parameterName = rs.getString("PARAMETER_NAME"); + RowCallbackHandler handler = rs -> { + String parameterName = rs.getString("PARAMETER_NAME"); - Class parameterType = null; - try { - parameterType = Class.forName(rs.getString("PARAMETER_TYPE")); - } - catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - String stringValue = rs.getString("PARAMETER_VALUE"); - Object typedValue = conversionService.convert(stringValue, parameterType); - - boolean identifying = rs.getString("IDENTIFYING").equalsIgnoreCase("Y"); - - JobParameter jobParameter = new JobParameter(typedValue, parameterType, identifying); - - map.put(parameterName, jobParameter); + Class parameterType = null; + try { + parameterType = Class.forName(rs.getString("PARAMETER_TYPE")); } + catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + String stringValue = rs.getString("PARAMETER_VALUE"); + Object typedValue = conversionService.convert(stringValue, parameterType); + + boolean identifying = rs.getString("IDENTIFYING").equalsIgnoreCase("Y"); + + JobParameter jobParameter = new JobParameter(typedValue, parameterType, identifying); + + map.put(parameterName, jobParameter); }; getJdbcTemplate().query(getQuery(FIND_PARAMS_FROM_ID), handler, executionId); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java index 7b924b2d8..30b087867 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java @@ -221,12 +221,7 @@ public class JdbcJobInstanceDao extends AbstractJdbcBatchMetadataDao implements */ @Override public List getJobNames() { - return getJdbcTemplate().query(getQuery(FIND_JOB_NAMES), new RowMapper<>() { - @Override - public String mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getString(1); - } - }); + return getJdbcTemplate().query(getQuery(FIND_JOB_NAMES), (rs, rowNum) -> rs.getString(1)); } /* diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/AbstractJobRepositoryFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/AbstractJobRepositoryFactoryBean.java index 88ab504f3..80415834a 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/AbstractJobRepositoryFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/support/AbstractJobRepositoryFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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,7 +19,6 @@ package org.springframework.batch.core.repository.support; import java.util.Properties; import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.NameMatchMethodPointcut; @@ -197,15 +196,12 @@ public abstract class AbstractJobRepositoryFactoryBean implements FactoryBean { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Existing transaction detected in JobRepository. " + + "Please fix this and try again (e.g. remove @Transactional annotations from client)."); } + return invocation.proceed(); }); NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut(); pointcut.addMethodName("create*"); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java index 1b53891ff..7cf74c855 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java @@ -28,7 +28,6 @@ import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.core.Ordered; import org.springframework.util.Assert; -import org.springframework.util.StringValueResolver; /** * ScopeSupport. @@ -174,12 +173,7 @@ public abstract class BatchScopeSupport implements Scope, BeanFactoryPostProcess private final boolean scoped; public Scopifier(BeanDefinitionRegistry registry, String scope, boolean proxyTargetClass, boolean scoped) { - super(new StringValueResolver() { - @Override - public String resolveStringValue(String value) { - return value; - } - }); + super(value -> value); this.registry = registry; this.proxyTargetClass = proxyTargetClass; this.scope = scope; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java index 12add7895..b051a4288 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java @@ -215,87 +215,77 @@ public class FaultTolerantChunkProcessor extends SimpleChunkProcessor retryCallback = new RetryCallback<>() { - - @Override - public O doWithRetry(RetryContext context) throws Exception { - Timer.Sample sample = BatchMetrics.createTimerSample(meterRegistry); - String status = BatchMetrics.STATUS_SUCCESS; - O output = null; - try { - O cached = (cacheIterator != null && cacheIterator.hasNext()) ? cacheIterator.next() : null; - if (cached != null && !processorTransactional) { - output = cached; - } - else { - output = doProcess(item); - if (output == null) { - data.incrementFilterCount(); - } - else if (!processorTransactional && !data.scanning()) { - cache.add(output); - } - } - } - catch (Exception e) { - status = BatchMetrics.STATUS_FAILURE; - if (rollbackClassifier.classify(e)) { - // Default is to rollback unless the classifier - // allows us to continue - throw e; - } - else if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) { - // If we are not re-throwing then we should check if - // this is skippable - contribution.incrementProcessSkipCount(); - logger.debug("Skipping after failed process with no rollback", e); - // If not re-throwing then the listener will not be - // called in next chunk. - callProcessSkipListener(item, e); - } - else { - // If it's not skippable that's an error in - // configuration - it doesn't make sense to not roll - // back if we are also not allowed to skip - throw new NonSkippableProcessException( - "Non-skippable exception in processor. Make sure any exceptions that do not cause a rollback are skippable.", - e); - } - } - finally { - stopTimer(sample, contribution.getStepExecution(), "item.process", status, "Item processing"); - } - if (output == null) { - // No need to re-process filtered items - iterator.remove(); - } - return output; - } - - }; - - RecoveryCallback recoveryCallback = new RecoveryCallback<>() { - - @Override - public O recover(RetryContext context) throws Exception { - Throwable e = context.getLastThrowable(); - if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) { - iterator.remove(e); - contribution.incrementProcessSkipCount(); - logger.debug("Skipping after failed process", e); - return null; + RetryCallback retryCallback = context -> { + Timer.Sample sample = BatchMetrics.createTimerSample(meterRegistry); + String status = BatchMetrics.STATUS_SUCCESS; + O output = null; + try { + O cached = (cacheIterator != null && cacheIterator.hasNext()) ? cacheIterator.next() : null; + if (cached != null && !processorTransactional) { + output = cached; } else { - if (rollbackClassifier.classify(e)) { - // Default is to rollback unless the classifier - // allows us to continue - throw new RetryException("Non-skippable exception in recoverer while processing", e); + output = doProcess(item); + if (output == null) { + data.incrementFilterCount(); + } + else if (!processorTransactional && !data.scanning()) { + cache.add(output); } - iterator.remove(e); - return null; } } + catch (Exception e) { + status = BatchMetrics.STATUS_FAILURE; + if (rollbackClassifier.classify(e)) { + // Default is to rollback unless the classifier + // allows us to continue + throw e; + } + else if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) { + // If we are not re-throwing then we should check if + // this is skippable + contribution.incrementProcessSkipCount(); + logger.debug("Skipping after failed process with no rollback", e); + // If not re-throwing then the listener will not be + // called in next chunk. + callProcessSkipListener(item, e); + } + else { + // If it's not skippable that's an error in + // configuration - it doesn't make sense to not roll + // back if we are also not allowed to skip + throw new NonSkippableProcessException( + "Non-skippable exception in processor. Make sure any exceptions that do not cause a rollback are skippable.", + e); + } + } + finally { + stopTimer(sample, contribution.getStepExecution(), "item.process", status, "Item processing"); + } + if (output == null) { + // No need to re-process filtered items + iterator.remove(); + } + return output; + }; + RecoveryCallback recoveryCallback = context -> { + Throwable e = context.getLastThrowable(); + if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) { + iterator.remove(e); + contribution.incrementProcessSkipCount(); + logger.debug("Skipping after failed process", e); + return null; + } + else { + if (rollbackClassifier.classify(e)) { + // Default is to rollback unless the classifier + // allows us to continue + throw new RetryException("Non-skippable exception in recoverer while processing", e); + } + iterator.remove(e); + return null; + } }; O output = batchRetryTemplate.execute(retryCallback, recoveryCallback, @@ -328,76 +318,68 @@ public class FaultTolerantChunkProcessor extends SimpleChunkProcessor data = (UserData) inputs.getUserData(); final AtomicReference contextHolder = new AtomicReference<>(); - RetryCallback retryCallback = new RetryCallback<>() { - @Override - public Object doWithRetry(RetryContext context) throws Exception { - contextHolder.set(context); + RetryCallback retryCallback = context -> { + contextHolder.set(context); - if (!data.scanning()) { - chunkMonitor.setChunkSize(inputs.size()); - Timer.Sample sample = BatchMetrics.createTimerSample(meterRegistry); - String status = BatchMetrics.STATUS_SUCCESS; - try { - doWrite(outputs); - } - catch (Exception e) { - status = BatchMetrics.STATUS_FAILURE; - if (rollbackClassifier.classify(e)) { - throw e; - } - /* - * If the exception is marked as no-rollback, we need to override - * that, otherwise there's no way to write the rest of the chunk - * or to honour the skip listener contract. - */ - throw new ForceRollbackForWriteSkipException( - "Force rollback on skippable exception so that skipped item can be located.", e); - } - finally { - stopTimer(sample, contribution.getStepExecution(), "chunk.write", status, "Chunk writing"); - } - contribution.incrementWriteCount(outputs.size()); + if (!data.scanning()) { + chunkMonitor.setChunkSize(inputs.size()); + Timer.Sample sample = BatchMetrics.createTimerSample(meterRegistry); + String status = BatchMetrics.STATUS_SUCCESS; + try { + doWrite(outputs); } - else { - scan(contribution, inputs, outputs, chunkMonitor, false); + catch (Exception e) { + status = BatchMetrics.STATUS_FAILURE; + if (rollbackClassifier.classify(e)) { + throw e; + } + /* + * If the exception is marked as no-rollback, we need to override + * that, otherwise there's no way to write the rest of the chunk or to + * honour the skip listener contract. + */ + throw new ForceRollbackForWriteSkipException( + "Force rollback on skippable exception so that skipped item can be located.", e); } - return null; - + finally { + stopTimer(sample, contribution.getStepExecution(), "chunk.write", status, "Chunk writing"); + } + contribution.incrementWriteCount(outputs.size()); } + else { + scan(contribution, inputs, outputs, chunkMonitor, false); + } + return null; + }; if (!buffering) { - RecoveryCallback batchRecoveryCallback = new RecoveryCallback<>() { + RecoveryCallback batchRecoveryCallback = context -> { - @Override - public Object recover(RetryContext context) throws Exception { + Throwable e = context.getLastThrowable(); + if (outputs.size() > 1 && !rollbackClassifier.classify(e)) { + throw new RetryException("Invalid retry state during write caused by " + + "exception that does not classify for rollback: ", e); + } - Throwable e = context.getLastThrowable(); - if (outputs.size() > 1 && !rollbackClassifier.classify(e)) { - throw new RetryException("Invalid retry state during write caused by " - + "exception that does not classify for rollback: ", e); + Chunk.ChunkIterator inputIterator = inputs.iterator(); + for (Chunk.ChunkIterator outputIterator = outputs.iterator(); outputIterator.hasNext();) { + + inputIterator.next(); + outputIterator.next(); + + checkSkipPolicy(inputIterator, outputIterator, e, contribution, true); + if (!rollbackClassifier.classify(e)) { + throw new RetryException( + "Invalid retry state during recovery caused by exception that does not classify for rollback: ", + e); } - Chunk.ChunkIterator inputIterator = inputs.iterator(); - for (Chunk.ChunkIterator outputIterator = outputs.iterator(); outputIterator.hasNext();) { - - inputIterator.next(); - outputIterator.next(); - - checkSkipPolicy(inputIterator, outputIterator, e, contribution, true); - if (!rollbackClassifier.classify(e)) { - throw new RetryException( - "Invalid retry state during recovery caused by exception that does not classify for rollback: ", - e); - } - - } - - return null; - } + return null; + }; batchRetryTemplate.execute(retryCallback, batchRecoveryCallback, @@ -406,26 +388,21 @@ public class FaultTolerantChunkProcessor extends SimpleChunkProcessor recoveryCallback = new RecoveryCallback<>() { - - @Override - public Object recover(RetryContext context) throws Exception { - /* - * If the last exception was not skippable we don't need to do any - * scanning. We can just bomb out with a retry exhausted. - */ - if (!shouldSkip(itemWriteSkipPolicy, context.getLastThrowable(), -1)) { - throw new ExhaustedRetryException( - "Retry exhausted after last attempt in recovery path, but exception is not skippable.", - context.getLastThrowable()); - } - - inputs.setBusy(true); - data.scanning(true); - scan(contribution, inputs, outputs, chunkMonitor, true); - return null; + RecoveryCallback recoveryCallback = context -> { + /* + * If the last exception was not skippable we don't need to do any + * scanning. We can just bomb out with a retry exhausted. + */ + if (!shouldSkip(itemWriteSkipPolicy, context.getLastThrowable(), -1)) { + throw new ExhaustedRetryException( + "Retry exhausted after last attempt in recovery path, but exception is not skippable.", + context.getLastThrowable()); } + inputs.setBusy(true); + data.scanning(true); + scan(contribution, inputs, outputs, chunkMonitor, true); + return null; }; if (logger.isDebugEnabled()) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java index c1f1343b1..8125b32b5 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -31,8 +31,6 @@ import org.springframework.batch.core.listener.MulticasterBatchListener; import org.springframework.batch.core.observability.BatchMetrics; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; -import org.springframework.batch.repeat.RepeatCallback; -import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.RepeatOperations; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.lang.Nullable; @@ -126,34 +124,29 @@ public class SimpleChunkProvider implements ChunkProvider { public Chunk provide(final StepContribution contribution) throws Exception { final Chunk inputs = new Chunk<>(); - repeatOperations.iterate(new RepeatCallback() { - - @Override - public RepeatStatus doInIteration(final RepeatContext context) throws Exception { - I item = null; - Timer.Sample sample = Timer.start(Metrics.globalRegistry); - String status = BatchMetrics.STATUS_SUCCESS; - try { - item = read(contribution, inputs); - } - catch (SkipOverflowException e) { - // read() tells us about an excess of skips by throwing an - // exception - status = BatchMetrics.STATUS_FAILURE; - return RepeatStatus.FINISHED; - } - finally { - stopTimer(sample, contribution.getStepExecution(), status); - } - if (item == null) { - inputs.setEnd(); - return RepeatStatus.FINISHED; - } - inputs.add(item); - contribution.incrementReadCount(); - return RepeatStatus.CONTINUABLE; + repeatOperations.iterate(context -> { + I item = null; + Timer.Sample sample = Timer.start(Metrics.globalRegistry); + String status = BatchMetrics.STATUS_SUCCESS; + try { + item = read(contribution, inputs); } - + catch (SkipOverflowException e) { + // read() tells us about an excess of skips by throwing an + // exception + status = BatchMetrics.STATUS_FAILURE; + return RepeatStatus.FINISHED; + } + finally { + stopTimer(sample, contribution.getStepExecution(), status); + } + if (item == null) { + inputs.setEnd(); + return RepeatStatus.FINISHED; + } + inputs.add(item); + contribution.incrementReadCount(); + return RepeatStatus.CONTINUABLE; }); return inputs; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java index 8d97b4abf..066db5b3c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java @@ -20,7 +20,6 @@ import javax.sql.DataSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; import org.mockito.Mockito; import org.springframework.aop.Advisor; @@ -56,23 +55,15 @@ class BatchRegistrarTests { @Test @DisplayName("When no datasource is provided, then an BeanCreationException should be thrown") void testMissingDataSource() { - Assertions.assertThrows(BeanCreationException.class, new Executable() { - @Override - public void execute() throws Throwable { - new AnnotationConfigApplicationContext(JobConfigurationWithoutDataSource.class); - } - }); + Assertions.assertThrows(BeanCreationException.class, + () -> new AnnotationConfigApplicationContext(JobConfigurationWithoutDataSource.class)); } @Test @DisplayName("When no transaction manager is provided, then an BeanCreationException should be thrown") void testMissingTransactionManager() { - Assertions.assertThrows(BeanCreationException.class, new Executable() { - @Override - public void execute() throws Throwable { - new AnnotationConfigApplicationContext(JobConfigurationWithoutTransactionManager.class); - } - }); + Assertions.assertThrows(BeanCreationException.class, + () -> new AnnotationConfigApplicationContext(JobConfigurationWithoutTransactionManager.class)); } @Test diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java index cefcd11d1..3f7966cc6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java @@ -21,7 +21,6 @@ import javax.sql.DataSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.function.Executable; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.Job; @@ -68,22 +67,14 @@ class DefaultBatchConfigurationTests { @Test void testConfigurationWithoutDataSource() { - Assertions.assertThrows(BeanCreationException.class, new Executable() { - @Override - public void execute() throws Throwable { - new AnnotationConfigApplicationContext(MyJobConfigurationWithoutDataSource.class); - } - }); + Assertions.assertThrows(BeanCreationException.class, + () -> new AnnotationConfigApplicationContext(MyJobConfigurationWithoutDataSource.class)); } @Test void testConfigurationWithoutTransactionManager() { - Assertions.assertThrows(BeanCreationException.class, new Executable() { - @Override - public void execute() throws Throwable { - new AnnotationConfigApplicationContext(MyJobConfigurationWithoutTransactionManager.class); - } - }); + Assertions.assertThrows(BeanCreationException.class, + () -> new AnnotationConfigApplicationContext(MyJobConfigurationWithoutTransactionManager.class)); } @Test diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java index fbf838acf..202febb59 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/SplitInterruptedJobParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -27,6 +27,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * @since 2.0 */ @SpringJUnitConfig @@ -36,12 +37,7 @@ class SplitInterruptedJobParserTests extends AbstractJobParserTests { void testSplitInterrupted() throws Exception { final JobExecution jobExecution = createJobExecution(); - new Thread(new Runnable() { - @Override - public void run() { - job.execute(jobExecution); - } - }).start(); + new Thread(() -> job.execute(jobExecution)).start(); Thread.sleep(100L); jobExecution.setStatus(BatchStatus.STOPPING); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java index 500ec8a33..e08bbacfe 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java @@ -122,19 +122,9 @@ class SimpleJobTests { job.setObservationRegistry(observationRegistry); step1 = new StubStep("TestStep1", jobRepository); - step1.setCallback(new Runnable() { - @Override - public void run() { - list.add("default"); - } - }); + step1.setCallback(() -> list.add("default")); step2 = new StubStep("TestStep2", jobRepository); - step2.setCallback(new Runnable() { - @Override - public void run() { - list.add("default"); - } - }); + step2.setCallback(() -> list.add("default")); List steps = new ArrayList<>(); steps.add(step1); @@ -492,11 +482,8 @@ class SimpleJobTests { void testGetMultipleJobParameters() throws Exception { StubStep failStep = new StubStep("failStep", jobRepository); - failStep.setCallback(new Runnable() { - @Override - public void run() { - throw new RuntimeException("An error occurred."); - } + failStep.setCallback(() -> { + throw new RuntimeException("An error occurred."); }); job.setName("parametersTestJob"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java index 4e1284408..3696ed18d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/flow/FlowJobTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -41,7 +41,6 @@ import org.springframework.batch.core.step.StepSupport; import org.springframework.jdbc.support.JdbcTransactionManager; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import org.springframework.lang.Nullable; import java.util.ArrayList; import java.util.Arrays; @@ -470,12 +469,9 @@ public class FlowJobTests { void testDecisionFlow() throws Throwable { SimpleFlow flow = new SimpleFlow("job"); - JobExecutionDecider decider = new JobExecutionDecider() { - @Override - public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecution stepExecution) { - assertNotNull(stepExecution); - return new FlowExecutionStatus("SWITCH"); - } + JobExecutionDecider decider = (jobExecution, stepExecution) -> { + assertNotNull(stepExecution); + return new FlowExecutionStatus("SWITCH"); }; List transitions = new ArrayList<>(); @@ -512,12 +508,9 @@ public class FlowJobTests { void testDecisionFlowWithExceptionInDecider() throws Throwable { SimpleFlow flow = new SimpleFlow("job"); - JobExecutionDecider decider = new JobExecutionDecider() { - @Override - public FlowExecutionStatus decide(JobExecution jobExecution, @Nullable StepExecution stepExecution) { - assertNotNull(stepExecution); - throw new RuntimeException("Foo"); - } + JobExecutionDecider decider = (jobExecution, stepExecution) -> { + assertNotNull(stepExecution); + throw new RuntimeException("Foo"); }; List transitions = new ArrayList<>(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java index 6f9daf23d..85bd28d9f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/TaskExecutorJobLauncherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -39,7 +39,6 @@ import org.springframework.batch.core.launch.support.TaskExecutorJobLauncher; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.JobRestartException; -import org.springframework.core.task.TaskExecutor; import org.springframework.core.task.TaskRejectedException; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -51,6 +50,7 @@ import static org.mockito.Mockito.when; /** * @author Lucas Ward * @author Will Schipp + * @author Mahmoud Ben Hassine * */ class TaskExecutorJobLauncherTests { @@ -146,12 +146,9 @@ class TaskExecutorJobLauncherTests { @Test void testTaskExecutor() throws Exception { final List list = new ArrayList<>(); - jobLauncher.setTaskExecutor(new TaskExecutor() { - @Override - public void execute(Runnable task) { - list.add("execute"); - task.run(); - } + jobLauncher.setTaskExecutor(task -> { + list.add("execute"); + task.run(); }); testRun(); assertEquals(1, list.size()); @@ -161,12 +158,9 @@ class TaskExecutorJobLauncherTests { void testTaskExecutorRejects() throws Exception { final List list = new ArrayList<>(); - jobLauncher.setTaskExecutor(new TaskExecutor() { - @Override - public void execute(Runnable task) { - list.add("execute"); - throw new TaskRejectedException("Planned failure"); - } + jobLauncher.setTaskExecutor(task -> { + list.add("execute"); + throw new TaskRejectedException("Planned failure"); }); JobExecution jobExecution = new JobExecution((JobInstance) null, (JobParameters) null); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java index c4db98895..8297bd867 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/OrderedCompositeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -27,6 +27,7 @@ import org.springframework.core.annotation.Order; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class OrderedCompositeTests { @@ -61,12 +62,7 @@ class OrderedCompositeTests { @Test void testAddOrdered() { list.setItems(Arrays.asList((Object) "1")); - list.add(new Ordered() { - @Override - public int getOrder() { - return 0; - } - }); + list.add((Ordered) () -> 0); Iterator iterator = list.iterator(); iterator.next(); assertEquals("1", iterator.next()); @@ -75,18 +71,8 @@ class OrderedCompositeTests { @Test void testAddMultipleOrdered() { list.setItems(Arrays.asList((Object) "1")); - list.add(new Ordered() { - @Override - public int getOrder() { - return 1; - } - }); - list.add(new Ordered() { - @Override - public int getOrder() { - return 0; - } - }); + list.add((Ordered) () -> 1); + list.add((Ordered) () -> 0); Iterator iterator = list.iterator(); assertEquals(0, ((Ordered) iterator.next()).getOrder()); assertEquals(1, ((Ordered) iterator.next()).getOrder()); @@ -96,18 +82,8 @@ class OrderedCompositeTests { @Test void testAddDuplicateOrdered() { list.setItems(Arrays.asList((Object) "1")); - list.add(new Ordered() { - @Override - public int getOrder() { - return 1; - } - }); - list.add(new Ordered() { - @Override - public int getOrder() { - return 1; - } - }); + list.add((Ordered) () -> 1); + list.add((Ordered) () -> 1); Iterator iterator = list.iterator(); assertEquals(1, ((Ordered) iterator.next()).getOrder()); assertEquals(1, ((Ordered) iterator.next()).getOrder()); @@ -116,12 +92,7 @@ class OrderedCompositeTests { @Test void testAddAnnotationOrdered() { - list.add(new Ordered() { - @Override - public int getOrder() { - return 1; - } - }); + list.add((Ordered) () -> 1); OrderedObject item = new OrderedObject(); list.add(item); Iterator iterator = list.iterator(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java index 100be50dd..e7fd7153e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2022 the original author or authors. + * Copyright 2002-2023 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. @@ -21,7 +21,6 @@ import java.util.Map; import javax.sql.DataSource; import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.ProxyFactory; @@ -234,12 +233,7 @@ class StepListenerFactoryBeanTests { void testProxyWithNoTarget() { ProxyFactory factory = new ProxyFactory(); factory.addInterface(DataSource.class); - factory.addAdvice(new MethodInterceptor() { - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - return null; - } - }); + factory.addAdvice((MethodInterceptor) invocation -> null); Object proxy = factory.getProxy(); assertFalse(StepListenerFactoryBean.isListener(proxy)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java index ae720c248..224c2d05b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/PartitionStepTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -29,8 +29,6 @@ import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.partition.PartitionHandler; -import org.springframework.batch.core.partition.StepExecutionSplitter; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.jdbc.support.JdbcTransactionManager; @@ -69,17 +67,13 @@ class PartitionStepTests { void testVanillaStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); - step.setPartitionHandler(new PartitionHandler() { - @Override - public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) - throws Exception { - Set executions = stepSplitter.split(stepExecution, 2); - for (StepExecution execution : executions) { - execution.setStatus(BatchStatus.COMPLETED); - execution.setExitStatus(ExitStatus.COMPLETED); - } - return executions; + step.setPartitionHandler((stepSplitter, stepExecution) -> { + Set executions = stepSplitter.split(stepExecution, 2); + for (StepExecution execution : executions) { + execution.setStatus(BatchStatus.COMPLETED); + execution.setExitStatus(ExitStatus.COMPLETED); } + return executions; }); step.afterPropertiesSet(); JobExecution jobExecution = jobRepository.createJobExecution("vanillaJob", new JobParameters()); @@ -95,17 +89,13 @@ class PartitionStepTests { void testFailedStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); - step.setPartitionHandler(new PartitionHandler() { - @Override - public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) - throws Exception { - Set executions = stepSplitter.split(stepExecution, 2); - for (StepExecution execution : executions) { - execution.setStatus(BatchStatus.FAILED); - execution.setExitStatus(ExitStatus.FAILED); - } - return executions; + step.setPartitionHandler((stepSplitter, stepExecution) -> { + Set executions = stepSplitter.split(stepExecution, 2); + for (StepExecution execution : executions) { + execution.setStatus(BatchStatus.FAILED); + execution.setExitStatus(ExitStatus.FAILED); } + return executions; }); step.afterPropertiesSet(); JobExecution jobExecution = jobRepository.createJobExecution("vanillaJob", new JobParameters()); @@ -122,31 +112,27 @@ class PartitionStepTests { final AtomicBoolean started = new AtomicBoolean(false); step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); - step.setPartitionHandler(new PartitionHandler() { - @Override - public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) - throws Exception { - Set executions = stepSplitter.split(stepExecution, 2); - if (!started.get()) { - started.set(true); - for (StepExecution execution : executions) { - execution.setStatus(BatchStatus.FAILED); - execution.setExitStatus(ExitStatus.FAILED); - execution.getExecutionContext().putString("foo", execution.getStepName()); - } - } - else { - for (StepExecution execution : executions) { - // On restart the execution context should have been restored - assertEquals(execution.getStepName(), execution.getExecutionContext().getString("foo")); - } - } + step.setPartitionHandler((stepSplitter, stepExecution) -> { + Set executions = stepSplitter.split(stepExecution, 2); + if (!started.get()) { + started.set(true); for (StepExecution execution : executions) { - jobRepository.update(execution); - jobRepository.updateExecutionContext(execution); + execution.setStatus(BatchStatus.FAILED); + execution.setExitStatus(ExitStatus.FAILED); + execution.getExecutionContext().putString("foo", execution.getStepName()); } - return executions; } + else { + for (StepExecution execution : executions) { + // On restart the execution context should have been restored + assertEquals(execution.getStepName(), execution.getExecutionContext().getString("foo")); + } + } + for (StepExecution execution : executions) { + jobRepository.update(execution); + jobRepository.updateExecutionContext(execution); + } + return executions; }); step.afterPropertiesSet(); JobExecution jobExecution = jobRepository.createJobExecution("vanillaJob", new JobParameters()); @@ -170,17 +156,13 @@ class PartitionStepTests { void testStoppedStepExecution() throws Exception { step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); - step.setPartitionHandler(new PartitionHandler() { - @Override - public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) - throws Exception { - Set executions = stepSplitter.split(stepExecution, 2); - for (StepExecution execution : executions) { - execution.setStatus(BatchStatus.STOPPED); - execution.setExitStatus(ExitStatus.STOPPED); - } - return executions; + step.setPartitionHandler((stepSplitter, stepExecution) -> { + Set executions = stepSplitter.split(stepExecution, 2); + for (StepExecution execution : executions) { + execution.setStatus(BatchStatus.STOPPED); + execution.setExitStatus(ExitStatus.STOPPED); } + return executions; }); step.afterPropertiesSet(); JobExecution jobExecution = jobRepository.createJobExecution("vanillaJob", new JobParameters()); @@ -203,13 +185,7 @@ class PartitionStepTests { }); step.setStepExecutionSplitter( new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), new SimplePartitioner())); - step.setPartitionHandler(new PartitionHandler() { - @Override - public Collection handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) - throws Exception { - return Arrays.asList(stepExecution); - } - }); + step.setPartitionHandler((stepSplitter, stepExecution) -> Arrays.asList(stepExecution)); step.afterPropertiesSet(); JobExecution jobExecution = jobRepository.createJobExecution("vanillaJob", new JobParameters()); StepExecution stepExecution = jobExecution.createStepExecution("foo"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java index 78e574c49..eb848ce84 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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. @@ -100,12 +100,7 @@ class SimpleStepExecutionSplitterTests { void testSimpleStepExecutionProviderJobRepositoryStepPartitioner() throws Exception { final Map map = Collections.singletonMap("foo", new ExecutionContext()); SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(), - new Partitioner() { - @Override - public Map partition(int gridSize) { - return map; - } - }); + gridSize -> map); assertEquals(1, splitter.split(stepExecution, 2).size()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java index 8f2fb0ae2..909f1a542 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/support/TaskExecutorPartitionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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. @@ -34,7 +34,6 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.partition.StepExecutionSplitter; import org.springframework.batch.core.step.StepSupport; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.core.task.TaskExecutor; import org.springframework.core.task.TaskRejectedException; class TaskExecutorPartitionHandlerTests { @@ -111,14 +110,11 @@ class TaskExecutorPartitionHandlerTests { @Test void testTaskExecutorFailure() throws Exception { handler.setGridSize(2); - handler.setTaskExecutor(new TaskExecutor() { - @Override - public void execute(Runnable task) { - if (count > 0) { - throw new TaskRejectedException("foo"); - } - task.run(); + handler.setTaskExecutor(task -> { + if (count > 0) { + throw new TaskRejectedException("foo"); } + task.run(); }); Collection executions = handler.handle(stepExecutionSplitter, stepExecution); new DefaultStepExecutionAggregator().aggregate(stepExecution, executions); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java index fddd692d7..5af17368e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncJobScopeIntegrationTests.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import org.apache.commons.logging.Log; @@ -91,20 +90,17 @@ public class AsyncJobScopeIntegrationTests implements BeanFactoryAware { for (int i = 0; i < 12; i++) { final String value = "foo" + i; final Long id = 123L + i; - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - JobExecution jobExecution = new JobExecution(id); - ExecutionContext executionContext = jobExecution.getExecutionContext(); - executionContext.put("foo", value); - JobContext context = JobSynchronizationManager.register(jobExecution); - logger.debug("Registered: " + context.getJobExecutionContext()); - try { - return simple.getName(); - } - finally { - JobSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + JobExecution jobExecution = new JobExecution(id); + ExecutionContext executionContext = jobExecution.getExecutionContext(); + executionContext.put("foo", value); + JobContext context = JobSynchronizationManager.register(jobExecution); + logger.debug("Registered: " + context.getJobExecutionContext()); + try { + return simple.getName(); + } + finally { + JobSynchronizationManager.close(); } }); tasks.add(task); @@ -131,19 +127,16 @@ public class AsyncJobScopeIntegrationTests implements BeanFactoryAware { for (int i = 0; i < 12; i++) { final String value = "foo" + i; - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - ExecutionContext executionContext = jobExecution.getExecutionContext(); - executionContext.put("foo", value); - JobContext context = JobSynchronizationManager.register(jobExecution); - logger.debug("Registered: " + context.getJobExecutionContext()); - try { - return simple.getName(); - } - finally { - JobSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + ExecutionContext executionContext1 = jobExecution.getExecutionContext(); + executionContext1.put("foo", value); + JobContext context = JobSynchronizationManager.register(jobExecution); + logger.debug("Registered: " + context.getJobExecutionContext()); + try { + return simple.getName(); + } + finally { + JobSynchronizationManager.close(); } }); tasks.add(task); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java index c83247bcd..bb84eb9b7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/AsyncStepScopeIntegrationTests.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import org.apache.commons.logging.Log; @@ -92,20 +91,17 @@ public class AsyncStepScopeIntegrationTests implements BeanFactoryAware { for (int i = 0; i < 12; i++) { final String value = "foo" + i; final Long id = 123L + i; - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - StepExecution stepExecution = new StepExecution(value, new JobExecution(0L), id); - ExecutionContext executionContext = stepExecution.getExecutionContext(); - executionContext.put("foo", value); - StepContext context = StepSynchronizationManager.register(stepExecution); - logger.debug("Registered: " + context.getStepExecutionContext()); - try { - return simple.getName(); - } - finally { - StepSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + StepExecution stepExecution = new StepExecution(value, new JobExecution(0L), id); + ExecutionContext executionContext = stepExecution.getExecutionContext(); + executionContext.put("foo", value); + StepContext context = StepSynchronizationManager.register(stepExecution); + logger.debug("Registered: " + context.getStepExecutionContext()); + try { + return simple.getName(); + } + finally { + StepSynchronizationManager.close(); } }); tasks.add(task); @@ -132,19 +128,16 @@ public class AsyncStepScopeIntegrationTests implements BeanFactoryAware { for (int i = 0; i < 12; i++) { final String value = "foo" + i; - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - ExecutionContext executionContext = stepExecution.getExecutionContext(); - executionContext.put("foo", value); - StepContext context = StepSynchronizationManager.register(stepExecution); - logger.debug("Registered: " + context.getStepExecutionContext()); - try { - return simple.getName(); - } - finally { - StepSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + ExecutionContext executionContext1 = stepExecution.getExecutionContext(); + executionContext1.put("foo", value); + StepContext context = StepSynchronizationManager.register(stepExecution); + logger.debug("Registered: " + context.getStepExecutionContext()); + try { + return simple.getName(); + } + finally { + StepSynchronizationManager.close(); } }); tasks.add(task); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java index fc67ba549..125085909 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/JobScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -30,13 +30,13 @@ import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.scope.context.JobContext; import org.springframework.batch.core.scope.context.JobSynchronizationManager; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.context.support.StaticApplicationContext; /** * @author Dave Syer * @author Jimmy Praet + * @author Mahmoud Ben Hassine */ class JobScopeTests { @@ -60,23 +60,13 @@ class JobScopeTests { void testGetWithNoContext() { final String foo = "bar"; JobSynchronizationManager.release(); - assertThrows(IllegalStateException.class, () -> scope.get("foo", new ObjectFactory() { - @Override - public String getObject() throws BeansException { - return foo; - } - })); + assertThrows(IllegalStateException.class, () -> scope.get("foo", (ObjectFactory) () -> foo)); } @Test void testGetWithNothingAlreadyThere() { final String foo = "bar"; - Object value = scope.get("foo", new ObjectFactory() { - @Override - public String getObject() throws BeansException { - return foo; - } - }); + Object value = scope.get("foo", (ObjectFactory) () -> foo); assertEquals(foo, value); assertTrue(context.hasAttribute("foo")); } @@ -84,12 +74,7 @@ class JobScopeTests { @Test void testGetWithSomethingAlreadyThere() { context.setAttribute("foo", "bar"); - Object value = scope.get("foo", new ObjectFactory() { - @Override - public String getObject() throws BeansException { - return null; - } - }); + Object value = scope.get("foo", (ObjectFactory) () -> null); assertEquals("bar", value); assertTrue(context.hasAttribute("foo")); } @@ -104,12 +89,7 @@ class JobScopeTests { void testRegisterDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + scope.registerDestructionCallback("foo", () -> list.add("foo")); assertEquals(0, list.size()); // When the context is closed, provided the attribute exists the // callback is called... @@ -121,18 +101,8 @@ class JobScopeTests { void testRegisterAnotherDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + scope.registerDestructionCallback("foo", () -> list.add("foo")); + scope.registerDestructionCallback("foo", () -> list.add("bar")); assertEquals(0, list.size()); // When the context is closed, provided the attribute exists the // callback is called... diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java index 7c3d901ab..2309d1004 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/StepScopeTests.java @@ -32,8 +32,6 @@ import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.StepContext; import org.springframework.batch.core.scope.context.StepSynchronizationManager; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.ObjectFactory; import org.springframework.context.support.StaticApplicationContext; /** @@ -64,23 +62,13 @@ class StepScopeTests { void testGetWithNoContext() { final String foo = "bar"; StepSynchronizationManager.close(); - assertThrows(IllegalStateException.class, () -> scope.get("foo", new ObjectFactory<>() { - @Override - public Object getObject() throws BeansException { - return foo; - } - })); + assertThrows(IllegalStateException.class, () -> scope.get("foo", () -> foo)); } @Test void testGetWithNothingAlreadyThere() { final String foo = "bar"; - Object value = scope.get("foo", new ObjectFactory<>() { - @Override - public Object getObject() throws BeansException { - return foo; - } - }); + Object value = scope.get("foo", () -> foo); assertEquals(foo, value); assertTrue(context.hasAttribute("foo")); } @@ -88,12 +76,7 @@ class StepScopeTests { @Test void testGetWithSomethingAlreadyThere() { context.setAttribute("foo", "bar"); - Object value = scope.get("foo", new ObjectFactory<>() { - @Override - public Object getObject() throws BeansException { - return null; - } - }); + Object value = scope.get("foo", () -> null); assertEquals("bar", value); assertTrue(context.hasAttribute("foo")); } @@ -102,12 +85,7 @@ class StepScopeTests { void testGetWithSomethingAlreadyInParentContext() { context.setAttribute("foo", "bar"); StepContext context = StepSynchronizationManager.register(new StepExecution("bar", new JobExecution(0L))); - Object value = scope.get("foo", new ObjectFactory<>() { - @Override - public Object getObject() throws BeansException { - return "spam"; - } - }); + Object value = scope.get("foo", () -> "spam"); assertEquals("spam", value); assertTrue(context.hasAttribute("foo")); StepSynchronizationManager.close(); @@ -131,12 +109,7 @@ class StepScopeTests { void testRegisterDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + scope.registerDestructionCallback("foo", () -> list.add("foo")); assertEquals(0, list.size()); // When the context is closed, provided the attribute exists the // callback is called... @@ -148,18 +121,8 @@ class StepScopeTests { void testRegisterAnotherDestructionCallback() { final List list = new ArrayList<>(); context.setAttribute("foo", "bar"); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); - scope.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + scope.registerDestructionCallback("foo", () -> list.add("foo")); + scope.registerDestructionCallback("foo", () -> list.add("bar")); assertEquals(0, list.size()); // When the context is closed, provided the attribute exists the // callback is called... diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java index ca9acf69a..588b6c57b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobContextTests.java @@ -83,12 +83,7 @@ class JobContextTests { @Test void testDestructionCallbackSunnyDay() { context.setAttribute("foo", "FOO"); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("bar")); context.close(); assertEquals(1, list.size()); assertEquals("bar", list.get(0)); @@ -96,12 +91,7 @@ class JobContextTests { @Test void testDestructionCallbackMissingAttribute() { - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("bar")); context.close(); // Yes the callback should be called even if the attribute is missing - // for inner beans @@ -112,19 +102,13 @@ class JobContextTests { void testDestructionCallbackWithException() { context.setAttribute("foo", "FOO"); context.setAttribute("bar", "BAR"); - context.registerDestructionCallback("bar", new Runnable() { - @Override - public void run() { - list.add("spam"); - throw new RuntimeException("fail!"); - } + context.registerDestructionCallback("bar", () -> { + list.add("spam"); + throw new RuntimeException("fail!"); }); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - throw new RuntimeException("fail!"); - } + context.registerDestructionCallback("foo", () -> { + list.add("bar"); + throw new RuntimeException("fail!"); }); Exception exception = assertThrows(RuntimeException.class, () -> context.close()); // We don't care which one was thrown... diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java index 9243030f2..66a9bce9f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/JobSynchronizationManagerTests.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; @@ -36,6 +35,7 @@ import org.springframework.batch.core.JobExecution; * JobSynchronizationManagerTests. * * @author Jimmy Praet + * @author Mahmoud Ben Hassine */ class JobSynchronizationManagerTests { @@ -60,12 +60,7 @@ class JobSynchronizationManagerTests { void testClose() { final List list = new ArrayList<>(); JobContext context = JobSynchronizationManager.register(jobExecution); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("foo")); JobSynchronizationManager.close(); assertNull(JobSynchronizationManager.getContext()); assertEquals(0, list.size()); @@ -75,18 +70,15 @@ class JobSynchronizationManagerTests { void testMultithreaded() throws Exception { JobContext context = JobSynchronizationManager.register(jobExecution); ExecutorService executorService = Executors.newFixedThreadPool(2); - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public JobContext call() throws Exception { - try { - JobSynchronizationManager.register(jobExecution); - JobContext context = JobSynchronizationManager.getContext(); - context.setAttribute("foo", "bar"); - return context; - } - finally { - JobSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + try { + JobSynchronizationManager.register(jobExecution); + JobContext context1 = JobSynchronizationManager.getContext(); + context1.setAttribute("foo", "bar"); + return context1; + } + finally { + JobSynchronizationManager.close(); } }); executorService.execute(task); @@ -100,12 +92,7 @@ class JobSynchronizationManagerTests { void testRelease() { JobContext context = JobSynchronizationManager.register(jobExecution); final List list = new ArrayList<>(); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("foo")); // On release we expect the destruction callbacks to be called JobSynchronizationManager.release(); assertNull(JobSynchronizationManager.getContext()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java index a0448a96a..f7f52153f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepContextTests.java @@ -76,12 +76,7 @@ class StepContextTests { @Test void testDestructionCallbackSunnyDay() { context.setAttribute("foo", "FOO"); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("bar")); context.close(); assertEquals(1, list.size()); assertEquals("bar", list.get(0)); @@ -89,12 +84,7 @@ class StepContextTests { @Test void testDestructionCallbackMissingAttribute() { - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("bar")); context.close(); // Yes the callback should be called even if the attribute is missing - // for inner beans @@ -105,19 +95,13 @@ class StepContextTests { void testDestructionCallbackWithException() { context.setAttribute("foo", "FOO"); context.setAttribute("bar", "BAR"); - context.registerDestructionCallback("bar", new Runnable() { - @Override - public void run() { - list.add("spam"); - throw new RuntimeException("fail!"); - } + context.registerDestructionCallback("bar", () -> { + list.add("spam"); + throw new RuntimeException("fail!"); }); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("bar"); - throw new RuntimeException("fail!"); - } + context.registerDestructionCallback("foo", () -> { + list.add("bar"); + throw new RuntimeException("fail!"); }); Exception exception = assertThrows(RuntimeException.class, () -> context.close()); // We don't care which one was thrown... diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java index 54fb67f55..a7c7158c4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/scope/context/StepSynchronizationManagerTests.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; @@ -56,12 +55,7 @@ class StepSynchronizationManagerTests { void testClose() { final List list = new ArrayList<>(); StepContext context = StepSynchronizationManager.register(stepExecution); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("foo")); StepSynchronizationManager.close(); assertNull(StepSynchronizationManager.getContext()); assertEquals(0, list.size()); @@ -71,18 +65,15 @@ class StepSynchronizationManagerTests { void testMultithreaded() throws Exception { StepContext context = StepSynchronizationManager.register(stepExecution); ExecutorService executorService = Executors.newFixedThreadPool(2); - FutureTask task = new FutureTask<>(new Callable<>() { - @Override - public StepContext call() throws Exception { - try { - StepSynchronizationManager.register(stepExecution); - StepContext context = StepSynchronizationManager.getContext(); - context.setAttribute("foo", "bar"); - return context; - } - finally { - StepSynchronizationManager.close(); - } + FutureTask task = new FutureTask<>(() -> { + try { + StepSynchronizationManager.register(stepExecution); + StepContext context1 = StepSynchronizationManager.getContext(); + context1.setAttribute("foo", "bar"); + return context1; + } + finally { + StepSynchronizationManager.close(); } }); executorService.execute(task); @@ -96,12 +87,7 @@ class StepSynchronizationManagerTests { void testRelease() { StepContext context = StepSynchronizationManager.register(stepExecution); final List list = new ArrayList<>(); - context.registerDestructionCallback("foo", new Runnable() { - @Override - public void run() { - list.add("foo"); - } - }); + context.registerDestructionCallback("foo", () -> list.add("foo")); // On release we expect the destruction callbacks to be called StepSynchronizationManager.release(); assertNull(StepSynchronizationManager.getContext()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java index aaeb0f877..c5a6e297e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java @@ -167,15 +167,10 @@ class RegisterMultiListenerTests { @Bean public ItemWriter writer() { - return new ItemWriter<>() { - - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("item2")) { - throw new MySkippableException(); - } + return chunk -> { + if (chunk.getItems().contains("item2")) { + throw new MySkippableException(); } - }; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java index e8526d750..77711e7d4 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/BatchRetryTemplateTests.java @@ -19,7 +19,6 @@ import org.junit.jupiter.api.Test; import org.springframework.retry.ExhaustedRetryException; import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryCallback; -import org.springframework.retry.RetryContext; import org.springframework.retry.RetryState; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.DefaultRetryState; @@ -52,13 +51,10 @@ class BatchRetryTemplateTests { BatchRetryTemplate template = new BatchRetryTemplate(); - String result = template.execute(new RetryCallback() { - @Override - public String doWithRetry(RetryContext context) throws Exception { - assertTrue(context.getClass().getSimpleName().contains("Batch"), - "Wrong context type: " + context.getClass().getSimpleName()); - return "2"; - } + String result = template.execute((RetryCallback) context -> { + assertTrue(context.getClass().getSimpleName().contains("Batch"), + "Wrong context type: " + context.getClass().getSimpleName()); + return "2"; }, Arrays.asList(new DefaultRetryState("1"))); assertEquals("2", result); @@ -70,15 +66,12 @@ class BatchRetryTemplateTests { BatchRetryTemplate template = new BatchRetryTemplate(); - RetryCallback retryCallback = new RetryCallback<>() { - @Override - public String[] doWithRetry(RetryContext context) throws Exception { - assertEquals(count, context.getRetryCount()); - if (count++ == 0) { - throw new RecoverableException("Recoverable"); - } - return new String[] { "a", "b" }; + RetryCallback retryCallback = context -> { + assertEquals(count, context.getRetryCount()); + if (count++ == 0) { + throw new RecoverableException("Recoverable"); } + return new String[] { "a", "b" }; }; List states = Arrays.asList(new DefaultRetryState("1"), new DefaultRetryState("2")); @@ -97,14 +90,11 @@ class BatchRetryTemplateTests { template.setRetryPolicy(new SimpleRetryPolicy(1, Collections., Boolean>singletonMap(Exception.class, true))); - RetryCallback retryCallback = new RetryCallback<>() { - @Override - public String[] doWithRetry(RetryContext context) throws Exception { - if (count++ < 2) { - throw new RecoverableException("Recoverable"); - } - return outputs.toArray(new String[0]); + RetryCallback retryCallback = context -> { + if (count++ < 2) { + throw new RecoverableException("Recoverable"); } + return outputs.toArray(new String[0]); }; outputs = List.of("a", "b"); @@ -123,14 +113,11 @@ class BatchRetryTemplateTests { template.setRetryPolicy(new SimpleRetryPolicy(1, Collections., Boolean>singletonMap(Exception.class, true))); - RetryCallback retryCallback = new RetryCallback<>() { - @Override - public String[] doWithRetry(RetryContext context) throws Exception { - if (count++ < 1) { - throw new RecoverableException("Recoverable"); - } - return outputs.toArray(new String[0]); + RetryCallback retryCallback = context -> { + if (count++ < 1) { + throw new RecoverableException("Recoverable"); } + return outputs.toArray(new String[0]); }; outputs = Arrays.asList("a", "b"); @@ -166,25 +153,19 @@ class BatchRetryTemplateTests { template.setRetryPolicy(new SimpleRetryPolicy(1, Collections., Boolean>singletonMap(Exception.class, true))); - RetryCallback retryCallback = new RetryCallback<>() { - @Override - public String[] doWithRetry(RetryContext context) throws Exception { - if (count++ < 2) { - throw new RecoverableException("Recoverable"); - } - return outputs.toArray(new String[0]); + RetryCallback retryCallback = context -> { + if (count++ < 2) { + throw new RecoverableException("Recoverable"); } + return outputs.toArray(new String[0]); }; - RecoveryCallback recoveryCallback = new RecoveryCallback<>() { - @Override - public String[] recover(RetryContext context) throws Exception { - List recovered = new ArrayList<>(); - for (String item : outputs) { - recovered.add("r:" + item); - } - return recovered.toArray(new String[0]); + RecoveryCallback recoveryCallback = context -> { + List recovered = new ArrayList<>(); + for (String item : outputs) { + recovered.add("r:" + item); } + return recovered.toArray(new String[0]); }; outputs = Arrays.asList("a", "b"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java index 3b4eed858..5ed3526e8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java @@ -52,12 +52,7 @@ class ChunkOrientedTaskletTests { @Override public void postProcess(StepContribution contribution, Chunk chunk) { } - }, new ChunkProcessor<>() { - @Override - public void process(StepContribution contribution, Chunk chunk) { - contribution.incrementWriteCount(1); - } - }); + }, (contribution, chunk) -> contribution.incrementWriteCount(1)); StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); handler.execute(contribution, context); @@ -77,12 +72,7 @@ class ChunkOrientedTaskletTests { @Override public void postProcess(StepContribution contribution, Chunk chunk) { } - }, new ChunkProcessor<>() { - @Override - public void process(StepContribution contribution, Chunk chunk) { - fail("Not expecting to get this far"); - } - }); + }, (contribution, chunk) -> fail("Not expecting to get this far")); StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); Exception exception = assertThrows(RuntimeException.class, () -> handler.execute(contribution, context)); @@ -105,12 +95,7 @@ class ChunkOrientedTaskletTests { @Override public void postProcess(StepContribution contribution, Chunk chunk) { } - }, new ChunkProcessor<>() { - @Override - public void process(StepContribution contribution, Chunk chunk) { - contribution.incrementWriteCount(1); - } - }); + }, (contribution, chunk) -> contribution.incrementWriteCount(1)); StepContribution contribution = new StepContribution( new StepExecution("foo", new JobExecution(new JobInstance(123L, "job"), new JobParameters()))); ExitStatus expected = contribution.getExitStatus(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java index cdc824b7b..c87631b71 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java @@ -39,7 +39,6 @@ import org.springframework.batch.core.step.skip.AlwaysSkipItemSkipPolicy; import org.springframework.batch.core.step.skip.LimitCheckingItemSkipPolicy; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; -import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.support.PassThroughItemProcessor; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.dao.DataIntegrityViolationException; @@ -67,14 +66,11 @@ class FaultTolerantChunkProcessorTests { @BeforeEach void setUp() { batchRetryTemplate = new BatchRetryTemplate(); - processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new RuntimeException("Planned failure!"); - } - list.addAll(chunk.getItems()); + processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), chunk -> { + if (chunk.getItems().contains("fail")) { + throw new RuntimeException("Planned failure!"); } + list.addAll(chunk.getItems()); }, batchRetryTemplate); batchRetryTemplate.setRetryPolicy(new NeverRetryPolicy()); } @@ -194,12 +190,9 @@ class FaultTolerantChunkProcessorTests { @Test void testWriteSkipOnError() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - fail("Expected Error!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + fail("Expected Error!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); @@ -211,12 +204,9 @@ class FaultTolerantChunkProcessorTests { @Test void testWriteSkipOnException() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new RuntimeException("Expected Exception!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + throw new RuntimeException("Expected Exception!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); @@ -233,12 +223,9 @@ class FaultTolerantChunkProcessorTests { @Test void testWriteSkipOnExceptionWithTrivialChunk() throws Exception { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new RuntimeException("Expected Exception!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + throw new RuntimeException("Expected Exception!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("fail")); @@ -302,15 +289,12 @@ class FaultTolerantChunkProcessorTests { @Test void testAfterWriteAllPassedInRecovery() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); - processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - // Fail if there is more than one item - if (chunk.size() > 1) { - throw new RuntimeException("Planned failure!"); - } - list.addAll(chunk.getItems()); + processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), chunk1 -> { + // Fail if there is more than one item + if (chunk1.size() > 1) { + throw new RuntimeException("Planned failure!"); } + list.addAll(chunk1.getItems()); }, batchRetryTemplate); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override @@ -349,12 +333,9 @@ class FaultTolerantChunkProcessorTests { @Test void testOnErrorInWriteAllItemsFail() throws Exception { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); - processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter<>() { - @Override - public void write(Chunk items) throws Exception { - // Always fail in writer - throw new RuntimeException("Planned failure!"); - } + processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), items -> { + // Always fail in writer + throw new RuntimeException("Planned failure!"); }, batchRetryTemplate); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override @@ -377,12 +358,9 @@ class FaultTolerantChunkProcessorTests { retryPolicy.setMaxAttempts(2); batchRetryTemplate.setRetryPolicy(retryPolicy); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new IllegalArgumentException("Expected Exception!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + throw new IllegalArgumentException("Expected Exception!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); @@ -410,12 +388,9 @@ class FaultTolerantChunkProcessorTests { retryPolicy.setMaxAttempts(2); batchRetryTemplate.setRetryPolicy(retryPolicy); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new IllegalArgumentException("Expected Exception!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + throw new IllegalArgumentException("Expected Exception!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "fail", "4")); @@ -447,15 +422,12 @@ class FaultTolerantChunkProcessorTests { batchRetryTemplate.setRetryPolicy(retryPolicy); processor.setWriteSkipPolicy(new LimitCheckingItemSkipPolicy(1, Collections., Boolean>singletonMap(IllegalArgumentException.class, true))); - processor.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - if (chunk.getItems().contains("fail")) { - throw new IllegalArgumentException("Expected Exception!"); - } - if (chunk.getItems().contains("2")) { - throw new RuntimeException("Expected Non-Skippable Exception!"); - } + processor.setItemWriter(chunk -> { + if (chunk.getItems().contains("fail")) { + throw new IllegalArgumentException("Expected Exception!"); + } + if (chunk.getItems().contains("2")) { + throw new RuntimeException("Expected Non-Skippable Exception!"); } }); Chunk inputs = new Chunk<>(Arrays.asList("3", "fail", "2")); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java index cdb7e649f..88f430e5a 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java @@ -23,7 +23,6 @@ import java.util.List; import java.util.Map; import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.BeforeEach; @@ -47,7 +46,6 @@ import org.springframework.batch.core.repository.support.JobRepositoryFactoryBea import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.factory.FaultTolerantStepFactoryBean; import org.springframework.batch.core.step.skip.LimitCheckingItemSkipPolicy; -import org.springframework.batch.core.step.skip.SkipLimitExceededException; import org.springframework.batch.core.step.skip.SkipPolicy; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; @@ -269,11 +267,8 @@ public class FaultTolerantStepFactoryBeanTests { // Should be ignored factory.setSkipLimit(0); - factory.setSkipPolicy(new SkipPolicy() { - @Override - public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededException { - throw new RuntimeException("Planned exception in SkipPolicy"); - } + factory.setSkipPolicy((t, skipCount) -> { + throw new RuntimeException("Planned exception in SkipPolicy"); }); reader.setFailures("2"); @@ -297,11 +292,8 @@ public class FaultTolerantStepFactoryBeanTests { // Should be ignored factory.setSkipLimit(0); - factory.setSkipPolicy(new SkipPolicy() { - @Override - public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededException { - throw new RuntimeException("Planned exception in SkipPolicy"); - } + factory.setSkipPolicy((t, skipCount) -> { + throw new RuntimeException("Planned exception in SkipPolicy"); }); writer.setFailures("2"); @@ -451,11 +443,8 @@ public class FaultTolerantStepFactoryBeanTests { map.put(SkippableRuntimeException.class, true); map.put(FatalRuntimeException.class, false); factory.setSkippableExceptionClasses(map); - factory.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk items) { - throw new FatalRuntimeException("Ouch!"); - } + factory.setItemWriter(items -> { + throw new FatalRuntimeException("Ouch!"); }); Step step = factory.getObject(); @@ -986,12 +975,7 @@ public class FaultTolerantStepFactoryBeanTests { ProxyFactory proxy = new ProxyFactory(); proxy.setTarget(reader); proxy.setInterfaces(new Class[] { ItemReader.class, ItemStream.class }); - proxy.addAdvice(new MethodInterceptor() { - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - return invocation.proceed(); - } - }); + proxy.addAdvice((MethodInterceptor) invocation -> invocation.proceed()); Object advised = proxy.getProxy(); factory.setItemReader((ItemReader) advised); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java index c97d974cb..88c2982aa 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/RepeatOperationsStepFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -30,8 +30,6 @@ import org.springframework.batch.core.launch.EmptyItemWriter; import org.springframework.batch.core.step.JobRepositorySupport; import org.springframework.batch.core.step.factory.SimpleStepFactoryBean; import org.springframework.batch.item.support.ListItemReader; -import org.springframework.batch.repeat.RepeatCallback; -import org.springframework.batch.repeat.RepeatOperations; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; @@ -40,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class RepeatOperationsStepFactoryBeanTests { @@ -78,14 +77,10 @@ class RepeatOperationsStepFactoryBeanTests { factory.setJobRepository(new JobRepositorySupport()); factory.setTransactionManager(new ResourcelessTransactionManager()); - factory.setStepOperations(new RepeatOperations() { - - @Override - public RepeatStatus iterate(RepeatCallback callback) { - list = new ArrayList<>(); - list.add("foo"); - return RepeatStatus.FINISHED; - } + factory.setStepOperations(callback -> { + list = new ArrayList<>(); + list.add("foo"); + return RepeatStatus.FINISHED; }); Step step = factory.getObject(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java index 3ac0ad8f2..a289cd09f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java @@ -71,12 +71,7 @@ class SimpleStepFactoryBeanTests { private final List written = new ArrayList<>(); - private final ItemWriter writer = new ItemWriter<>() { - @Override - public void write(Chunk data) throws Exception { - written.addAll(data.getItems()); - } - }; + private final ItemWriter writer = data -> written.addAll(data.getItems()); private ItemReader reader = new ListItemReader<>(Arrays.asList("a", "b", "c")); @@ -175,11 +170,8 @@ class SimpleStepFactoryBeanTests { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); - factory.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk data) throws Exception { - throw new RuntimeException("Error!"); - } + factory.setItemWriter(data -> { + throw new RuntimeException("Error!"); }); factory.setListeners(new StepListener[] { new ItemListenerSupport() { @Override @@ -213,11 +205,8 @@ class SimpleStepFactoryBeanTests { void testExceptionTerminates() throws Exception { SimpleStepFactoryBean factory = getStepFactory(new String[] { "foo", "bar", "spam" }); factory.setBeanName("exceptionStep"); - factory.setItemWriter(new ItemWriter<>() { - @Override - public void write(Chunk data) throws Exception { - throw new RuntimeException("Foo"); - } + factory.setItemWriter(data -> { + throw new RuntimeException("Foo"); }); AbstractStep step = (AbstractStep) factory.getObject(); job.setSteps(Collections.singletonList((Step) step)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java index 81303fc99..014caf073 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/job/DefaultJobParametersExtractorJobParametersTests.java @@ -26,7 +26,6 @@ import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.converter.DefaultJobParametersConverter; -import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -47,12 +46,7 @@ class DefaultJobParametersExtractorJobParametersTests { @BeforeEach void setUp() { DefaultConversionService conversionService = new DefaultConversionService(); - conversionService.addConverter(String.class, LocalDate.class, new Converter<>() { - @Override - public LocalDate convert(String source) { - return LocalDate.parse(source); - } - }); + conversionService.addConverter(String.class, LocalDate.class, source -> LocalDate.parse(source)); this.jobParametersConverter.setConversionService(conversionService); this.extractor.setJobParametersConverter(this.jobParametersConverter); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java index 1bb858700..5a3efbf65 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java @@ -34,9 +34,7 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.job.JobSupport; import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; -import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.support.ListItemReader; import org.springframework.batch.repeat.policy.SimpleCompletionPolicy; import org.springframework.batch.repeat.support.RepeatTemplate; @@ -45,8 +43,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -125,12 +121,7 @@ class AsyncChunkOrientedStepIntegrationTests { step.setTasklet(new TestingChunkOrientedTasklet<>( getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }), - new ItemWriter<>() { - @Override - public void write(Chunk data) throws Exception { - written.addAll(data.getItems()); - } - }, chunkOperations)); + data -> written.addAll(data.getItems()), chunkOperations)); final JobExecution jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters( Collections.singletonMap("run.id", new JobParameter(getClass().getName() + ".1", Long.class)))); @@ -142,12 +133,7 @@ class AsyncChunkOrientedStepIntegrationTests { // Need a transaction so one connection is enough to get job execution and its // parameters StepExecution lastStepExecution = new TransactionTemplate(transactionManager) - .execute(new TransactionCallback<>() { - @Override - public StepExecution doInTransaction(TransactionStatus status) { - return jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName()); - } - }); + .execute(status -> jobRepository.getLastStepExecution(jobExecution.getJobInstance(), step.getName())); assertEquals(lastStepExecution, stepExecution); assertNotSame(lastStepExecution, stepExecution); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java index d157ca134..07f861fb5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/CallableTaskletAdapterTests.java @@ -18,8 +18,6 @@ package org.springframework.batch.core.step.tasklet; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.concurrent.Callable; - import org.junit.jupiter.api.Test; import org.springframework.batch.repeat.RepeatStatus; @@ -29,12 +27,7 @@ class CallableTaskletAdapterTests { @Test void testHandle() throws Exception { - adapter.setCallable(new Callable<>() { - @Override - public RepeatStatus call() throws Exception { - return RepeatStatus.FINISHED; - } - }); + adapter.setCallable(() -> RepeatStatus.FINISHED); assertEquals(RepeatStatus.FINISHED, adapter.execute(null, null)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java index 604d623ea..2ff333b76 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java @@ -33,7 +33,6 @@ import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteExcep import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; -import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.repeat.policy.SimpleCompletionPolicy; @@ -89,10 +88,7 @@ class StepExecutorInterruptionTests { jobExecution = jobRepository.createJobExecution(job.getName(), new JobParameters()); step.setJobRepository(jobRepository); step.setTransactionManager(this.transactionManager); - itemWriter = new ItemWriter<>() { - @Override - public void write(Chunk item) throws Exception { - } + itemWriter = item -> { }; stepExecution = new StepExecution(step.getName(), jobExecution); } @@ -235,18 +231,15 @@ class StepExecutorInterruptionTests { * @return */ private Thread createThread(final StepExecution stepExecution) { - Thread processingThread = new Thread() { - @Override - public void run() { - try { - jobRepository.add(stepExecution); - step.execute(stepExecution); - } - catch (JobInterruptedException e) { - // do nothing... - } + Thread processingThread = new Thread(() -> { + try { + jobRepository.add(stepExecution); + step.execute(stepExecution); } - }; + catch (JobInterruptedException e) { + // do nothing... + } + }); processingThread.setDaemon(true); processingThread.setPriority(Thread.MIN_PRIORITY); return processingThread; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java index 0d3593ebe..dcb0a213c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java @@ -45,7 +45,6 @@ import org.springframework.batch.core.repository.support.JobRepositoryFactoryBea import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.JobRepositorySupport; import org.springframework.batch.core.step.StepInterruptionPolicy; -import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemStream; @@ -74,12 +73,7 @@ class TaskletStepTests { private final List list = new ArrayList<>(); - ItemWriter itemWriter = new ItemWriter<>() { - @Override - public void write(Chunk data) throws Exception { - processed.addAll(data.getItems()); - } - }; + ItemWriter itemWriter = data -> processed.addAll(data.getItems()); private TaskletStep step; @@ -599,12 +593,8 @@ class TaskletStepTests { @Test void testStatusForInterruptedException() throws Exception { - StepInterruptionPolicy interruptionPolicy = new StepInterruptionPolicy() { - - @Override - public void checkInterrupted(StepExecution stepExecution) throws JobInterruptedException { - throw new JobInterruptedException("interrupted"); - } + StepInterruptionPolicy interruptionPolicy = stepExecution -> { + throw new JobInterruptedException("interrupted"); }; step.setInterruptionPolicy(interruptionPolicy); diff --git a/spring-batch-core/src/test/java/test/jdbc/datasource/DataSourceInitializer.java b/spring-batch-core/src/test/java/test/jdbc/datasource/DataSourceInitializer.java index 4f09a1e2d..2bd7ca7d7 100644 --- a/spring-batch-core/src/test/java/test/jdbc/datasource/DataSourceInitializer.java +++ b/spring-batch-core/src/test/java/test/jdbc/datasource/DataSourceInitializer.java @@ -31,7 +31,6 @@ import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.JdbcTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.Assert; @@ -98,38 +97,33 @@ public class DataSourceInitializer implements InitializingBean { } TransactionTemplate transactionTemplate = new TransactionTemplate(new JdbcTransactionManager(dataSource)); - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Void doInTransaction(TransactionStatus status) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - String[] scripts; - try { - scripts = StringUtils.delimitedListToStringArray( - stripComments(IOUtils.readLines(scriptResource.getInputStream(), "UTF-8")), ";"); - } - catch (IOException e) { - throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); - } - for (String s : scripts) { - String script = s.trim(); - if (StringUtils.hasText(script)) { - try { - jdbcTemplate.execute(script); + transactionTemplate.execute((TransactionCallback) status -> { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); + String[] scripts; + try { + scripts = StringUtils.delimitedListToStringArray( + stripComments(IOUtils.readLines(scriptResource.getInputStream(), "UTF-8")), ";"); + } + catch (IOException e) { + throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); + } + for (String s : scripts) { + String script = s.trim(); + if (StringUtils.hasText(script)) { + try { + jdbcTemplate.execute(script); + } + catch (DataAccessException e) { + if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { + logger.debug("DROP script failed (ignoring): " + script); } - catch (DataAccessException e) { - if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { - logger.debug("DROP script failed (ignoring): " + script); - } - else { - throw e; - } + else { + throw e; } } } - return null; } - + return null; }); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java index 439de1531..e81ed4c49 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.PreparedStatement; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -28,7 +26,6 @@ import org.apache.commons.logging.LogFactory; import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; -import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.PreparedStatementCallback; @@ -192,16 +189,12 @@ public class JdbcBatchItemWriter implements ItemWriter, InitializingBean { } else { updateCounts = namedParameterJdbcTemplate.getJdbcOperations() - .execute(sql, new PreparedStatementCallback<>() { - @Override - public int[] doInPreparedStatement(PreparedStatement ps) - throws SQLException, DataAccessException { - for (T item : chunk) { - itemPreparedStatementSetter.setValues(item, ps); - ps.addBatch(); - } - return ps.executeBatch(); + .execute(sql, (PreparedStatementCallback) ps -> { + for (T item : chunk) { + itemPreparedStatementSetter.setValues(item, ps); + ps.addBatch(); } + return ps.executeBatch(); }); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java index b0289b573..a22d3585c 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java @@ -21,7 +21,6 @@ import org.springframework.util.StringUtils; import java.beans.PropertyEditorSupport; import java.util.Arrays; -import java.util.Comparator; /** * Property editor implementation which parses string and creates array of ranges. Ranges @@ -120,12 +119,7 @@ public class RangeArrayPropertyEditor extends PropertyEditorSupport { } // sort array of Ranges - Arrays.sort(c, new Comparator<>() { - @Override - public int compare(Integer r1, Integer r2) { - return ranges[r1].getMin() - ranges[r2].getMin(); - } - }); + Arrays.sort(c, (r1, r2) -> ranges[r1].getMin() - ranges[r2].getMin()); // set max values for all unbound ranges (except last range) for (int i = 0; i < c.length - 1; i++) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java index 05d79a6cc..db4a36135 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java @@ -481,12 +481,8 @@ public class StaxEventItemWriter extends AbstractItemStreamItemWriter 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); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java index 034b78e0c..422370fb9 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java @@ -20,8 +20,6 @@ import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.ProxyMethodInvocation; import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.batch.repeat.RepeatCallback; -import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.RepeatException; import org.springframework.batch.repeat.RepeatOperations; import org.springframework.batch.repeat.support.RepeatTemplate; @@ -73,45 +71,40 @@ public class RepeatOperationsInterceptor implements MethodInterceptor { } try { - repeatOperations.iterate(new RepeatCallback() { + repeatOperations.iterate(context -> { + try { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - try { - - MethodInvocation clone = invocation; - if (invocation instanceof ProxyMethodInvocation) { - clone = ((ProxyMethodInvocation) invocation).invocableClone(); - } - else { - throw new IllegalStateException( - "MethodInvocation of the wrong type detected - this should not happen with Spring AOP, so please raise an issue if you see this exception"); - } - - Object value = clone.proceed(); - if (voidReturnType) { - return RepeatStatus.CONTINUABLE; - } - if (!isComplete(value)) { - // Save the last result - result.setValue(value); - return RepeatStatus.CONTINUABLE; - } - else { - result.setFinalValue(value); - return RepeatStatus.FINISHED; - } + MethodInvocation clone = invocation; + if (invocation instanceof ProxyMethodInvocation) { + clone = ((ProxyMethodInvocation) invocation).invocableClone(); } - catch (Throwable e) { - if (e instanceof Exception) { - throw (Exception) e; - } - else { - throw new RepeatOperationsInterceptorException("Unexpected error in batch interceptor", e); - } + else { + throw new IllegalStateException( + "MethodInvocation of the wrong type detected - this should not happen with Spring AOP, so please raise an issue if you see this exception"); + } + + Object value = clone.proceed(); + if (voidReturnType) { + return RepeatStatus.CONTINUABLE; + } + if (!isComplete(value)) { + // Save the last result + result.setValue(value); + return RepeatStatus.CONTINUABLE; + } + else { + result.setFinalValue(value); + return RepeatStatus.FINISHED; + } + } + catch (Throwable e) { + if (e instanceof Exception) { + throw (Exception) e; + } + else { + throw new RepeatOperationsInterceptorException("Unexpected error in batch interceptor", e); } } - }); } catch (Throwable t) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/AnnotationMethodResolver.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/AnnotationMethodResolver.java index 819ca280e..a26abcb8b 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/AnnotationMethodResolver.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/AnnotationMethodResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2023 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. @@ -34,6 +34,7 @@ import org.springframework.util.ReflectionUtils; * Class that contains the specified annotation type. * * @author Mark Fisher + * @author Mahmoud Ben Hassine */ public class AnnotationMethodResolver implements MethodResolver { @@ -85,15 +86,12 @@ public class AnnotationMethodResolver implements MethodResolver { public Method findMethod(final Class clazz) { Assert.notNull(clazz, "class must not be null"); final AtomicReference annotatedMethod = new AtomicReference<>(); - ReflectionUtils.doWithMethods(clazz, 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 [" + clazz - + "] with the annotation type [" + annotationType + "]"); - annotatedMethod.set(method); - } + ReflectionUtils.doWithMethods(clazz, method -> { + Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType); + if (annotation != null) { + Assert.isNull(annotatedMethod.get(), "found more than one method on target class [" + clazz + + "] with the annotation type [" + annotationType + "]"); + annotatedMethod.set(method); } }); return annotatedMethod.get(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/CompositeKeyFooDao.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/CompositeKeyFooDao.java index 90be8d34a..c0d8b4005 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/CompositeKeyFooDao.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/CompositeKeyFooDao.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Map; import org.springframework.batch.item.sample.Foo; @@ -47,15 +45,12 @@ public class CompositeKeyFooDao extends JdbcDaoSupport implements FooDao { Map keys = (Map) key; Object[] args = keys.values().toArray(); - RowMapper fooMapper = new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int rowNum) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + RowMapper fooMapper = (rs, rowNum) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }; return getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ? and VALUE = ?", fooMapper, args) diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java index 5ac931037..e4407c5bc 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2022 the original author or authors. + * Copyright 2009-2023 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. @@ -41,7 +41,6 @@ import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.SmartDataSource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -191,35 +190,23 @@ class ExtendedConnectionDataSourceProxyTests { Connection connection = DataSourceUtils.getConnection(csds); csds.startCloseSuppression(connection); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - template.queryForList("select baz from bar"); - template.queryForList("select foo from bar"); - return null; - } + tt.execute((TransactionCallback) status -> { + template.queryForList("select baz from bar"); + template.queryForList("select foo from bar"); + return null; }); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - template.queryForList("select ham from foo"); - tt2.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - template.queryForList("select 1 from eggs"); - return null; - } - }); - template.queryForList("select more, ham from foo"); + tt.execute((TransactionCallback) status -> { + template.queryForList("select ham from foo"); + tt2.execute((TransactionCallback) status1 -> { + template.queryForList("select 1 from eggs"); return null; - } + }); + template.queryForList("select more, ham from foo"); + return null; }); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - template.queryForList("select spam from ham"); - return null; - } + tt.execute((TransactionCallback) status -> { + template.queryForList("select spam from ham"); + return null; }); csds.stopCloseSuppression(connection); DataSourceUtils.releaseConnection(connection, csds); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java index 9a40e785f..a9b49f588 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java @@ -70,12 +70,7 @@ class JdbcBatchItemWriterClassicTests { }; writer.setSql("SQL"); writer.setJdbcTemplate(new NamedParameterJdbcTemplate(jdbcTemplate)); - writer.setItemPreparedStatementSetter(new ItemPreparedStatementSetter<>() { - @Override - public void setValues(String item, PreparedStatement ps) throws SQLException { - list.add(item); - } - }); + writer.setItemPreparedStatementSetter((item, ps) -> list.add(item)); writer.afterPropertiesSet(); } @@ -128,24 +123,16 @@ class JdbcBatchItemWriterClassicTests { @Test void testWriteAndFlushWithFailure() throws Exception { final RuntimeException ex = new RuntimeException("bar"); - writer.setItemPreparedStatementSetter(new ItemPreparedStatementSetter<>() { - @Override - public void setValues(String item, PreparedStatement ps) throws SQLException { - list.add(item); - throw ex; - } + writer.setItemPreparedStatementSetter((item, ps) -> { + list.add(item); + throw ex; }); ps.addBatch(); when(ps.executeBatch()).thenReturn(new int[] { 123 }); Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of("foo"))); assertEquals("bar", exception.getMessage()); assertEquals(2, list.size()); - writer.setItemPreparedStatementSetter(new ItemPreparedStatementSetter<>() { - @Override - public void setValues(String item, PreparedStatement ps) throws SQLException { - list.add(item); - } - }); + writer.setItemPreparedStatementSetter((item, ps) -> list.add(item)); writer.write(Chunk.of("foo")); assertEquals(4, list.size()); assertTrue(list.contains("SQL")); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java index ff8930082..ddcbf400f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java @@ -148,12 +148,7 @@ public class JdbcBatchItemWriterNamedParameterTests { mapWriter.setSql(sql); mapWriter.setJdbcTemplate(namedParameterJdbcOperations); - mapWriter.setItemSqlParameterSourceProvider(new ItemSqlParameterSourceProvider<>() { - @Override - public SqlParameterSource createSqlParameterSource(Map item) { - return new MapSqlParameterSource(item); - } - }); + mapWriter.setItemSqlParameterSourceProvider(item -> new MapSqlParameterSource(item)); mapWriter.afterPropertiesSet(); ArgumentCaptor captor = ArgumentCaptor.forClass(SqlParameterSource[].class); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcCursorItemReaderConfigTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcCursorItemReaderConfigTests.java index 12e4ee9b2..978ff3534 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcCursorItemReaderConfigTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcCursorItemReaderConfigTests.java @@ -25,7 +25,6 @@ import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.jdbc.support.JdbcTransactionManager; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -59,13 +58,10 @@ class JdbcCursorItemReaderConfigTests { reader.setUseSharedExtendedConnection(true); reader.setSql("select foo from bar"); final ExecutionContext ec = new ExecutionContext(); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - reader.open(ec); - reader.close(); - return null; - } + tt.execute((TransactionCallback) status -> { + reader.open(ec); + reader.close(); + return null; }); } @@ -90,13 +86,10 @@ class JdbcCursorItemReaderConfigTests { reader.setDataSource(ds); reader.setSql("select foo from bar"); final ExecutionContext ec = new ExecutionContext(); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - reader.open(ec); - reader.close(); - return null; - } + tt.execute((TransactionCallback) status -> { + reader.open(ec); + reader.close(); + return null; }); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderAsyncTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderAsyncTests.java index b13865d79..26aeb6592 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderAsyncTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderAsyncTests.java @@ -18,15 +18,12 @@ package org.springframework.batch.item.database; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; @@ -45,7 +42,6 @@ import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; @@ -119,22 +115,19 @@ class JdbcPagingItemReaderAsyncTests { CompletionService> completionService = new ExecutorCompletionService<>( Executors.newFixedThreadPool(THREAD_COUNT)); for (int i = 0; i < THREAD_COUNT; i++) { - completionService.submit(new Callable<>() { - @Override - public List call() throws Exception { - List list = new ArrayList<>(); - Foo next = null; - do { - next = reader.read(); - Thread.sleep(10L); - logger.debug("Reading item: " + next); - if (next != null) { - list.add(next); - } + completionService.submit(() -> { + List list = new ArrayList<>(); + Foo next = null; + do { + next = reader.read(); + Thread.sleep(10L); + logger.debug("Reading item: " + next); + if (next != null) { + list.add(next); } - while (next != null); - return list; } + while (next != null); + return list; }); } int count = 0; @@ -162,15 +155,12 @@ class JdbcPagingItemReaderAsyncTests { sortKeys.put("ID", Order.ASCENDING); queryProvider.setSortKeys(sortKeys); reader.setQueryProvider(queryProvider); - reader.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + reader.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); reader.setPageSize(PAGE_SIZE); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderClassicParameterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderClassicParameterTests.java index 2ebe7c224..053b42d1b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderClassicParameterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderClassicParameterTests.java @@ -15,15 +15,12 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; -import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** @@ -50,15 +47,12 @@ class JdbcPagingItemReaderClassicParameterTests extends AbstractJdbcPagingItemRe queryProvider.setSortKeys(sortKeys); reader.setParameterValues(Collections.singletonMap("limit", 2)); reader.setQueryProvider(queryProvider); - reader.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + reader.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); reader.setPageSize(3); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderCommonTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderCommonTests.java index 7669aed0b..c80cfc9c9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderCommonTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderCommonTests.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; @@ -28,7 +26,6 @@ import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** @@ -55,15 +52,12 @@ public class JdbcPagingItemReaderCommonTests extends AbstractItemStreamItemReade sortKeys.put("ID", Order.ASCENDING); queryProvider.setSortKeys(sortKeys); reader.setQueryProvider(queryProvider); - reader.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + reader.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); reader.setPageSize(3); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderIntegrationTests.java index 61959e46e..aa3c0f52f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderIntegrationTests.java @@ -15,15 +15,12 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; -import org.springframework.jdbc.core.RowMapper; /** * Tests for {@link JpaPagingItemReader}. @@ -46,15 +43,12 @@ public class JdbcPagingItemReaderIntegrationTests extends AbstractGenericDataSou sortKeys.put("ID", Order.ASCENDING); queryProvider.setSortKeys(sortKeys); inputSource.setQueryProvider(queryProvider); - inputSource.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + inputSource.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); inputSource.setPageSize(3); inputSource.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderNamedParameterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderNamedParameterTests.java index ddcab7383..2a9a1debe 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderNamedParameterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderNamedParameterTests.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -25,7 +23,6 @@ import org.junit.jupiter.api.Disabled; import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; -import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** @@ -55,15 +52,12 @@ class JdbcPagingItemReaderNamedParameterTests extends AbstractJdbcPagingItemRead queryProvider.setSortKeys(sortKeys); reader.setParameterValues(Collections.singletonMap("limit", 2)); reader.setQueryProvider(queryProvider); - reader.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + reader.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); reader.setPageSize(3); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderOrderIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderOrderIntegrationTests.java index 32e8f6d08..027e5b604 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderOrderIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingItemReaderOrderIntegrationTests.java @@ -15,15 +15,12 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.database.support.HsqlPagingQueryProvider; import org.springframework.batch.item.sample.Foo; -import org.springframework.jdbc.core.RowMapper; /** * Tests for {@link JpaPagingItemReader} with sort key not equal to ID. @@ -47,15 +44,12 @@ public class JdbcPagingItemReaderOrderIntegrationTests extends AbstractGenericDa sortKeys.put("NAME", Order.DESCENDING); queryProvider.setSortKeys(sortKeys); inputSource.setQueryProvider(queryProvider); - inputSource.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + inputSource.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); inputSource.setPageSize(3); inputSource.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingRestartIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingRestartIntegrationTests.java index d974ad67c..1823e456c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingRestartIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcPagingRestartIntegrationTests.java @@ -20,8 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -42,7 +40,6 @@ import org.springframework.batch.item.database.support.SqlPagingQueryProviderFac import org.springframework.batch.item.sample.Foo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; @@ -157,15 +154,12 @@ class JdbcPagingRestartIntegrationTests { sortKeys.put("VALUE", Order.ASCENDING); factory.setSortKeys(sortKeys); reader.setQueryProvider(factory.getObject()); - reader.setRowMapper(new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int i) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + reader.setRowMapper((rs, i) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }); reader.setPageSize(pageSize); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaPagingItemReaderAsyncTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaPagingItemReaderAsyncTests.java index ddbf53d77..fd91b44cd 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaPagingItemReaderAsyncTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaPagingItemReaderAsyncTests.java @@ -22,7 +22,6 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; @@ -110,22 +109,19 @@ class JpaPagingItemReaderAsyncTests { CompletionService> completionService = new ExecutorCompletionService<>( Executors.newFixedThreadPool(THREAD_COUNT)); for (int i = 0; i < THREAD_COUNT; i++) { - completionService.submit(new Callable<>() { - @Override - public List call() throws Exception { - List list = new ArrayList<>(); - Foo next = null; - do { - next = reader.read(); - Thread.sleep(10L); - logger.debug("Reading item: " + next); - if (next != null) { - list.add(next); - } + completionService.submit(() -> { + List list = new ArrayList<>(); + Foo next = null; + do { + next = reader.read(); + Thread.sleep(10L); + logger.debug("Reading item: " + next); + if (next != null) { + list.add(next); } - while (next != null); - return list; } + while (next != null); + return list; }); } int count = 0; diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/SingleKeyFooDao.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/SingleKeyFooDao.java index 53c3441da..7e7b81f45 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/SingleKeyFooDao.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/SingleKeyFooDao.java @@ -15,9 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.ResultSet; -import java.sql.SQLException; - import org.springframework.batch.item.sample.Foo; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; @@ -27,15 +24,12 @@ public class SingleKeyFooDao extends JdbcDaoSupport implements FooDao { @Override public Foo getFoo(Object key) { - RowMapper fooMapper = new RowMapper<>() { - @Override - public Foo mapRow(ResultSet rs, int rowNum) throws SQLException { - Foo foo = new Foo(); - foo.setId(rs.getInt(1)); - foo.setName(rs.getString(2)); - foo.setValue(rs.getInt(3)); - return foo; - } + RowMapper fooMapper = (rs, rowNum) -> { + Foo foo = new Foo(); + foo.setId(rs.getInt(1)); + foo.setName(rs.getString(2)); + foo.setValue(rs.getInt(3)); + return foo; }; return getJdbcTemplate().query("SELECT ID, NAME, VALUE from T_FOOS where ID = ?", fooMapper, key).get(0); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredProcedureItemReaderCommonTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredProcedureItemReaderCommonTests.java index f9f85fd78..a5b7190c4 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredProcedureItemReaderCommonTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredProcedureItemReaderCommonTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2022 the original author or authors. + * Copyright 2010-2023 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. @@ -15,9 +15,6 @@ */ package org.springframework.batch.item.database; -import java.sql.PreparedStatement; -import java.sql.SQLException; - import org.hsqldb.types.Types; import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; @@ -25,7 +22,6 @@ import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ReaderNotOpenException; import org.springframework.batch.item.sample.Foo; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.SqlParameter; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -68,12 +64,9 @@ class StoredProcedureItemReaderCommonTests extends AbstractDatabaseItemStreamIte reader.setProcedureName("read_some_foos"); reader.setParameters(new SqlParameter[] { new SqlParameter("from_id", Types.NUMERIC), new SqlParameter("to_id", Types.NUMERIC) }); - reader.setPreparedStatementSetter(new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, 1000); - ps.setInt(2, 1001); - } + reader.setPreparedStatementSetter(ps -> { + ps.setInt(1, 1000); + ps.setInt(2, 1001); }); reader.setRowMapper(new FooRowMapper()); reader.setVerifyCursorPosition(false); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredprocedureItemReaderConfigTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredprocedureItemReaderConfigTests.java index defcc7c5a..50a02a9c0 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredprocedureItemReaderConfigTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/StoredprocedureItemReaderConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2022 the original author or authors. + * Copyright 2010-2023 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. @@ -21,20 +21,16 @@ import static org.mockito.Mockito.when; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import javax.sql.DataSource; import org.hsqldb.types.Types; import org.junit.jupiter.api.Test; import org.springframework.batch.item.ExecutionContext; -import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.support.JdbcTransactionManager; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -66,13 +62,10 @@ class StoredprocedureItemReaderConfigTests { reader.setUseSharedExtendedConnection(true); reader.setProcedureName("foo_bar"); final ExecutionContext ec = new ExecutionContext(); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - reader.open(ec); - reader.close(); - return null; - } + tt.execute((TransactionCallback) status -> { + reader.open(ec); + reader.close(); + return null; }); } @@ -101,13 +94,10 @@ class StoredprocedureItemReaderConfigTests { reader.setDataSource(ds); reader.setProcedureName("foo_bar"); final ExecutionContext ec = new ExecutionContext(); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - reader.open(ec); - reader.close(); - return null; - } + tt.execute((TransactionCallback) status -> { + reader.open(ec); + reader.close(); + return null; }); } @@ -137,20 +127,14 @@ class StoredprocedureItemReaderConfigTests { reader.setProcedureName("foo_bar"); reader.setParameters( new SqlParameter[] { new SqlParameter("foo", Types.VARCHAR), new SqlParameter("bar", Types.OTHER) }); - reader.setPreparedStatementSetter(new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - } + reader.setPreparedStatementSetter(ps -> { }); reader.setRefCursorPosition(3); final ExecutionContext ec = new ExecutionContext(); - tt.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - reader.open(ec); - reader.close(); - return null; - } + tt.execute((TransactionCallback) status -> { + reader.open(ec); + reader.close(); + return null; }); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcCursorItemReaderBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcCursorItemReaderBuilderTests.java index b742b848f..c8b2528e1 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcCursorItemReaderBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcCursorItemReaderBuilderTests.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.database.builder; -import java.sql.PreparedStatement; -import java.sql.SQLException; import java.sql.Types; import java.util.Arrays; import javax.sql.DataSource; @@ -33,7 +31,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; -import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; @@ -49,6 +46,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Drummond Dawson * @author Ankur Trapasiya * @author Parikshit Dutta + * @author Mahmoud Ben Hassine */ class JdbcCursorItemReaderBuilderTests { @@ -207,12 +205,7 @@ class JdbcCursorItemReaderBuilderTests { JdbcCursorItemReader reader = new JdbcCursorItemReaderBuilder().dataSource(this.dataSource) .name("fooReader") .sql("SELECT * FROM FOO WHERE FIRST > ? ORDER BY FIRST") - .preparedStatementSetter(new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, 3); - } - }) + .preparedStatementSetter(ps -> ps.setInt(1, 3)) .rowMapper((rs, rowNum) -> { Foo foo = new Foo(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderCommonTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderCommonTests.java index aee4d125f..1990a6afe 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderCommonTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderCommonTests.java @@ -34,13 +34,10 @@ public class FlatFileItemReaderCommonTests extends AbstractItemStreamItemReaderT FlatFileItemReader tested = new FlatFileItemReader<>(); Resource resource = new ByteArrayResource(FOOS.getBytes()); tested.setResource(resource); - tested.setLineMapper(new LineMapper<>() { - @Override - public Foo mapLine(String line, int lineNumber) { - Foo foo = new Foo(); - foo.setValue(Integer.parseInt(line.trim())); - return foo; - } + tested.setLineMapper((line, lineNumber) -> { + Foo foo = new Foo(); + foo.setValue(Integer.parseInt(line.trim())); + return foo; }); tested.setSaveState(true); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderTests.java index 48cc7ece2..daacb784b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemReaderTests.java @@ -440,14 +440,11 @@ class FlatFileItemReaderTests { */ @Test void testMappingExceptionWrapping() throws Exception { - LineMapper exceptionLineMapper = new LineMapper<>() { - @Override - public String mapLine(String line, int lineNumber) throws Exception { - if (lineNumber == 2) { - throw new Exception("Couldn't map line 2"); - } - return line; + LineMapper exceptionLineMapper = (line, lineNumber) -> { + if (lineNumber == 2) { + throw new Exception("Couldn't map line 2"); } + return line; }; reader.setLineMapper(exceptionLineMapper); reader.afterPropertiesSet(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java index 51e0957ef..361b6b2c9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.io.Writer; import java.nio.charset.UnsupportedCharsetException; import org.junit.jupiter.api.AfterEach; @@ -32,13 +31,11 @@ import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.UnexpectedInputException; -import org.springframework.batch.item.file.transform.LineAggregator; import org.springframework.batch.item.file.transform.PassThroughLineAggregator; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.WritableResource; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.ClassUtils; @@ -244,12 +241,7 @@ class FlatFileItemWriterTests { */ @Test void testWriteWithConverter() throws Exception { - writer.setLineAggregator(new LineAggregator<>() { - @Override - public String aggregate(String item) { - return "FOO:" + item; - } - }); + writer.setLineAggregator(item -> "FOO:" + item); String data = "string"; writer.open(executionContext); writer.write(Chunk.of(data)); @@ -264,12 +256,7 @@ class FlatFileItemWriterTests { */ @Test void testWriteWithConverterAndString() throws Exception { - writer.setLineAggregator(new LineAggregator<>() { - @Override - public String aggregate(String item) { - return "FOO:" + item; - } - }); + writer.setLineAggregator(item -> "FOO:" + item); writer.open(executionContext); writer.write(Chunk.of(TEST_STRING)); String lineFromFile = readLine(); @@ -300,14 +287,7 @@ class FlatFileItemWriterTests { @Test void testRestart() throws Exception { - writer.setFooterCallback(new FlatFileFooterCallback() { - - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("footer"); - } - - }); + writer.setFooterCallback(writer -> writer.write("footer")); writer.open(executionContext); // write some lines @@ -356,19 +336,16 @@ class FlatFileItemWriterTests { PlatformTransactionManager transactionManager = new ResourcelessTransactionManager(); writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(Chunk.of(TEST_STRING)); - assertEquals(expectedInTransaction, readLine()); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(Chunk.of(TEST_STRING)); + assertEquals(expectedInTransaction, readLine()); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + + return null; }); writer.close(); } @@ -376,35 +353,25 @@ class FlatFileItemWriterTests { @Test void testTransactionalRestart() throws Exception { - writer.setFooterCallback(new FlatFileFooterCallback() { - - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("footer"); - } - - }); + writer.setFooterCallback(writer -> writer.write("footer")); writer.open(executionContext); PlatformTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write some lines - writer.write(Chunk.of(new String[] { "testLine1", "testLine2", "testLine3" })); - // write more lines - writer.write(Chunk.of(new String[] { "testLine4", "testLine5" })); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write some lines + writer.write(Chunk.of(new String[] { "testLine1", "testLine2", "testLine3" })); + // write more lines + writer.write(Chunk.of(new String[] { "testLine4", "testLine5" })); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); // close template writer.close(); @@ -412,20 +379,17 @@ class FlatFileItemWriterTests { // init with correct data writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write more lines - writer.write(Chunk.of(new String[] { "testLine6", "testLine7", "testLine8" })); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write more lines + writer.write(Chunk.of(new String[] { "testLine6", "testLine7", "testLine8" })); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); // close template writer.close(); @@ -456,35 +420,25 @@ class FlatFileItemWriterTests { private void testTransactionalRestartWithMultiByteCharacter(String encoding) throws Exception { writer.setEncoding(encoding); - writer.setFooterCallback(new FlatFileFooterCallback() { - - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("footer"); - } - - }); + writer.setFooterCallback(writer -> writer.write("footer")); writer.open(executionContext); PlatformTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write some lines - writer.write(Chunk.of(new String[] { "téstLine1", "téstLine2", "téstLine3" })); - // write more lines - writer.write(Chunk.of(new String[] { "téstLine4", "téstLine5" })); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write some lines + writer.write(Chunk.of(new String[] { "téstLine1", "téstLine2", "téstLine3" })); + // write more lines + writer.write(Chunk.of(new String[] { "téstLine4", "téstLine5" })); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); // close template writer.close(); @@ -492,20 +446,17 @@ class FlatFileItemWriterTests { // init with correct data writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write more lines - writer.write(Chunk.of(new String[] { "téstLine6", "téstLine7", "téstLine8" })); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write more lines + writer.write(Chunk.of(new String[] { "téstLine6", "téstLine7", "téstLine8" })); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); // close template writer.close(); @@ -587,14 +538,7 @@ class FlatFileItemWriterTests { @Test void testWriteFooter() throws Exception { - writer.setFooterCallback(new FlatFileFooterCallback() { - - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setFooterCallback(writer -> writer.write("a\nb")); writer.open(executionContext); writer.write(Chunk.of(TEST_STRING)); writer.close(); @@ -605,14 +549,7 @@ class FlatFileItemWriterTests { @Test void testWriteHeader() throws Exception { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.open(executionContext); writer.write(Chunk.of(TEST_STRING)); writer.close(); @@ -626,13 +563,7 @@ class FlatFileItemWriterTests { @Test void testWriteWithAppendAfterHeaders() throws Exception { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.setAppendAllowed(true); writer.open(executionContext); writer.write(Chunk.of("test1")); @@ -651,14 +582,7 @@ class FlatFileItemWriterTests { @Test void testWriteHeaderAndDeleteOnExit() { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.setShouldDeleteIfEmpty(true); writer.open(executionContext); assertTrue(outputFile.exists()); @@ -681,14 +605,7 @@ class FlatFileItemWriterTests { @Test void testWriteHeaderAndDeleteOnExitReopen() throws Exception { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.setShouldDeleteIfEmpty(true); writer.open(executionContext); writer.update(executionContext); @@ -718,14 +635,7 @@ class FlatFileItemWriterTests { @Test void testWriteHeaderAfterRestartOnFirstChunk() throws Exception { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.open(executionContext); writer.write(Chunk.of(TEST_STRING)); writer.close(); @@ -744,14 +654,7 @@ class FlatFileItemWriterTests { @Test void testWriteHeaderAfterRestartOnSecondChunk() throws Exception { - writer.setHeaderCallback(new FlatFileHeaderCallback() { - - @Override - public void writeHeader(Writer writer) throws IOException { - writer.write("a\nb"); - } - - }); + writer.setHeaderCallback(writer -> writer.write("a\nb")); writer.open(executionContext); writer.write(Chunk.of(TEST_STRING)); writer.update(executionContext); @@ -783,15 +686,11 @@ class FlatFileItemWriterTests { */ void testLineAggregatorFailure() throws Exception { - writer.setLineAggregator(new LineAggregator<>() { - - @Override - public String aggregate(String item) { - if (item.equals("2")) { - throw new RuntimeException("aggregation failed on " + item); - } - return item; + writer.setLineAggregator(item -> { + if (item.equals("2")) { + throw new RuntimeException("aggregation failed on " + item); } + return item; }); Chunk items = Chunk.of("1", "2", "3"); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderFlatFileTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderFlatFileTests.java index 7677a35fd..3b8abaa79 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderFlatFileTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderFlatFileTests.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.file; -import java.util.Comparator; - import org.springframework.batch.item.AbstractItemStreamItemReaderTests; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemReader; @@ -32,15 +30,10 @@ class MultiResourceItemReaderFlatFileTests extends AbstractItemStreamItemReaderT MultiResourceItemReader multiReader = new MultiResourceItemReader<>(); FlatFileItemReader fileReader = new FlatFileItemReader<>(); - fileReader.setLineMapper(new LineMapper<>() { - - @Override - public Foo mapLine(String line, int lineNumber) throws Exception { - Foo foo = new Foo(); - foo.setValue(Integer.parseInt(line)); - return foo; - } - + fileReader.setLineMapper((line, lineNumber) -> { + Foo foo = new Foo(); + foo.setValue(Integer.parseInt(line)); + return foo; }); fileReader.setSaveState(true); @@ -53,12 +46,8 @@ class MultiResourceItemReaderFlatFileTests extends AbstractItemStreamItemReaderT multiReader.setResources(new Resource[] { r1, r2, r3, r4 }); multiReader.setSaveState(true); - multiReader.setComparator(new Comparator<>() { - @Override - public int compare(Resource arg0, Resource arg1) { - return 0; // preserve original ordering - } - + multiReader.setComparator((arg0, arg1) -> { + return 0; // preserve original ordering }); return multiReader; diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderIntegrationTests.java index 24c236f14..80a6a5b32 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderIntegrationTests.java @@ -68,11 +68,8 @@ class MultiResourceItemReaderIntegrationTests { itemReader.setLineMapper(new PassThroughLineMapper()); tested.setDelegate(itemReader); - tested.setComparator(new Comparator<>() { - @Override - public int compare(Resource o1, Resource o2) { - return 0; // do not change ordering - } + tested.setComparator((o1, o2) -> { + return 0; // do not change ordering }); tested.setResources(new Resource[] { r1, r2, r3, r4, r5 }); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderResourceAwareTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderResourceAwareTests.java index 0841fc4a1..368c1f825 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderResourceAwareTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderResourceAwareTests.java @@ -21,7 +21,6 @@ import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ResourceAware; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; -import java.util.Comparator; import static org.junit.jupiter.api.Assertions.*; @@ -58,11 +57,8 @@ class MultiResourceItemReaderResourceAwareTests { itemReader.setLineMapper(new FooLineMapper()); tested.setDelegate(itemReader); - tested.setComparator(new Comparator<>() { - @Override - public int compare(Resource o1, Resource o2) { - return 0; // do not change ordering - } + tested.setComparator((o1, o2) -> { + return 0; // do not change ordering }); tested.setResources(new Resource[] { r1, r2, r3, r4, r5 }); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderXmlTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderXmlTests.java index 230f7efc0..9641d83e6 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderXmlTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemReaderXmlTests.java @@ -18,7 +18,6 @@ package org.springframework.batch.item.file; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; -import java.util.Comparator; import javax.xml.stream.XMLEventReader; import javax.xml.stream.events.Attribute; @@ -81,11 +80,8 @@ class MultiResourceItemReaderXmlTests extends AbstractItemStreamItemReaderTests multiReader.setDelegate(reader); multiReader.setResources(new Resource[] { r1, r2, r3, r4 }); multiReader.setSaveState(true); - multiReader.setComparator(new Comparator<>() { - @Override - public int compare(Resource arg0, Resource arg1) { - return 0; // preserve original ordering - } + multiReader.setComparator((arg0, arg1) -> { + return 0; // preserve original ordering }); return multiReader; diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java index b8bbcb176..6c4b056a9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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. @@ -16,8 +16,6 @@ package org.springframework.batch.item.file; import java.io.File; -import java.io.IOException; -import java.io.Writer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -117,12 +115,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI @Test void testMultiResourceWriteScenarioWithFooter() throws Exception { - delegate.setFooterCallback(new FlatFileFooterCallback() { - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("f"); - } - }); + delegate.setFooterCallback(writer -> writer.write("f")); super.setUp(delegate); tested.open(executionContext); @@ -145,12 +138,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI @Test void testTransactionalMultiResourceWriteScenarioWithFooter() throws Exception { - delegate.setFooterCallback(new FlatFileFooterCallback() { - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("f"); - } - }); + delegate.setFooterCallback(writer -> writer.write("f")); super.setUp(delegate); tested.open(executionContext); @@ -206,12 +194,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI @Test void testRestartWithFooter() throws Exception { - delegate.setFooterCallback(new FlatFileFooterCallback() { - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("f"); - } - }); + delegate.setFooterCallback(writer -> writer.write("f")); super.setUp(delegate); tested.open(executionContext); @@ -244,12 +227,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI @Test void testTransactionalRestartWithFooter() throws Exception { - delegate.setFooterCallback(new FlatFileFooterCallback() { - @Override - public void writeFooter(Writer writer) throws IOException { - writer.write("f"); - } - }); + delegate.setFooterCallback(writer -> writer.write("f")); super.setUp(delegate); tested.open(executionContext); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java index 882013557..6eb75b9ed 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2022 the original author or authors. + * Copyright 2017-2023 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. @@ -48,12 +48,7 @@ class MultiResourceItemWriterBuilderTests { private File file; - private final ResourceSuffixCreator suffixCreator = new ResourceSuffixCreator() { - @Override - public String getSuffix(int index) { - return "A" + index; - } - }; + private final ResourceSuffixCreator suffixCreator = index -> "A" + index; private final ExecutionContext executionContext = new ExecutionContext(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapperConcurrentTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapperConcurrentTests.java index 774a75400..2b32e6627 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapperConcurrentTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapperConcurrentTests.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -44,15 +43,12 @@ class BeanWrapperFieldSetMapperConcurrentTests { ExecutorService executorService = Executors.newFixedThreadPool(5); Collection> results = new ArrayList<>(); for (int i = 0; i < 10; i++) { - Future result = executorService.submit(new Callable<>() { - @Override - public Boolean call() throws Exception { - for (int i = 0; i < 10; i++) { - GreenBean bean = mapper.mapFieldSet(lineTokenizer.tokenize("blue,green")); - assertEquals("green", bean.getGreen()); - } - return true; + Future result = executorService.submit(() -> { + for (int i1 = 0; i1 < 10; i1++) { + GreenBean bean = mapper.mapFieldSet(lineTokenizer.tokenize("blue,green")); + assertEquals("green", bean.getGreen()); } + return true; }); results.add(result); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapperTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapperTests.java index 3110f3f07..734171b4c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapperTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/mapping/PatternMatchingCompositeLineMapperTests.java @@ -26,10 +26,8 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.batch.item.file.transform.DefaultFieldSet; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; -import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.batch.item.file.transform.LineTokenizer; import org.springframework.batch.item.file.transform.Name; -import org.springframework.lang.Nullable; /** * @author Dan Garrette @@ -51,33 +49,13 @@ class PatternMatchingCompositeLineMapperTests { @Test void testKeyFound() throws Exception { Map tokenizers = new HashMap<>(); - tokenizers.put("foo*", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return new DefaultFieldSet(new String[] { "a", "b" }); - } - }); - tokenizers.put("bar*", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return new DefaultFieldSet(new String[] { "c", "d" }); - } - }); + tokenizers.put("foo*", line -> new DefaultFieldSet(new String[] { "a", "b" })); + tokenizers.put("bar*", line -> new DefaultFieldSet(new String[] { "c", "d" })); mapper.setTokenizers(tokenizers); Map> fieldSetMappers = new HashMap<>(); - fieldSetMappers.put("foo*", new FieldSetMapper<>() { - @Override - public Name mapFieldSet(FieldSet fs) { - return new Name(fs.readString(0), fs.readString(1), 0); - } - }); - fieldSetMappers.put("bar*", new FieldSetMapper<>() { - @Override - public Name mapFieldSet(FieldSet fs) { - return new Name(fs.readString(1), fs.readString(0), 0); - } - }); + fieldSetMappers.put("foo*", fs -> new Name(fs.readString(0), fs.readString(1), 0)); + fieldSetMappers.put("bar*", fs -> new Name(fs.readString(1), fs.readString(0), 0)); mapper.setFieldSetMappers(fieldSetMappers); Name name = mapper.mapLine("bar", 1); @@ -87,27 +65,12 @@ class PatternMatchingCompositeLineMapperTests { @Test void testMapperKeyNotFound() { Map tokenizers = new HashMap<>(); - tokenizers.put("foo*", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return new DefaultFieldSet(new String[] { "a", "b" }); - } - }); - tokenizers.put("bar*", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return new DefaultFieldSet(new String[] { "c", "d" }); - } - }); + tokenizers.put("foo*", line -> new DefaultFieldSet(new String[] { "a", "b" })); + tokenizers.put("bar*", line -> new DefaultFieldSet(new String[] { "c", "d" })); mapper.setTokenizers(tokenizers); Map> fieldSetMappers = new HashMap<>(); - fieldSetMappers.put("foo*", new FieldSetMapper<>() { - @Override - public Name mapFieldSet(FieldSet fs) { - return new Name(fs.readString(0), fs.readString(1), 0); - } - }); + fieldSetMappers.put("foo*", fs -> new Name(fs.readString(0), fs.readString(1), 0)); mapper.setFieldSetMappers(fieldSetMappers); assertThrows(IllegalStateException.class, () -> mapper.mapLine("bar", 1)); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/FormatterLineAggregatorTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/FormatterLineAggregatorTests.java index c0cec91ad..1eb719d6f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/FormatterLineAggregatorTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/FormatterLineAggregatorTests.java @@ -33,12 +33,7 @@ class FormatterLineAggregatorTests { // object under test private FormatterLineAggregator aggregator; - private final FieldExtractor defaultFieldExtractor = new FieldExtractor<>() { - @Override - public Object[] extract(String[] item) { - return item; - } - }; + private final FieldExtractor defaultFieldExtractor = item -> item; @BeforeEach void setup() { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/PatternMatchingCompositeLineTokenizerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/PatternMatchingCompositeLineTokenizerTests.java index 4a5e3159c..6002782b0 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/PatternMatchingCompositeLineTokenizerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/PatternMatchingCompositeLineTokenizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -25,7 +25,6 @@ import java.util.LinkedHashMap; import java.util.Map; import org.junit.jupiter.api.Test; -import org.springframework.lang.Nullable; /** * @author Ben Hale @@ -45,12 +44,7 @@ class PatternMatchingCompositeLineTokenizerTests { void testEmptyKeyMatchesAnyLine() throws Exception { Map map = new HashMap<>(); map.put("*", new DelimitedLineTokenizer()); - map.put("foo", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return null; - } - }); + map.put("foo", line -> null); tokenizer.setTokenizers(map); tokenizer.afterPropertiesSet(); FieldSet fields = tokenizer.tokenize("abc"); @@ -61,12 +55,7 @@ class PatternMatchingCompositeLineTokenizerTests { void testEmptyKeyDoesNotMatchWhenAlternativeAvailable() throws Exception { Map map = new LinkedHashMap<>(); - map.put("*", new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return null; - } - }); + map.put("*", line -> null); map.put("foo*", new DelimitedLineTokenizer()); tokenizer.setTokenizers(map); tokenizer.afterPropertiesSet(); @@ -83,12 +72,8 @@ class PatternMatchingCompositeLineTokenizerTests { @Test void testMatchWithPrefix() throws Exception { - tokenizer.setTokenizers(Collections.singletonMap("foo*", (LineTokenizer) new LineTokenizer() { - @Override - public FieldSet tokenize(@Nullable String line) { - return new DefaultFieldSet(new String[] { line }); - } - })); + tokenizer.setTokenizers( + Collections.singletonMap("foo*", (LineTokenizer) line -> new DefaultFieldSet(new String[] { line }))); tokenizer.afterPropertiesSet(); FieldSet fields = tokenizer.tokenize("foo bar"); assertEquals(1, fields.getFieldCount()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/RecursiveCollectionItemTransformerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/RecursiveCollectionItemTransformerTests.java index a9d8e099f..4e0048ce3 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/RecursiveCollectionItemTransformerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/transform/RecursiveCollectionItemTransformerTests.java @@ -36,12 +36,7 @@ class RecursiveCollectionItemTransformerTests { @Test void testSetDelegateAndPassInString() { - aggregator.setDelegate(new LineAggregator<>() { - @Override - public String aggregate(String item) { - return "bar"; - } - }); + aggregator.setDelegate(item -> "bar"); assertEquals("bar", aggregator.aggregate(Collections.singleton("foo"))); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java index 1f0713cc7..7d69fc64c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -24,8 +24,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.batch.item.Chunk; -import org.springframework.mail.MailException; -import org.springframework.mail.MailMessage; import org.springframework.mail.MailSendException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; @@ -99,12 +97,7 @@ class SimpleMailMessageItemWriterTests { void testCustomErrorHandler() { final AtomicReference content = new AtomicReference<>(); - writer.setMailErrorHandler(new MailErrorHandler() { - @Override - public void handle(MailMessage message, Exception exception) throws MailException { - content.set(exception.getMessage()); - } - }); + writer.setMailErrorHandler((message, exception) -> content.set(exception.getMessage())); SimpleMailMessage foo = new SimpleMailMessage(); SimpleMailMessage bar = new SimpleMailMessage(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java index 3e3849502..cc30179ab 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2022 the original author or authors. + * Copyright 2017-2023 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. @@ -25,10 +25,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.batch.item.Chunk; -import org.springframework.batch.item.mail.MailErrorHandler; import org.springframework.batch.item.mail.SimpleMailMessageItemWriter; -import org.springframework.mail.MailException; -import org.springframework.mail.MailMessage; import org.springframework.mail.MailSendException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; @@ -92,12 +89,7 @@ class SimpleMailMessageItemWriterBuilderTests { void testCustomErrorHandler() { final AtomicReference content = new AtomicReference<>(); SimpleMailMessageItemWriter writer = new SimpleMailMessageItemWriterBuilder() - .mailErrorHandler(new MailErrorHandler() { - @Override - public void handle(MailMessage message, Exception exception) throws MailException { - content.set(exception.getMessage()); - } - }) + .mailErrorHandler((message, exception) -> content.set(exception.getMessage())) .mailSender(this.mailSender) .build(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java index bf72efc8f..573c53177 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -27,9 +27,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.batch.item.Chunk; -import org.springframework.batch.item.mail.MailErrorHandler; -import org.springframework.mail.MailException; -import org.springframework.mail.MailMessage; import org.springframework.mail.MailSendException; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSender; @@ -99,12 +96,7 @@ class MimeMessageItemWriterTests { void testCustomErrorHandler() { final AtomicReference content = new AtomicReference<>(); - writer.setMailErrorHandler(new MailErrorHandler() { - @Override - public void handle(MailMessage message, Exception exception) throws MailException { - content.set(exception.getMessage()); - } - }); + writer.setMailErrorHandler((message, exception) -> content.set(exception.getMessage())); MimeMessage foo = new MimeMessage(session); MimeMessage bar = new MimeMessage(session); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java index 537d3a6d6..f07c62ad9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java @@ -45,18 +45,8 @@ class ClassifierCompositeItemWriterTests { @Test void testWrite() throws Exception { Map> map = new HashMap<>(); - ItemWriter fooWriter = new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - foos.addAll(chunk.getItems()); - } - }; - ItemWriter defaultWriter = new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - defaults.addAll(chunk.getItems()); - } - }; + ItemWriter fooWriter = chunk -> foos.addAll(chunk.getItems()); + ItemWriter defaultWriter = chunk -> defaults.addAll(chunk.getItems()); map.put("foo", fooWriter); map.put("*", defaultWriter); writer.setClassifier(new PatternMatchingClassifier(map)); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java index 08c323dd1..b6ab6eb30 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java @@ -43,18 +43,8 @@ class ClassifierCompositeItemWriterBuilderTests { @Test void testWrite() throws Exception { Map> map = new HashMap<>(); - ItemWriter fooWriter = new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - foos.addAll(chunk.getItems()); - } - }; - ItemWriter defaultWriter = new ItemWriter<>() { - @Override - public void write(Chunk chunk) throws Exception { - defaults.addAll(chunk.getItems()); - } - }; + ItemWriter fooWriter = chunk -> foos.addAll(chunk.getItems()); + ItemWriter defaultWriter = chunk -> defaults.addAll(chunk.getItems()); map.put("foo", fooWriter); map.put("*", defaultWriter); ClassifierCompositeItemWriter writer = new ClassifierCompositeItemWriterBuilder() diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java index cfe260cc6..f8fc95ebd 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2022 the original author or authors. + * Copyright 2010-2023 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. @@ -37,7 +37,6 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.WritableResource; import org.springframework.oxm.Marshaller; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.ClassUtils; @@ -71,9 +70,8 @@ abstract class AbstractStaxEventWriterItemWriterTests { StopWatch stopWatch = new StopWatch(getClass().getSimpleName()); stopWatch.start(); for (int i = 0; i < MAX_WRITE; i++) { - new TransactionTemplate(new ResourcelessTransactionManager()).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { + new TransactionTemplate(new ResourcelessTransactionManager()) + .execute((TransactionCallback) status -> { try { writer.write(objects); } @@ -84,8 +82,7 @@ abstract class AbstractStaxEventWriterItemWriterTests { throw new IllegalStateException("Exception encountered on write", e); } return null; - } - }); + }); } writer.close(); stopWatch.stop(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java index d86e3f0ea..cfe385f14 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2022 the original author or authors. + * Copyright 2010-2023 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. @@ -39,7 +39,6 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.WritableResource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.ClassUtils; @@ -75,9 +74,8 @@ class Jaxb2NamespaceMarshallingTests { StopWatch stopWatch = new StopWatch(getClass().getSimpleName()); stopWatch.start(); for (int i = 0; i < MAX_WRITE; i++) { - new TransactionTemplate(new ResourcelessTransactionManager()).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { + new TransactionTemplate(new ResourcelessTransactionManager()) + .execute((TransactionCallback) status -> { try { writer.write(objects); } @@ -88,8 +86,7 @@ class Jaxb2NamespaceMarshallingTests { throw new IllegalStateException("Exception encountered on write", e); } return null; - } - }); + }); } writer.close(); stopWatch.stop(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java index befea018a..caeb995fa 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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. @@ -20,7 +20,6 @@ import java.io.IOException; import java.util.Collections; import javax.xml.stream.XMLEventFactory; -import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.transform.Result; import jakarta.xml.bind.annotation.XmlRootElement; @@ -40,7 +39,6 @@ import org.springframework.oxm.Marshaller; import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.Assert; @@ -224,39 +222,33 @@ class StaxEventItemWriterTests { PlatformTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write item - writer.write(items); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write item + writer.write(items); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); writer.close(); // create new writer from saved restart data and continue writing writer = createItemWriter(); writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(items); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(items); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); writer.close(); @@ -285,20 +277,17 @@ class StaxEventItemWriterTests { PlatformTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - // write item - writer.write(itemsMultiByte); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + // write item + writer.write(itemsMultiByte); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); writer.close(); @@ -306,19 +295,16 @@ class StaxEventItemWriterTests { writer = createItemWriter(); writer.setEncoding(encoding); writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(itemsMultiByte); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(itemsMultiByte); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); writer.close(); @@ -336,17 +322,14 @@ class StaxEventItemWriterTests { writer.open(executionContext); try { - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(items); - } - catch (Exception e) { - throw new IllegalStateException("Could not write data", e); - } - throw new UnexpectedInputException("Could not write data"); + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(items); } + catch (Exception e) { + throw new IllegalStateException("Could not write data", e); + } + throw new UnexpectedInputException("Could not write data"); }); } catch (UnexpectedInputException e) { @@ -358,20 +341,17 @@ class StaxEventItemWriterTests { // create new writer from saved restart data and continue writing writer = createItemWriter(); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - writer.open(executionContext); - try { - writer.write(items); - } - catch (Exception e) { - throw new UnexpectedInputException("Could not write data", e); - } - // get restart data - writer.update(executionContext); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + writer.open(executionContext); + try { + writer.write(items); } + catch (Exception e) { + throw new UnexpectedInputException("Could not write data", e); + } + // get restart data + writer.update(executionContext); + return null; }); writer.close(); @@ -389,19 +369,14 @@ class StaxEventItemWriterTests { @Test void testWriteWithHeader() throws Exception { - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -435,35 +410,25 @@ class StaxEventItemWriterTests { */ @Test void testOpenAndClose() throws Exception { - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); - writer.setFooterCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "footer")); - writer.add(factory.createEndElement("", "", "footer")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setFooterCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "footer")); + writer.add(factory.createEndElement("", "", "footer")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -524,35 +489,25 @@ class StaxEventItemWriterTests { @Test void testDeleteIfEmptyNoRecordsWrittenHeaderAndFooter() throws Exception { writer.setShouldDeleteIfEmpty(true); - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); - writer.setFooterCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "footer")); - writer.add(factory.createEndElement("", "", "footer")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setFooterCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "footer")); + writer.add(factory.createEndElement("", "", "footer")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -608,35 +563,25 @@ class StaxEventItemWriterTests { @Test void testDeleteIfEmptyNoRecordsWrittenHeaderAndFooterRestartAfterDelete() throws Exception { writer.setShouldDeleteIfEmpty(true); - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); - writer.setFooterCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "footer")); - writer.add(factory.createEndElement("", "", "footer")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setFooterCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "footer")); + writer.add(factory.createEndElement("", "", "footer")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -888,32 +833,22 @@ class StaxEventItemWriterTests { private void initWriterForSimpleCallbackTests() throws Exception { writer = createItemWriter(); - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("ns", "https://www.springframework.org/test", "group")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("ns", "https://www.springframework.org/test", "group")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } - }); - writer.setFooterCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createEndElement("ns", "https://www.springframework.org/test", "group")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setFooterCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createEndElement("ns", "https://www.springframework.org/test", "group")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -925,46 +860,36 @@ class StaxEventItemWriterTests { // header- and footer elements private void initWriterForComplexCallbackTests() throws Exception { writer = createItemWriter(); - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "preHeader")); - writer.add(factory.createCharacters("PRE-HEADER")); - writer.add(factory.createEndElement("", "", "preHeader")); - writer.add(factory.createStartElement("ns", "https://www.springframework.org/test", "group")); - writer.add(factory.createStartElement("", "", "subGroup")); - writer.add(factory.createStartElement("", "", "postHeader")); - writer.add(factory.createCharacters("POST-HEADER")); - writer.add(factory.createEndElement("", "", "postHeader")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "preHeader")); + writer.add(factory.createCharacters("PRE-HEADER")); + writer.add(factory.createEndElement("", "", "preHeader")); + writer.add(factory.createStartElement("ns", "https://www.springframework.org/test", "group")); + writer.add(factory.createStartElement("", "", "subGroup")); + writer.add(factory.createStartElement("", "", "postHeader")); + writer.add(factory.createCharacters("POST-HEADER")); + writer.add(factory.createEndElement("", "", "postHeader")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } - }); - writer.setFooterCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "preFooter")); - writer.add(factory.createCharacters("PRE-FOOTER")); - writer.add(factory.createEndElement("", "", "preFooter")); - writer.add(factory.createEndElement("", "", "subGroup")); - writer.add(factory.createEndElement("ns", "https://www.springframework.org/test", "group")); - writer.add(factory.createStartElement("", "", "postFooter")); - writer.add(factory.createCharacters("POST-FOOTER")); - writer.add(factory.createEndElement("", "", "postFooter")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setFooterCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "preFooter")); + writer.add(factory.createCharacters("PRE-FOOTER")); + writer.add(factory.createEndElement("", "", "preFooter")); + writer.add(factory.createEndElement("", "", "subGroup")); + writer.add(factory.createEndElement("ns", "https://www.springframework.org/test", "group")); + writer.add(factory.createStartElement("", "", "postFooter")); + writer.add(factory.createCharacters("POST-FOOTER")); + writer.add(factory.createEndElement("", "", "postFooter")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java index 320c7edcb..230c08460 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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,7 +19,6 @@ import java.io.File; import java.io.IOException; import javax.xml.stream.XMLEventFactory; -import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.transform.Result; @@ -35,7 +34,6 @@ import org.springframework.core.io.WritableResource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.XmlMappingException; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.ClassUtils; @@ -86,17 +84,14 @@ class TransactionalStaxEventItemWriterTests { @Test void testWriteAndFlush() throws Exception { writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(items); - } - catch (Exception e) { - throw new RuntimeException(e); - } - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(items); } + catch (Exception e) { + throw new RuntimeException(e); + } + return null; }); writer.close(); String content = outputFileContent(); @@ -108,19 +103,14 @@ class TransactionalStaxEventItemWriterTests { */ @Test void testWriteWithHeaderAfterRollback() throws Exception { - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); @@ -137,17 +127,14 @@ class TransactionalStaxEventItemWriterTests { })); writer.close(); writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(items); - } - catch (Exception e) { - throw new RuntimeException(e); - } - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(items); } + catch (Exception e) { + throw new RuntimeException(e); + } + return null; }); writer.close(); String content = outputFileContent(); @@ -160,34 +147,26 @@ class TransactionalStaxEventItemWriterTests { */ @Test void testWriteWithHeaderAfterFlushAndRollback() throws Exception { - writer.setHeaderCallback(new StaxWriterCallback() { - - @Override - public void write(XMLEventWriter writer) throws IOException { - XMLEventFactory factory = XMLEventFactory.newInstance(); - try { - writer.add(factory.createStartElement("", "", "header")); - writer.add(factory.createEndElement("", "", "header")); - } - catch (XMLStreamException e) { - throw new RuntimeException(e); - } - + writer.setHeaderCallback(writer -> { + XMLEventFactory factory = XMLEventFactory.newInstance(); + try { + writer.add(factory.createStartElement("", "", "header")); + writer.add(factory.createEndElement("", "", "header")); + } + catch (XMLStreamException e) { + throw new RuntimeException(e); } }); writer.open(executionContext); - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - try { - writer.write(items); - } - catch (Exception e) { - throw new RuntimeException(e); - } - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + try { + writer.write(items); } + catch (Exception e) { + throw new RuntimeException(e); + } + return null; }); writer.update(executionContext); writer.close(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/poller/DirectPollerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/poller/DirectPollerTests.java index 8433ff5ea..9295e9e53 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/poller/DirectPollerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/poller/DirectPollerTests.java @@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class DirectPollerTests { @@ -38,17 +39,12 @@ class DirectPollerTests { @Test void testSimpleSingleThreaded() throws Exception { - Callable callback = new Callable<>() { - - @Override - public String call() throws Exception { - Set executions = new HashSet<>(repository); - if (executions.isEmpty()) { - return null; - } - return executions.iterator().next(); + Callable callback = () -> { + Set executions = new HashSet<>(repository); + if (executions.isEmpty()) { + return null; } - + return executions.iterator().next(); }; sleepAndCreateStringInBackground(500L); @@ -63,17 +59,12 @@ class DirectPollerTests { @Test void testTimeUnit() throws Exception { - Callable callback = new Callable<>() { - - @Override - public String call() throws Exception { - Set executions = new HashSet<>(repository); - if (executions.isEmpty()) { - return null; - } - return executions.iterator().next(); + Callable callback = () -> { + Set executions = new HashSet<>(repository); + if (executions.isEmpty()) { + return null; } - + return executions.iterator().next(); }; sleepAndCreateStringInBackground(500L); @@ -88,17 +79,12 @@ class DirectPollerTests { @Test void testWithError() { - Callable callback = new Callable<>() { - - @Override - public String call() throws Exception { - Set executions = new HashSet<>(repository); - if (executions.isEmpty()) { - return null; - } - throw new RuntimeException("Expected"); + Callable callback = () -> { + Set executions = new HashSet<>(repository); + if (executions.isEmpty()) { + return null; } - + throw new RuntimeException("Expected"); }; Poller poller = new DirectPoller<>(100L); @@ -111,16 +97,13 @@ class DirectPollerTests { } private void sleepAndCreateStringInBackground(final long duration) { - new Thread(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(duration); - repository.add("foo"); - } - catch (Exception e) { - throw new IllegalStateException("Unexpected"); - } + new Thread(() -> { + try { + Thread.sleep(duration); + repository.add("foo"); + } + catch (Exception e) { + throw new IllegalStateException("Unexpected"); } }).start(); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/callback/NestedRepeatCallbackTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/callback/NestedRepeatCallbackTests.java index 520219cbd..82dbc8af9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/callback/NestedRepeatCallbackTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/callback/NestedRepeatCallbackTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -18,8 +18,6 @@ package org.springframework.batch.repeat.callback; import org.junit.jupiter.api.Test; import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.batch.repeat.RepeatCallback; -import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.support.RepeatTemplate; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -31,12 +29,9 @@ class NestedRepeatCallbackTests { @Test void testExecute() throws Exception { - NestedRepeatCallback callback = new NestedRepeatCallback(new RepeatTemplate(), new RepeatCallback() { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - count++; - return RepeatStatus.continueIf(count <= 1); - } + NestedRepeatCallback callback = new NestedRepeatCallback(new RepeatTemplate(), context -> { + count++; + return RepeatStatus.continueIf(count <= 1); }); RepeatStatus result = callback.doInIteration(null); assertEquals(2, count); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/CompositeExceptionHandlerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/CompositeExceptionHandlerTests.java index d2671bc2f..ebeae2363 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/CompositeExceptionHandlerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/CompositeExceptionHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; -import org.springframework.batch.repeat.RepeatContext; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -37,17 +36,8 @@ class CompositeExceptionHandlerTests { @Test void testDelegation() throws Throwable { final List list = new ArrayList<>(); - handler.setHandlers(new ExceptionHandler[] { new ExceptionHandler() { - @Override - public void handleException(RepeatContext context, Throwable throwable) throws RuntimeException { - list.add("1"); - } - }, new ExceptionHandler() { - @Override - public void handleException(RepeatContext context, Throwable throwable) throws RuntimeException { - list.add("2"); - } - } }); + handler.setHandlers(new ExceptionHandler[] { (context, throwable) -> list.add("1"), + (context, throwable) -> list.add("2") }); handler.handleException(null, new RuntimeException()); assertEquals(2, list.size()); assertEquals("1", list.get(0)); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptorTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptorTests.java index b2121aa38..419553bea 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptorTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptorTests.java @@ -28,7 +28,6 @@ import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; import org.springframework.batch.repeat.RepeatStatus; -import org.springframework.batch.repeat.RepeatCallback; import org.springframework.batch.repeat.RepeatException; import org.springframework.batch.repeat.RepeatOperations; import org.springframework.batch.repeat.policy.SimpleCompletionPolicy; @@ -75,18 +74,15 @@ class RepeatOperationsInterceptorTests { @Test void testSetTemplate() throws Exception { final List calls = new ArrayList<>(); - interceptor.setRepeatOperations(new RepeatOperations() { - @Override - public RepeatStatus iterate(RepeatCallback callback) { - try { - Object result = callback.doInIteration(null); - calls.add(result); - } - catch (Exception e) { - throw new RepeatException("Encountered exception in repeat.", e); - } - return RepeatStatus.CONTINUABLE; + interceptor.setRepeatOperations(callback -> { + try { + Object result = callback.doInIteration(null); + calls.add(result); } + catch (Exception e) { + throw new RepeatException("Encountered exception in repeat.", e); + } + return RepeatStatus.CONTINUABLE; }); ((Advised) service).addAdvice(interceptor); service.service(); @@ -96,12 +92,9 @@ class RepeatOperationsInterceptorTests { @Test void testCallbackNotExecuted() { final List calls = new ArrayList<>(); - interceptor.setRepeatOperations(new RepeatOperations() { - @Override - public RepeatStatus iterate(RepeatCallback callback) { - calls.add(null); - return RepeatStatus.FINISHED; - } + interceptor.setRepeatOperations(callback -> { + calls.add(null); + return RepeatStatus.FINISHED; }); ((Advised) service).addAdvice(interceptor); Exception exception = assertThrows(IllegalStateException.class, service::service); @@ -161,12 +154,9 @@ class RepeatOperationsInterceptorTests { void testInterceptorChainWithRetry() throws Exception { ((Advised) service).addAdvice(interceptor); final List list = new ArrayList<>(); - ((Advised) service).addAdvice(new MethodInterceptor() { - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - list.add("chain"); - return invocation.proceed(); - } + ((Advised) service).addAdvice((MethodInterceptor) invocation -> { + list.add("chain"); + return invocation.proceed(); }); RepeatTemplate template = new RepeatTemplate(); template.setCompletionPolicy(new SimpleCompletionPolicy(2)); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/SimpleRepeatTemplateTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/SimpleRepeatTemplateTests.java index 1dcea1588..d239724bb 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/SimpleRepeatTemplateTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/SimpleRepeatTemplateTests.java @@ -245,15 +245,12 @@ class SimpleRepeatTemplateTests extends AbstractTradeBatchTests { void testNestedSession() { RepeatTemplate outer = getRepeatTemplate(); RepeatTemplate inner = getRepeatTemplate(); - outer.iterate(new NestedRepeatCallback(inner, new RepeatCallback() { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - count++; - assertNotNull(context); - assertNotSame(context, context.getParent(), "Nested batch should have new session"); - assertSame(context, RepeatSynchronizationManager.getContext()); - return RepeatStatus.FINISHED; - } + outer.iterate(new NestedRepeatCallback(inner, context -> { + count++; + assertNotNull(context); + assertNotSame(context, context.getParent(), "Nested batch should have new session"); + assertSame(context, RepeatSynchronizationManager.getContext()); + return RepeatStatus.FINISHED; }) { @Override public RepeatStatus doInIteration(RepeatContext context) throws Exception { @@ -269,14 +266,11 @@ class SimpleRepeatTemplateTests extends AbstractTradeBatchTests { void testNestedSessionTerminatesBeforeIteration() { RepeatTemplate outer = getRepeatTemplate(); RepeatTemplate inner = getRepeatTemplate(); - outer.iterate(new NestedRepeatCallback(inner, new RepeatCallback() { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - count++; - assertEquals(2, count); - fail("Nested batch should not have been executed"); - return RepeatStatus.FINISHED; - } + outer.iterate(new NestedRepeatCallback(inner, context -> { + count++; + assertEquals(2, count); + fail("Nested batch should not have been executed"); + return RepeatStatus.FINISHED; }) { @Override public RepeatStatus doInIteration(RepeatContext context) throws Exception { @@ -293,15 +287,12 @@ class SimpleRepeatTemplateTests extends AbstractTradeBatchTests { RepeatTemplate outer = getRepeatTemplate(); outer.setCompletionPolicy(new SimpleCompletionPolicy(2)); RepeatTemplate inner = getRepeatTemplate(); - outer.iterate(new NestedRepeatCallback(inner, new RepeatCallback() { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - count++; - assertNotNull(context); - assertNotSame(context, context.getParent(), "Nested batch should have new session"); - assertSame(context, RepeatSynchronizationManager.getContext()); - return RepeatStatus.FINISHED; - } + outer.iterate(new NestedRepeatCallback(inner, context -> { + count++; + assertNotNull(context); + assertNotSame(context, context.getParent(), "Nested batch should have new session"); + assertSame(context, RepeatSynchronizationManager.getContext()); + return RepeatStatus.FINISHED; }) { @Override public RepeatStatus doInIteration(RepeatContext context) throws Exception { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java index 5e0191721..6d5dbf0d9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java @@ -108,15 +108,12 @@ class TaskExecutorRepeatTemplateAsynchronousTests extends AbstractTradeBatchTest RepeatTemplate outer = getRepeatTemplate(); RepeatTemplate inner = new RepeatTemplate(); - outer.iterate(new NestedRepeatCallback(inner, new RepeatCallback() { - @Override - public RepeatStatus doInIteration(RepeatContext context) throws Exception { - count++; - assertNotNull(context); - assertNotSame(context, context.getParent(), "Nested batch should have new session"); - assertSame(context, RepeatSynchronizationManager.getContext()); - return RepeatStatus.FINISHED; - } + outer.iterate(new NestedRepeatCallback(inner, context -> { + count++; + assertNotNull(context); + assertNotSame(context, context.getParent(), "Nested batch should have new session"); + assertSame(context, RepeatSynchronizationManager.getContext()); + return RepeatStatus.FINISHED; }) { @Override public RepeatStatus doInIteration(RepeatContext context) throws Exception { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java index 8fdb257f3..baef448a3 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java @@ -25,7 +25,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; @@ -41,7 +40,6 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.Assert; @@ -110,12 +108,7 @@ class ConcurrentTransactionAwareProxyTests { @Test void testTransactionalContains() { final Map> map = TransactionAwareProxyFactory.createAppendOnlyTransactionalMap(); - boolean result = new TransactionTemplate(transactionManager).execute(new TransactionCallback<>() { - @Override - public Boolean doInTransaction(TransactionStatus status) { - return map.containsKey("foo"); - } - }); + boolean result = new TransactionTemplate(transactionManager).execute(status -> map.containsKey("foo")); assertFalse(result); } @@ -124,17 +117,14 @@ class ConcurrentTransactionAwareProxyTests { for (int i = 0; i < outerMax; i++) { final int count = i; - completionService.submit(new Callable<>() { - @Override - public List call() throws Exception { - List list = new ArrayList<>(); - for (int i = 0; i < innerMax; i++) { - String value = count + "bar" + i; - saveInSetAndAssert(set, value); - list.add(value); - } - return list; + completionService.submit(() -> { + List list = new ArrayList<>(); + for (int i1 = 0; i1 < innerMax; i1++) { + String value = count + "bar" + i1; + saveInSetAndAssert(set, value); + list.add(value); } + return list; }); } @@ -152,24 +142,21 @@ class ConcurrentTransactionAwareProxyTests { for (int i = 0; i < outerMax; i++) { - completionService.submit(new Callable<>() { - @Override - public List call() throws Exception { - List result = new ArrayList<>(); - for (int i = 0; i < innerMax; i++) { - String value = "bar" + i; - saveInListAndAssert(list, value); - result.add(value); - // Need to slow it down to allow threads to interleave - Thread.sleep(10L); - if (mutate) { - list.remove(value); - list.add(value); - } + completionService.submit(() -> { + List result = new ArrayList<>(); + for (int i1 = 0; i1 < innerMax; i1++) { + String value = "bar" + i1; + saveInListAndAssert(list, value); + result.add(value); + // Need to slow it down to allow threads to interleave + Thread.sleep(10L); + if (mutate) { + list.remove(value); + list.add(value); } - logger.info("Added: " + innerMax + " values"); - return result; } + logger.info("Added: " + innerMax + " values"); + return result; }); } @@ -192,16 +179,13 @@ class ConcurrentTransactionAwareProxyTests { for (int j = 0; j < numberOfKeys; j++) { final long id = j * 1000 + 123L + i; - completionService.submit(new Callable<>() { - @Override - public List call() throws Exception { - List list = new ArrayList<>(); - for (int i = 0; i < innerMax; i++) { - String value = "bar" + i; - list.add(saveInMapAndAssert(map, id, value).get("foo")); - } - return list; + completionService.submit(() -> { + List list = new ArrayList<>(); + for (int i1 = 0; i1 < innerMax; i1++) { + String value = "bar" + i1; + list.add(saveInMapAndAssert(map, id, value).get("foo")); } + return list; }); } @@ -215,12 +199,9 @@ class ConcurrentTransactionAwareProxyTests { private String saveInSetAndAssert(final Set set, final String value) { - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - set.add(value); - return null; - } + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + set.add(value); + return null; }); Assert.state(set.contains(value), "Lost update: value=" + value); @@ -231,12 +212,9 @@ class ConcurrentTransactionAwareProxyTests { private String saveInListAndAssert(final List list, final String value) { - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - list.add(value); - return null; - } + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + list.add(value); + return null; }); Assert.state(list.contains(value), "Lost update: value=" + value); @@ -248,15 +226,12 @@ class ConcurrentTransactionAwareProxyTests { private Map saveInMapAndAssert(final Map> map, final Long id, final String value) { - new TransactionTemplate(transactionManager).execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - if (!map.containsKey(id)) { - map.put(id, new HashMap<>()); - } - map.get(id).put("foo", value); - return null; + new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { + if (!map.containsKey(id)) { + map.put(id, new HashMap<>()); } + map.get(id).put("foo", value); + return null; }); Map result = map.get(id); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareListFactoryTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareListFactoryTests.java index f56d9df67..bd7c4069c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareListFactoryTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareListFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -26,7 +26,6 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -66,36 +65,27 @@ class TransactionAwareListFactoryTests { @Test void testTransactionalAdd() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testAdd(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testAdd(); + return null; }); assertEquals(4, list.size()); } @Test void testTransactionalRemove() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testRemove(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testRemove(); + return null; }); assertEquals(2, list.size()); } @Test void testTransactionalClear() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testClear(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testClear(); + return null; }); assertEquals(0, list.size()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareMapFactoryTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareMapFactoryTests.java index 61bcdf56d..ec864ac14 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareMapFactoryTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/TransactionAwareMapFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -21,7 +21,6 @@ import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -84,60 +83,45 @@ class TransactionAwareMapFactoryTests { @Test void testTransactionalAdd() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testAdd(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testAdd(); + return null; }); assertEquals(4, map.size()); } @Test void testTransactionalEmpty() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testEmpty(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testEmpty(); + return null; }); assertEquals(4, map.size()); } @Test void testTransactionalValues() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testValues(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testValues(); + return null; }); assertEquals(4, map.size()); } @Test void testTransactionalRemove() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testRemove(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testRemove(); + return null; }); assertEquals(2, map.size()); } @Test void testTransactionalClear() { - transactionTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - testClear(); - return null; - } + transactionTemplate.execute((TransactionCallback) status -> { + testClear(); + return null; }); assertEquals(0, map.size()); } diff --git a/spring-batch-infrastructure/src/test/java/test/jdbc/datasource/DataSourceInitializer.java b/spring-batch-infrastructure/src/test/java/test/jdbc/datasource/DataSourceInitializer.java index 563394e80..057af5b50 100644 --- a/spring-batch-infrastructure/src/test/java/test/jdbc/datasource/DataSourceInitializer.java +++ b/spring-batch-infrastructure/src/test/java/test/jdbc/datasource/DataSourceInitializer.java @@ -32,7 +32,6 @@ import org.springframework.core.io.Resource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.JdbcTransactionManager; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.Assert; @@ -125,38 +124,32 @@ public class DataSourceInitializer implements InitializingBean, DisposableBean { final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); TransactionTemplate transactionTemplate = new TransactionTemplate(new JdbcTransactionManager(dataSource)); - transactionTemplate.execute(new TransactionCallback() { - - @Override - @SuppressWarnings("unchecked") - public Void doInTransaction(TransactionStatus status) { - String[] scripts; - try { - scripts = StringUtils.delimitedListToStringArray( - stripComments(IOUtils.readLines(scriptResource.getInputStream(), "UTF-8")), ";"); - } - catch (IOException e) { - throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); - } - for (String s : scripts) { - String script = s.trim(); - if (StringUtils.hasText(script)) { - try { - jdbcTemplate.execute(script); + transactionTemplate.execute((TransactionCallback) status -> { + String[] scripts; + try { + scripts = StringUtils.delimitedListToStringArray( + stripComments(IOUtils.readLines(scriptResource.getInputStream(), "UTF-8")), ";"); + } + catch (IOException e) { + throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); + } + for (String s : scripts) { + String script = s.trim(); + if (StringUtils.hasText(script)) { + try { + jdbcTemplate.execute(script); + } + catch (DataAccessException e) { + if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { + logger.debug("DROP script failed (ignoring): " + script); } - catch (DataAccessException e) { - if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { - logger.debug("DROP script failed (ignoring): " + script); - } - else { - throw e; - } + else { + throw e; } } } - return null; } - + return null; }); } diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemProcessor.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemProcessor.java index ea9590ba2..9b65d9e2a 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemProcessor.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemProcessor.java @@ -15,7 +15,6 @@ */ package org.springframework.batch.integration.async; -import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -90,18 +89,16 @@ public class AsyncItemProcessor implements ItemProcessor>, In @Nullable public Future process(final I item) throws Exception { final StepExecution stepExecution = getStepExecution(); - FutureTask task = new FutureTask<>(new Callable<>() { - public O call() throws Exception { + FutureTask task = new FutureTask<>(() -> { + if (stepExecution != null) { + StepSynchronizationManager.register(stepExecution); + } + try { + return delegate.process(item); + } + finally { if (stepExecution != null) { - StepSynchronizationManager.register(stepExecution); - } - try { - return delegate.process(item); - } - finally { - if (stepExecution != null) { - StepSynchronizationManager.close(); - } + StepSynchronizationManager.close(); } } }); diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/partition/MessageChannelPartitionHandler.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/partition/MessageChannelPartitionHandler.java index 528334bf9..e4ac74e8d 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/partition/MessageChannelPartitionHandler.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/partition/MessageChannelPartitionHandler.java @@ -253,30 +253,25 @@ public class MessageChannelPartitionHandler extends AbstractPartitionHandler imp throws Exception { final Set result = new HashSet<>(split.size()); - Callable> callback = new Callable<>() { - @Override - public Set call() throws Exception { - Set currentStepExecutionIds = split.stream() - .map(StepExecution::getId) - .collect(Collectors.toSet()); - JobExecution jobExecution = jobExplorer.getJobExecution(managerStepExecution.getJobExecutionId()); - jobExecution.getStepExecutions() - .stream() - .filter(stepExecution -> currentStepExecutionIds.contains(stepExecution.getId())) - .filter(stepExecution -> !result.contains(stepExecution)) - .filter(stepExecution -> !stepExecution.getStatus().isRunning()) - .forEach(result::add); + Callable> callback = () -> { + Set currentStepExecutionIds = split.stream().map(StepExecution::getId).collect(Collectors.toSet()); + JobExecution jobExecution = jobExplorer.getJobExecution(managerStepExecution.getJobExecutionId()); + jobExecution.getStepExecutions() + .stream() + .filter(stepExecution -> currentStepExecutionIds.contains(stepExecution.getId())) + .filter(stepExecution -> !result.contains(stepExecution)) + .filter(stepExecution -> !stepExecution.getStatus().isRunning()) + .forEach(result::add); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Currently waiting on %s partitions to finish", split.size())); - } + if (logger.isDebugEnabled()) { + logger.debug(String.format("Currently waiting on %s partitions to finish", split.size())); + } - if (result.size() == split.size()) { - return result; - } - else { - return null; - } + if (result.size() == split.size()) { + return result; + } + else { + return null; } }; diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemProcessorTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemProcessorTests.java index 6f761e207..401c607ae 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemProcessorTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemProcessorTests.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.junit.jupiter.api.Test; @@ -68,11 +67,7 @@ class AsyncItemProcessorTests { }; processor.setDelegate(delegate); Future result = StepScopeTestUtils.doInStepScope(MetaDataInstanceFactory.createStepExecution(), - new Callable<>() { - public Future call() throws Exception { - return processor.process("foo"); - } - }); + () -> processor.process("foo")); assertEquals("foofoo", result.get()); } diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java index 9bf5c2f94..4d8a75f19 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java @@ -17,7 +17,6 @@ package org.springframework.batch.integration.async; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -64,19 +63,9 @@ class AsyncItemWriterTests { writer.setDelegate(new ListItemWriter(writtenItems)); Chunk> processedItems = new Chunk<>(); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - return "foo"; - } - })); + processedItems.add(new FutureTask<>(() -> "foo")); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - return "bar"; - } - })); + processedItems.add(new FutureTask<>(() -> "bar")); for (FutureTask processedItem : processedItems) { taskExecutor.execute(processedItem); @@ -94,19 +83,9 @@ class AsyncItemWriterTests { writer.setDelegate(new ListItemWriter(writtenItems)); Chunk> processedItems = new Chunk<>(); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - return "foo"; - } - })); + processedItems.add(new FutureTask<>(() -> "foo")); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - return null; - } - })); + processedItems.add(new FutureTask<>(() -> null)); for (FutureTask processedItem : processedItems) { taskExecutor.execute(processedItem); @@ -123,18 +102,10 @@ class AsyncItemWriterTests { writer.setDelegate(new ListItemWriter(writtenItems)); Chunk> processedItems = new Chunk<>(); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - return "foo"; - } - })); + processedItems.add(new FutureTask<>(() -> "foo")); - processedItems.add(new FutureTask<>(new Callable<>() { - @Override - public String call() throws Exception { - throw new RuntimeException("This was expected"); - } + processedItems.add(new FutureTask<>(() -> { + throw new RuntimeException("This was expected"); })); for (FutureTask processedItem : processedItems) { diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java index 3326ba7be..376894a49 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java @@ -18,7 +18,6 @@ package org.springframework.batch.integration.chunk; import org.junit.jupiter.api.Test; import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.step.item.ChunkProcessor; import org.springframework.batch.item.Chunk; import org.springframework.batch.test.MetaDataInstanceFactory; @@ -34,11 +33,7 @@ class ChunkProcessorChunkHandlerTests { @Test void testVanillaHandleChunk() throws Exception { // given - handler.setChunkProcessor(new ChunkProcessor<>() { - public void process(StepContribution contribution, Chunk chunk) throws Exception { - count += chunk.size(); - } - }); + handler.setChunkProcessor((contribution, chunk) -> count += chunk.size()); StepContribution stepContribution = MetaDataInstanceFactory.createStepExecution().createStepContribution(); Chunk items = Chunk.of("foo", "bar"); ChunkRequest chunkRequest = new ChunkRequest<>(0, items, 12L, stepContribution); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemReader.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemReader.java index 5ca9ffd10..193a39801 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemReader.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemReader.java @@ -18,8 +18,6 @@ package org.springframework.batch.sample.common; import java.io.InputStream; import java.io.ObjectInputStream; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Iterator; import java.util.List; @@ -37,7 +35,6 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -84,12 +81,7 @@ public class StagingItemReader "SELECT ID FROM BATCH_STAGING WHERE JOB_ID=? AND PROCESSED=? ORDER BY ID", - new RowMapper<>() { - @Override - public Long mapRow(ResultSet rs, int rowNum) throws SQLException { - return rs.getLong(1); - } - }, + (rs, rowNum) -> rs.getLong(1), stepExecution.getJobExecution().getJobId(), StagingItemWriter.NEW); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/CustomerFilterJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/CustomerFilterJobFunctionalTests.java index 36ca64195..3755b29e3 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/CustomerFilterJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/CustomerFilterJobFunctionalTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -16,8 +16,6 @@ package org.springframework.batch.sample; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -33,7 +31,6 @@ import org.springframework.batch.core.JobExecution; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; @@ -90,13 +87,10 @@ class CustomerFilterJobFunctionalTests { new Customer("customer6", 123456)); activeRow = 0; - jdbcTemplate.query(GET_CUSTOMERS, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - CustomerFilterJobFunctionalTests.Customer customer = customers.get(activeRow++); - assertEquals(customer.getName(), rs.getString(1)); - assertEquals(customer.getCredit(), rs.getDouble(2), .01); - } + jdbcTemplate.query(GET_CUSTOMERS, rs -> { + Customer customer = customers.get(activeRow++); + assertEquals(customer.getName(), rs.getString(1)); + assertEquals(customer.getCredit(), rs.getDouble(2), .01); }); Map step1Execution = this.getStepExecution(jobExecution, "uploadCustomer"); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java index 015c69efc..4faf885fe 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -17,8 +17,6 @@ package org.springframework.batch.sample; import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -34,7 +32,6 @@ import org.springframework.batch.sample.domain.trade.Trade; import org.springframework.batch.test.JobLauncherTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; @@ -95,29 +92,23 @@ class TradeJobFunctionalTests { new Trade("UK21341EAH48", 108, new BigDecimal("109.25"), "customer3"), new Trade("UK21341EAH49", 854, new BigDecimal("123.39"), "customer4")); - jdbcTemplate.query(GET_TRADES, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - Trade trade = trades.get(activeRow++); + jdbcTemplate.query(GET_TRADES, rs -> { + Trade trade = trades.get(activeRow++); - assertEquals(trade.getIsin(), rs.getString(1)); - assertEquals(trade.getQuantity(), rs.getLong(2)); - assertEquals(trade.getPrice(), rs.getBigDecimal(3)); - assertEquals(trade.getCustomer(), rs.getString(4)); - } + assertEquals(trade.getIsin(), rs.getString(1)); + assertEquals(trade.getQuantity(), rs.getLong(2)); + assertEquals(trade.getPrice(), rs.getBigDecimal(3)); + assertEquals(trade.getCustomer(), rs.getString(4)); }); assertEquals(activeRow, trades.size()); activeRow = 0; - jdbcTemplate.query(GET_CUSTOMERS, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - Customer customer = customers.get(activeRow++); + jdbcTemplate.query(GET_CUSTOMERS, rs -> { + Customer customer = customers.get(activeRow++); - assertEquals(customer.getName(), rs.getString(1)); - assertEquals(customer.getCredit(), rs.getDouble(2), .01); - } + assertEquals(customer.getName(), rs.getString(1)); + assertEquals(customer.getCredit(), rs.getDouble(2), .01); }); assertEquals(customers.size(), activeRow); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java index 0d845f774..3b2ada91a 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java @@ -32,7 +32,6 @@ import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @@ -100,17 +99,14 @@ class StagingItemReaderTests { void testUpdateProcessIndicatorAfterCommit() { TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - txTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus transactionStatus) { - try { - testReaderWithProcessorUpdatesProcessIndicator(); - } - catch (Exception e) { - fail("Unexpected Exception: " + e); - } - return null; + txTemplate.execute((TransactionCallback) transactionStatus -> { + try { + testReaderWithProcessorUpdatesProcessIndicator(); } + catch (Exception e) { + fail("Unexpected Exception: " + e); + } + return null; }); long id = jdbcTemplate.queryForObject("SELECT MIN(ID) from BATCH_STAGING where JOB_ID=?", Long.class, jobId); String before = jdbcTemplate.queryForObject("SELECT PROCESSED from BATCH_STAGING where ID=?", String.class, id); @@ -123,23 +119,20 @@ class StagingItemReaderTests { TransactionTemplate txTemplate = new TransactionTemplate(transactionManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - final Long idToUse = txTemplate.execute(new TransactionCallback<>() { - @Override - public Long doInTransaction(TransactionStatus transactionStatus) { + final Long idToUse = txTemplate.execute(transactionStatus -> { - long id = jdbcTemplate.queryForObject("SELECT MIN(ID) from BATCH_STAGING where JOB_ID=?", Long.class, - jobId); - String before = jdbcTemplate.queryForObject("SELECT PROCESSED from BATCH_STAGING where ID=?", - String.class, id); - assertEquals(StagingItemWriter.NEW, before); + long id = jdbcTemplate.queryForObject("SELECT MIN(ID) from BATCH_STAGING where JOB_ID=?", Long.class, + jobId); + String before = jdbcTemplate.queryForObject("SELECT PROCESSED from BATCH_STAGING where ID=?", String.class, + id); + assertEquals(StagingItemWriter.NEW, before); - ProcessIndicatorItemWrapper wrapper = reader.read(); - assertEquals("FOO", wrapper.getItem()); + ProcessIndicatorItemWrapper wrapper = reader.read(); + assertEquals("FOO", wrapper.getItem()); - transactionStatus.setRollbackOnly(); + transactionStatus.setRollbackOnly(); - return id; - } + return id; }); String after = jdbcTemplate.queryForObject("SELECT PROCESSED from BATCH_STAGING where ID=?", String.class, diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerDaoIntegrationTests.java index c761d06a0..6f61b2e7b 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerDaoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -15,9 +15,6 @@ */ package org.springframework.batch.sample.domain.football.internal; -import java.sql.ResultSet; -import java.sql.SQLException; - import javax.sql.DataSource; import org.junit.jupiter.api.BeforeEach; @@ -26,7 +23,6 @@ import org.junit.jupiter.api.Test; import org.springframework.batch.sample.domain.football.Player; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.annotation.Transactional; @@ -74,16 +70,13 @@ class JdbcPlayerDaoIntegrationTests { @Transactional void testSavePlayer() { playerDao.savePlayer(player); - jdbcTemplate.query(GET_PLAYER, new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - assertEquals(rs.getString("PLAYER_ID"), "AKFJDL00"); - assertEquals(rs.getString("LAST_NAME"), "Doe"); - assertEquals(rs.getString("FIRST_NAME"), "John"); - assertEquals(rs.getString("POS"), "QB"); - assertEquals(rs.getInt("YEAR_OF_BIRTH"), 1975); - assertEquals(rs.getInt("YEAR_DRAFTED"), 1998); - } + jdbcTemplate.query(GET_PLAYER, rs -> { + assertEquals(rs.getString("PLAYER_ID"), "AKFJDL00"); + assertEquals(rs.getString("LAST_NAME"), "Doe"); + assertEquals(rs.getString("FIRST_NAME"), "John"); + assertEquals(rs.getString("POS"), "QB"); + assertEquals(rs.getInt("YEAR_OF_BIRTH"), 1975); + assertEquals(rs.getInt("YEAR_DRAFTED"), 1998); }); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/multiline/AggregateItemFieldSetMapperTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/multiline/AggregateItemFieldSetMapperTests.java index a9409d378..1d1ff93dd 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/multiline/AggregateItemFieldSetMapperTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/multiline/AggregateItemFieldSetMapperTests.java @@ -16,9 +16,7 @@ package org.springframework.batch.sample.domain.multiline; import org.junit.jupiter.api.Test; -import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.DefaultFieldSet; -import org.springframework.batch.item.file.transform.FieldSet; import static org.junit.jupiter.api.Assertions.*; @@ -57,12 +55,7 @@ class AggregateItemFieldSetMapperTests { @Test void testDelegate() throws Exception { - mapper.setDelegate(new FieldSetMapper<>() { - @Override - public String mapFieldSet(FieldSet fs) { - return "foo"; - } - }); + mapper.setDelegate(fs -> "foo"); assertEquals("foo", mapper.mapFieldSet(new DefaultFieldSet(new String[] { "FOO" })).getItem()); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java index 4abf86a8a..435d9a349 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2022 the original author or authors. + * Copyright 2008-2023 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. @@ -17,7 +17,6 @@ package org.springframework.batch.sample.domain.trade.internal; import org.junit.jupiter.api.Test; import org.springframework.batch.item.Chunk; -import org.springframework.batch.sample.domain.trade.CustomerDebit; import org.springframework.batch.sample.domain.trade.CustomerDebitDao; import org.springframework.batch.sample.domain.trade.Trade; @@ -33,12 +32,9 @@ class CustomerUpdateProcessorTests { trade.setCustomer("testCustomerName"); trade.setPrice(new BigDecimal("123.0")); - CustomerDebitDao dao = new CustomerDebitDao() { - @Override - public void write(CustomerDebit customerDebit) { - assertEquals("testCustomerName", customerDebit.getName()); - assertEquals(new BigDecimal("123.0"), customerDebit.getDebit()); - } + CustomerDebitDao dao = customerDebit -> { + assertEquals("testCustomerName", customerDebit.getName()); + assertEquals(new BigDecimal("123.0"), customerDebit.getDebit()); }; CustomerUpdateWriter processor = new CustomerUpdateWriter(); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcCustomerDebitDaoTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcCustomerDebitDaoTests.java index 2354cf5a6..5037a45a2 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcCustomerDebitDaoTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcCustomerDebitDaoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -16,8 +16,6 @@ package org.springframework.batch.sample.domain.trade.internal; import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; import javax.sql.DataSource; @@ -27,7 +25,6 @@ import org.springframework.batch.sample.domain.trade.CustomerDebit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; @@ -57,11 +54,8 @@ class JdbcCustomerDebitDaoTests { writer.write(customerDebit); - jdbcTemplate.query("SELECT name, credit FROM CUSTOMER WHERE name = 'testName'", new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - assertEquals(95, rs.getLong("credit")); - } + jdbcTemplate.query("SELECT name, credit FROM CUSTOMER WHERE name = 'testName'", rs -> { + assertEquals(95, rs.getLong("credit")); }); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcTradeWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcTradeWriterTests.java index 6268f111d..c3bf4613a 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcTradeWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/JdbcTradeWriterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -16,8 +16,6 @@ package org.springframework.batch.sample.domain.trade.internal; import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; import javax.sql.DataSource; @@ -29,7 +27,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.support.incrementer.AbstractDataFieldMaxValueIncrementer; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.transaction.annotation.Transactional; @@ -69,13 +66,10 @@ class JdbcTradeWriterTests implements InitializingBean { writer.writeTrade(trade); - jdbcTemplate.query("SELECT * FROM TRADE WHERE ISIN = '5647238492'", new RowCallbackHandler() { - @Override - public void processRow(ResultSet rs) throws SQLException { - assertEquals("testCustomer", rs.getString("CUSTOMER")); - assertEquals(new BigDecimal(Double.toString(99.69)), rs.getBigDecimal("PRICE")); - assertEquals(5, rs.getLong("QUANTITY")); - } + jdbcTemplate.query("SELECT * FROM TRADE WHERE ISIN = '5647238492'", rs -> { + assertEquals("testCustomer", rs.getString("CUSTOMER")); + assertEquals(new BigDecimal(Double.toString(99.69)), rs.getBigDecimal("PRICE")); + assertEquals(5, rs.getLong("QUANTITY")); }); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/TwoJobInstancesDelimitedFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/TwoJobInstancesDelimitedFunctionalTests.java index 2f40a6b01..dd485ad21 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/TwoJobInstancesDelimitedFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/TwoJobInstancesDelimitedFunctionalTests.java @@ -17,7 +17,6 @@ package org.springframework.batch.sample.iosample; import java.util.Date; -import java.util.concurrent.Callable; import org.junit.jupiter.api.Test; @@ -79,23 +78,20 @@ class TwoJobInstancesDelimitedFunctionalTests { .toJobParameters(); StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(jobParameters); - int count = StepScopeTestUtils.doInStepScope(stepExecution, new Callable<>() { - @Override - public Integer call() throws Exception { - int count = 0; + int count = StepScopeTestUtils.doInStepScope(stepExecution, () -> { + int count1 = 0; - readerStream.open(new ExecutionContext()); + readerStream.open(new ExecutionContext()); - try { - while (reader.read() != null) { - count++; - } + try { + while (reader.read() != null) { + count1++; } - finally { - readerStream.close(); - } - return count; } + finally { + readerStream.close(); + } + return count1; }); assertEquals(expected, count); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/jmx/JobExecutionNotificationPublisherTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/jmx/JobExecutionNotificationPublisherTests.java index fd82351dc..182e9b7ac 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/jmx/JobExecutionNotificationPublisherTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/jmx/JobExecutionNotificationPublisherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -16,8 +16,6 @@ package org.springframework.batch.sample.jmx; import org.junit.jupiter.api.Test; -import org.springframework.jmx.export.notification.NotificationPublisher; -import org.springframework.jmx.export.notification.UnableToSendNotificationException; import javax.management.Notification; import java.util.ArrayList; @@ -30,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * @author Dave Syer * @author Thomas Risberg * @author Glenn Renfro + * @author Mahmoud Ben Hassine * */ class JobExecutionNotificationPublisherTests { @@ -40,12 +39,7 @@ class JobExecutionNotificationPublisherTests { void testRepeatOperationsOpenUsed() { final List list = new ArrayList<>(); - publisher.setNotificationPublisher(new NotificationPublisher() { - @Override - public void sendNotification(Notification notification) throws UnableToSendNotificationException { - list.add(notification); - } - }); + publisher.setNotificationPublisher(notification -> list.add(notification)); publisher.onApplicationEvent(new SimpleMessageApplicationEvent(this, "foo")); assertEquals(1, list.size()); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/launch/RemoteLauncherTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/launch/RemoteLauncherTests.java index 74fcbf2c2..fcabdb607 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/launch/RemoteLauncherTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/launch/RemoteLauncherTests.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.*; /** * @author Dave Syer * @author Jinwoo Bae + * @author Mahmoud Ben Hassine * */ class RemoteLauncherTests { @@ -117,16 +118,13 @@ class RemoteLauncherTests { static void setUp() throws Exception { System.setProperty("com.sun.management.jmxremote", ""); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - try { - JobRegistryBackgroundJobRunner.main("adhoc-job-launcher-context.xml", "jobs/adhocLoopJob.xml"); - } - catch (Exception e) { - logger.error(e); - errors.add(e); - } + Thread thread = new Thread(() -> { + try { + JobRegistryBackgroundJobRunner.main("adhoc-job-launcher-context.xml", "jobs/adhocLoopJob.xml"); + } + catch (Exception e) { + logger.error(e); + errors.add(e); } }); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/quartz/JobLauncherDetailsTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/quartz/JobLauncherDetailsTests.java index ea7a6704c..ec270ebba 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/quartz/JobLauncherDetailsTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/quartz/JobLauncherDetailsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -29,11 +29,6 @@ import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersIncrementer; import org.springframework.batch.core.JobParametersValidator; -import org.springframework.batch.core.configuration.JobLocator; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.NoSuchJobException; -import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; -import org.springframework.batch.core.repository.JobRestartException; import org.springframework.lang.Nullable; import java.io.Serializable; @@ -47,6 +42,7 @@ import static org.mockito.Mockito.mock; /** * @author Dave Syer * @author Glenn Renfro + * @author Mahmoud Ben Hassine * */ class JobLauncherDetailsTests { @@ -59,21 +55,14 @@ class JobLauncherDetailsTests { @BeforeEach public void setUp() throws Exception { - details.setJobLauncher(new JobLauncher() { - @Override - public JobExecution run(org.springframework.batch.core.Job job, JobParameters jobParameters) - throws JobExecutionAlreadyRunningException, JobRestartException { - list.add(jobParameters); - return null; - } + details.setJobLauncher((job, jobParameters) -> { + list.add(jobParameters); + return null; }); - details.setJobLocator(new JobLocator() { - @Override - public org.springframework.batch.core.Job getJob(@Nullable String name) throws NoSuchJobException { - list.add(name); - return new StubJob("foo"); - } + details.setJobLocator(name -> { + list.add(name); + return new StubJob("foo"); }); } diff --git a/spring-batch-test/src/test/java/org/springframework/batch/test/JobRepositoryTestUtilsTests.java b/spring-batch-test/src/test/java/org/springframework/batch/test/JobRepositoryTestUtilsTests.java index 0575fce35..3887f71ec 100644 --- a/spring-batch-test/src/test/java/org/springframework/batch/test/JobRepositoryTestUtilsTests.java +++ b/spring-batch-test/src/test/java/org/springframework/batch/test/JobRepositoryTestUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2022 the original author or authors. + * Copyright 2006-2023 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. @@ -28,11 +28,9 @@ import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.JobParametersIncrementer; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.lang.Nullable; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.jdbc.JdbcTestUtils; @@ -122,12 +120,8 @@ class JobRepositoryTestUtilsTests { @Test void testCreateJobExecutionsWithIncrementer() throws Exception { utils = new JobRepositoryTestUtils(jobRepository); - utils.setJobParametersIncrementer(new JobParametersIncrementer() { - @Override - public JobParameters getNext(@Nullable JobParameters parameters) { - return new JobParametersBuilder().addString("foo", "bar").toJobParameters(); - } - }); + utils.setJobParametersIncrementer( + parameters -> new JobParametersBuilder().addString("foo", "bar").toJobParameters()); List list = utils.createJobExecutions(1); assertEquals(1, list.size()); assertEquals("bar", list.get(0).getJobParameters().getString("foo"));