Use lambdas and method references where appropriate

This commit is contained in:
Mahmoud Ben Hassine
2023-06-12 16:43:25 +02:00
parent c5b4f1a777
commit 93d911e100
115 changed files with 1260 additions and 2500 deletions

View File

@@ -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<FlowExecution> task = new FutureTask<>(new Callable<>() {
@Override
public FlowExecution call() throws Exception {
return flow.start(executor);
}
});
final FutureTask<FlowExecution> task = new FutureTask<>(() -> flow.start(executor));
tasks.add(task);

View File

@@ -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<StepExecution> 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;
});
}

View File

@@ -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);
});
}

View File

@@ -373,12 +373,9 @@ public class JdbcJobExecutionDao extends AbstractJdbcBatchMetadataDao implements
public Set<JobExecution> findRunningJobExecutions(String jobName) {
final Set<JobExecution> 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<String, JobParameter<?>> 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);

View File

@@ -221,12 +221,7 @@ public class JdbcJobInstanceDao extends AbstractJdbcBatchMetadataDao implements
*/
@Override
public List<String> 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));
}
/*

View File

@@ -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<Jo
TransactionInterceptor advice = new TransactionInterceptor((TransactionManager) this.transactionManager,
this.transactionAttributeSource);
if (this.validateTransactionState) {
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
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();
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor((MethodInterceptor) invocation -> {
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*");

View File

@@ -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;

View File

@@ -215,87 +215,77 @@ public class FaultTolerantChunkProcessor<I, O> extends SimpleChunkProcessor<I, O
final I item = iterator.next();
RetryCallback<O, Exception> 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<O> 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<O, Exception> 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<O> 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<I, O> extends SimpleChunkProcessor<I, O
final UserData<O> data = (UserData<O>) inputs.getUserData();
final AtomicReference<RetryContext> contextHolder = new AtomicReference<>();
RetryCallback<Object, Exception> retryCallback = new RetryCallback<>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
contextHolder.set(context);
RetryCallback<Object, Exception> 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<Object> batchRecoveryCallback = new RecoveryCallback<>() {
RecoveryCallback<Object> 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<I>.ChunkIterator inputIterator = inputs.iterator();
for (Chunk<O>.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<I>.ChunkIterator inputIterator = inputs.iterator();
for (Chunk<O>.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<I, O> extends SimpleChunkProcessor<I, O
}
else {
RecoveryCallback<Object> 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<Object> 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()) {

View File

@@ -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<I> implements ChunkProvider<I> {
public Chunk<I> provide(final StepContribution contribution) throws Exception {
final Chunk<I> 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;

View File

@@ -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

View File

@@ -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

View File

@@ -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);

View File

@@ -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<Step> 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");

View File

@@ -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<StateTransition> 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<StateTransition> transitions = new ArrayList<>();

View File

@@ -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<String> 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<String> 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);

View File

@@ -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<Object> 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<Object> 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<Object> 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<Object> iterator = list.iterator();

View File

@@ -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));
}

View File

@@ -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<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution)
throws Exception {
Set<StepExecution> executions = stepSplitter.split(stepExecution, 2);
for (StepExecution execution : executions) {
execution.setStatus(BatchStatus.COMPLETED);
execution.setExitStatus(ExitStatus.COMPLETED);
}
return executions;
step.setPartitionHandler((stepSplitter, stepExecution) -> {
Set<StepExecution> 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<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution)
throws Exception {
Set<StepExecution> executions = stepSplitter.split(stepExecution, 2);
for (StepExecution execution : executions) {
execution.setStatus(BatchStatus.FAILED);
execution.setExitStatus(ExitStatus.FAILED);
}
return executions;
step.setPartitionHandler((stepSplitter, stepExecution) -> {
Set<StepExecution> 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<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution)
throws Exception {
Set<StepExecution> 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<StepExecution> 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<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution)
throws Exception {
Set<StepExecution> executions = stepSplitter.split(stepExecution, 2);
for (StepExecution execution : executions) {
execution.setStatus(BatchStatus.STOPPED);
execution.setExitStatus(ExitStatus.STOPPED);
}
return executions;
step.setPartitionHandler((stepSplitter, stepExecution) -> {
Set<StepExecution> 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<StepExecution> 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");

View File

@@ -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<String, ExecutionContext> map = Collections.singletonMap("foo", new ExecutionContext());
SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, true, step.getName(),
new Partitioner() {
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
return map;
}
});
gridSize -> map);
assertEquals(1, splitter.split(stepExecution, 2).size());
}

View File

@@ -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<StepExecution> executions = handler.handle(stepExecutionSplitter, stepExecution);
new DefaultStepExecutionAggregator().aggregate(stepExecution, executions);

View File

@@ -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<String> 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<String> 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<String> 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<String> 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);

View File

@@ -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<String> 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<String> 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<String> 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<String> 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);

View File

@@ -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<String>() {
@Override
public String getObject() throws BeansException {
return foo;
}
}));
assertThrows(IllegalStateException.class, () -> scope.get("foo", (ObjectFactory<String>) () -> foo));
}
@Test
void testGetWithNothingAlreadyThere() {
final String foo = "bar";
Object value = scope.get("foo", new ObjectFactory<String>() {
@Override
public String getObject() throws BeansException {
return foo;
}
});
Object value = scope.get("foo", (ObjectFactory<String>) () -> 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<String>() {
@Override
public String getObject() throws BeansException {
return null;
}
});
Object value = scope.get("foo", (ObjectFactory<String>) () -> null);
assertEquals("bar", value);
assertTrue(context.hasAttribute("foo"));
}
@@ -104,12 +89,7 @@ class JobScopeTests {
void testRegisterDestructionCallback() {
final List<String> 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<String> 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...

View File

@@ -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<String> 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<String> 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...

View File

@@ -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...

View File

@@ -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<String> 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<JobContext> 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<JobContext> 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<String> 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());

View File

@@ -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...

View File

@@ -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<String> 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<StepContext> 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<StepContext> 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<String> 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());

View File

@@ -167,15 +167,10 @@ class RegisterMultiListenerTests {
@Bean
public ItemWriter<String> writer() {
return new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
if (chunk.getItems().contains("item2")) {
throw new MySkippableException();
}
return chunk -> {
if (chunk.getItems().contains("item2")) {
throw new MySkippableException();
}
};
}

View File

@@ -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<String, Exception>() {
@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<String, Exception>) context -> {
assertTrue(context.getClass().getSimpleName().contains("Batch"),
"Wrong context type: " + context.getClass().getSimpleName());
return "2";
}, Arrays.<RetryState>asList(new DefaultRetryState("1")));
assertEquals("2", result);
@@ -70,15 +66,12 @@ class BatchRetryTemplateTests {
BatchRetryTemplate template = new BatchRetryTemplate();
RetryCallback<String[], Exception> 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<String[], Exception> retryCallback = context -> {
assertEquals(count, context.getRetryCount());
if (count++ == 0) {
throw new RecoverableException("Recoverable");
}
return new String[] { "a", "b" };
};
List<RetryState> states = Arrays.<RetryState>asList(new DefaultRetryState("1"), new DefaultRetryState("2"));
@@ -97,14 +90,11 @@ class BatchRetryTemplateTests {
template.setRetryPolicy(new SimpleRetryPolicy(1,
Collections.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true)));
RetryCallback<String[], Exception> 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<String[], Exception> 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.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true)));
RetryCallback<String[], Exception> 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<String[], Exception> 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.<Class<? extends Throwable>, Boolean>singletonMap(Exception.class, true)));
RetryCallback<String[], Exception> 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<String[], Exception> retryCallback = context -> {
if (count++ < 2) {
throw new RecoverableException("Recoverable");
}
return outputs.toArray(new String[0]);
};
RecoveryCallback<String[]> recoveryCallback = new RecoveryCallback<>() {
@Override
public String[] recover(RetryContext context) throws Exception {
List<String> recovered = new ArrayList<>();
for (String item : outputs) {
recovered.add("r:" + item);
}
return recovered.toArray(new String[0]);
RecoveryCallback<String[]> recoveryCallback = context -> {
List<String> recovered = new ArrayList<>();
for (String item : outputs) {
recovered.add("r:" + item);
}
return recovered.toArray(new String[0]);
};
outputs = Arrays.asList("a", "b");

View File

@@ -52,12 +52,7 @@ class ChunkOrientedTaskletTests {
@Override
public void postProcess(StepContribution contribution, Chunk<String> chunk) {
}
}, new ChunkProcessor<>() {
@Override
public void process(StepContribution contribution, Chunk<String> 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<String> chunk) {
}
}, new ChunkProcessor<>() {
@Override
public void process(StepContribution contribution, Chunk<String> 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<String> chunk) {
}
}, new ChunkProcessor<>() {
@Override
public void process(StepContribution contribution, Chunk<String> 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();

View File

@@ -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<? extends String> 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<? extends String> chunk) throws Exception {
if (chunk.getItems().contains("fail")) {
fail("Expected Error!");
}
processor.setItemWriter(chunk -> {
if (chunk.getItems().contains("fail")) {
fail("Expected Error!");
}
});
Chunk<String> 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<? extends String> 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<String> 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<? extends String> 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<String> inputs = new Chunk<>(Arrays.asList("fail"));
@@ -302,15 +289,12 @@ class FaultTolerantChunkProcessorTests {
@Test
void testAfterWriteAllPassedInRecovery() throws Exception {
Chunk<String> chunk = new Chunk<>(Arrays.asList("foo", "bar"));
processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> 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<String, String>() {
@Override
@@ -349,12 +333,9 @@ class FaultTolerantChunkProcessorTests {
@Test
void testOnErrorInWriteAllItemsFail() throws Exception {
Chunk<String> chunk = new Chunk<>(Arrays.asList("foo", "bar"));
processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> 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<String, String>() {
@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<? extends String> 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<String> 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<? extends String> 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<String> inputs = new Chunk<>(Arrays.asList("3", "fail", "fail", "4"));
@@ -447,15 +422,12 @@ class FaultTolerantChunkProcessorTests {
batchRetryTemplate.setRetryPolicy(retryPolicy);
processor.setWriteSkipPolicy(new LimitCheckingItemSkipPolicy(1,
Collections.<Class<? extends Throwable>, Boolean>singletonMap(IllegalArgumentException.class, true)));
processor.setItemWriter(new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> 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<String> inputs = new Chunk<>(Arrays.asList("3", "fail", "2"));

View File

@@ -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<? extends String> 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<? extends String>) advised);

View File

@@ -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();

View File

@@ -71,12 +71,7 @@ class SimpleStepFactoryBeanTests {
private final List<String> written = new ArrayList<>();
private final ItemWriter<String> writer = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> data) throws Exception {
written.addAll(data.getItems());
}
};
private final ItemWriter<String> writer = data -> written.addAll(data.getItems());
private ItemReader<String> reader = new ListItemReader<>(Arrays.asList("a", "b", "c"));
@@ -175,11 +170,8 @@ class SimpleStepFactoryBeanTests {
SimpleStepFactoryBean<String, String> factory = getStepFactory(new String[] { "foo", "bar", "spam" });
factory.setItemWriter(new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> data) throws Exception {
throw new RuntimeException("Error!");
}
factory.setItemWriter(data -> {
throw new RuntimeException("Error!");
});
factory.setListeners(new StepListener[] { new ItemListenerSupport<String, String>() {
@Override
@@ -213,11 +205,8 @@ class SimpleStepFactoryBeanTests {
void testExceptionTerminates() throws Exception {
SimpleStepFactoryBean<String, String> factory = getStepFactory(new String[] { "foo", "bar", "spam" });
factory.setBeanName("exceptionStep");
factory.setItemWriter(new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> 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));

View File

@@ -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);
}

View File

@@ -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<? extends String> 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);
}

View File

@@ -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));
}

View File

@@ -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<? extends Object> 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;

View File

@@ -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<Serializable> list = new ArrayList<>();
ItemWriter<String> itemWriter = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> data) throws Exception {
processed.addAll(data.getItems());
}
};
ItemWriter<String> 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);

View File

@@ -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<Void>() {
@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<Void>) 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;
});
}

View File

@@ -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<T> implements ItemWriter<T>, 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<int[]>) ps -> {
for (T item : chunk) {
itemPreparedStatementSetter.setValues(item, ps);
ps.addBatch();
}
return ps.executeBatch();
});
}

View File

@@ -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++) {

View File

@@ -481,12 +481,8 @@ public class StaxEventItemWriter<T> extends AbstractItemStreamItemWriter<T>
try {
final FileChannel channel = fileChannel;
if (transactional) {
TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, new Runnable() {
@Override
public void run() {
closeStream();
}
});
TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel,
() -> closeStream());
writer.setEncoding(encoding);
writer.setForceSync(forceSync);

View File

@@ -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) {

View File

@@ -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<Method> 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();

View File

@@ -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<Foo> 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<Foo> 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)

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
template.queryForList("select baz from bar");
template.queryForList("select foo from bar");
return null;
}
tt.execute((TransactionCallback<Void>) status -> {
template.queryForList("select baz from bar");
template.queryForList("select foo from bar");
return null;
});
tt.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
template.queryForList("select ham from foo");
tt2.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
template.queryForList("select 1 from eggs");
return null;
}
});
template.queryForList("select more, ham from foo");
tt.execute((TransactionCallback<Void>) status -> {
template.queryForList("select ham from foo");
tt2.execute((TransactionCallback<Void>) status1 -> {
template.queryForList("select 1 from eggs");
return null;
}
});
template.queryForList("select more, ham from foo");
return null;
});
tt.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
template.queryForList("select spam from ham");
return null;
}
tt.execute((TransactionCallback<Void>) status -> {
template.queryForList("select spam from ham");
return null;
});
csds.stopCloseSuppression(connection);
DataSourceUtils.releaseConnection(connection, csds);

View File

@@ -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"));

View File

@@ -148,12 +148,7 @@ public class JdbcBatchItemWriterNamedParameterTests {
mapWriter.setSql(sql);
mapWriter.setJdbcTemplate(namedParameterJdbcOperations);
mapWriter.setItemSqlParameterSourceProvider(new ItemSqlParameterSourceProvider<>() {
@Override
public SqlParameterSource createSqlParameterSource(Map<String, Object> item) {
return new MapSqlParameterSource(item);
}
});
mapWriter.setItemSqlParameterSourceProvider(item -> new MapSqlParameterSource(item));
mapWriter.afterPropertiesSet();
ArgumentCaptor<SqlParameterSource[]> captor = ArgumentCaptor.forClass(SqlParameterSource[].class);

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
reader.open(ec);
reader.close();
return null;
}
tt.execute((TransactionCallback<Void>) 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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
reader.open(ec);
reader.close();
return null;
}
tt.execute((TransactionCallback<Void>) status -> {
reader.open(ec);
reader.close();
return null;
});
}

View File

@@ -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<List<Foo>> completionService = new ExecutorCompletionService<>(
Executors.newFixedThreadPool(THREAD_COUNT));
for (int i = 0; i < THREAD_COUNT; i++) {
completionService.submit(new Callable<>() {
@Override
public List<Foo> call() throws Exception {
List<Foo> 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<Foo> 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();

View File

@@ -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.<String, Object>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();

View File

@@ -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();

View File

@@ -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();

View File

@@ -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.<String, Object>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();

View File

@@ -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();

View File

@@ -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();

View File

@@ -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<List<Foo>> completionService = new ExecutorCompletionService<>(
Executors.newFixedThreadPool(THREAD_COUNT));
for (int i = 0; i < THREAD_COUNT; i++) {
completionService.submit(new Callable<>() {
@Override
public List<Foo> call() throws Exception {
List<Foo> 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<Foo> 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;

View File

@@ -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<Foo> 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<Foo> 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);

View File

@@ -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);

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
reader.open(ec);
reader.close();
return null;
}
tt.execute((TransactionCallback<Void>) 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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
reader.open(ec);
reader.close();
return null;
}
tt.execute((TransactionCallback<Void>) 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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
reader.open(ec);
reader.close();
return null;
}
tt.execute((TransactionCallback<Void>) status -> {
reader.open(ec);
reader.close();
return null;
});
}

View File

@@ -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<Foo> reader = new JdbcCursorItemReaderBuilder<Foo>().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();

View File

@@ -34,13 +34,10 @@ public class FlatFileItemReaderCommonTests extends AbstractItemStreamItemReaderT
FlatFileItemReader<Foo> 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);

View File

@@ -440,14 +440,11 @@ class FlatFileItemReaderTests {
*/
@Test
void testMappingExceptionWrapping() throws Exception {
LineMapper<String> 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<String> exceptionLineMapper = (line, lineNumber) -> {
if (lineNumber == 2) {
throw new Exception("Couldn't map line 2");
}
return line;
};
reader.setLineMapper(exceptionLineMapper);
reader.afterPropertiesSet();

View File

@@ -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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<String> items = Chunk.of("1", "2", "3");

View File

@@ -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<Foo> multiReader = new MultiResourceItemReader<>();
FlatFileItemReader<Foo> 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;

View File

@@ -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 });
}

View File

@@ -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 });
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -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();

View File

@@ -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<Future<Boolean>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<Boolean> 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<Boolean> 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);
}

View File

@@ -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<String, LineTokenizer> 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<String, FieldSetMapper<Name>> 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<String, LineTokenizer> 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<String, FieldSetMapper<Name>> 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));

View File

@@ -33,12 +33,7 @@ class FormatterLineAggregatorTests {
// object under test
private FormatterLineAggregator<String[]> aggregator;
private final FieldExtractor<String[]> defaultFieldExtractor = new FieldExtractor<>() {
@Override
public Object[] extract(String[] item) {
return item;
}
};
private final FieldExtractor<String[]> defaultFieldExtractor = item -> item;
@BeforeEach
void setup() {

View File

@@ -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<String, LineTokenizer> 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<String, LineTokenizer> 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());

View File

@@ -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")));
}

View File

@@ -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<String> 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();

View File

@@ -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<String> 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();

View File

@@ -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<String> 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);

View File

@@ -45,18 +45,8 @@ class ClassifierCompositeItemWriterTests {
@Test
void testWrite() throws Exception {
Map<String, ItemWriter<String>> map = new HashMap<>();
ItemWriter<String> fooWriter = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
foos.addAll(chunk.getItems());
}
};
ItemWriter<String> defaultWriter = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
defaults.addAll(chunk.getItems());
}
};
ItemWriter<String> fooWriter = chunk -> foos.addAll(chunk.getItems());
ItemWriter<String> defaultWriter = chunk -> defaults.addAll(chunk.getItems());
map.put("foo", fooWriter);
map.put("*", defaultWriter);
writer.setClassifier(new PatternMatchingClassifier(map));

View File

@@ -43,18 +43,8 @@ class ClassifierCompositeItemWriterBuilderTests {
@Test
void testWrite() throws Exception {
Map<String, ItemWriter<? super String>> map = new HashMap<>();
ItemWriter<String> fooWriter = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
foos.addAll(chunk.getItems());
}
};
ItemWriter<String> defaultWriter = new ItemWriter<>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
defaults.addAll(chunk.getItems());
}
};
ItemWriter<String> fooWriter = chunk -> foos.addAll(chunk.getItems());
ItemWriter<String> defaultWriter = chunk -> defaults.addAll(chunk.getItems());
map.put("foo", fooWriter);
map.put("*", defaultWriter);
ClassifierCompositeItemWriter<String> writer = new ClassifierCompositeItemWriterBuilder<String>()

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
new TransactionTemplate(new ResourcelessTransactionManager())
.execute((TransactionCallback<Void>) 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();

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
new TransactionTemplate(new ResourcelessTransactionManager())
.execute((TransactionCallback<Void>) 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();

View File

@@ -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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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<Void>() {
@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<Void>) 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);
}
});

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
try {
writer.write(items);
}
catch (Exception e) {
throw new RuntimeException(e);
}
return null;
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) 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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
try {
writer.write(items);
}
catch (Exception e) {
throw new RuntimeException(e);
}
return null;
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) 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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
try {
writer.write(items);
}
catch (Exception e) {
throw new RuntimeException(e);
}
return null;
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) status -> {
try {
writer.write(items);
}
catch (Exception e) {
throw new RuntimeException(e);
}
return null;
});
writer.update(executionContext);
writer.close();

View File

@@ -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<String> callback = new Callable<>() {
@Override
public String call() throws Exception {
Set<String> executions = new HashSet<>(repository);
if (executions.isEmpty()) {
return null;
}
return executions.iterator().next();
Callable<String> callback = () -> {
Set<String> 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<String> callback = new Callable<>() {
@Override
public String call() throws Exception {
Set<String> executions = new HashSet<>(repository);
if (executions.isEmpty()) {
return null;
}
return executions.iterator().next();
Callable<String> callback = () -> {
Set<String> 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<String> callback = new Callable<>() {
@Override
public String call() throws Exception {
Set<String> executions = new HashSet<>(repository);
if (executions.isEmpty()) {
return null;
}
throw new RuntimeException("Expected");
Callable<String> callback = () -> {
Set<String> executions = new HashSet<>(repository);
if (executions.isEmpty()) {
return null;
}
throw new RuntimeException("Expected");
};
Poller<String> 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();
}

View File

@@ -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);

View File

@@ -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<String> 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));

View File

@@ -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<Object> 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<Object> 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<Object> 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));

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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<Long, Map<String, String>> 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<String> call() throws Exception {
List<String> 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<String> 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<String> call() throws Exception {
List<String> 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<String> 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<String> call() throws Exception {
List<String> 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<String> 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<String> set, final String value) {
new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
set.add(value);
return null;
}
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) 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<String> list, final String value) {
new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
list.add(value);
return null;
}
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) status -> {
list.add(value);
return null;
});
Assert.state(list.contains(value), "Lost update: value=" + value);
@@ -248,15 +226,12 @@ class ConcurrentTransactionAwareProxyTests {
private Map<String, String> saveInMapAndAssert(final Map<Long, Map<String, String>> map, final Long id,
final String value) {
new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
@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<Void>) status -> {
if (!map.containsKey(id)) {
map.put(id, new HashMap<>());
}
map.get(id).put("foo", value);
return null;
});
Map<String, String> result = map.get(id);

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testAdd();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testAdd();
return null;
});
assertEquals(4, list.size());
}
@Test
void testTransactionalRemove() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testRemove();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testRemove();
return null;
});
assertEquals(2, list.size());
}
@Test
void testTransactionalClear() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testClear();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testClear();
return null;
});
assertEquals(0, list.size());
}

View File

@@ -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<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testAdd();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testAdd();
return null;
});
assertEquals(4, map.size());
}
@Test
void testTransactionalEmpty() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testEmpty();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testEmpty();
return null;
});
assertEquals(4, map.size());
}
@Test
void testTransactionalValues() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testValues();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testValues();
return null;
});
assertEquals(4, map.size());
}
@Test
void testTransactionalRemove() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testRemove();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testRemove();
return null;
});
assertEquals(2, map.size());
}
@Test
void testTransactionalClear() {
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
testClear();
return null;
}
transactionTemplate.execute((TransactionCallback<Void>) status -> {
testClear();
return null;
});
assertEquals(0, map.size());
}

View File

@@ -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<Void>() {
@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<Void>) 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;
});
}

View File

@@ -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<I, O> implements ItemProcessor<I, Future<O>>, In
@Nullable
public Future<O> process(final I item) throws Exception {
final StepExecution stepExecution = getStepExecution();
FutureTask<O> task = new FutureTask<>(new Callable<>() {
public O call() throws Exception {
FutureTask<O> 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();
}
}
});

View File

@@ -253,30 +253,25 @@ public class MessageChannelPartitionHandler extends AbstractPartitionHandler imp
throws Exception {
final Set<StepExecution> result = new HashSet<>(split.size());
Callable<Set<StepExecution>> callback = new Callable<>() {
@Override
public Set<StepExecution> call() throws Exception {
Set<Long> 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<Set<StepExecution>> callback = () -> {
Set<Long> 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;
}
};

View File

@@ -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<String> result = StepScopeTestUtils.doInStepScope(MetaDataInstanceFactory.createStepExecution(),
new Callable<>() {
public Future<String> call() throws Exception {
return processor.process("foo");
}
});
() -> processor.process("foo"));
assertEquals("foofoo", result.get());
}

View File

@@ -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<FutureTask<String>> 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<String> processedItem : processedItems) {
taskExecutor.execute(processedItem);
@@ -94,19 +83,9 @@ class AsyncItemWriterTests {
writer.setDelegate(new ListItemWriter(writtenItems));
Chunk<FutureTask<String>> 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<String> processedItem : processedItems) {
taskExecutor.execute(processedItem);
@@ -123,18 +102,10 @@ class AsyncItemWriterTests {
writer.setDelegate(new ListItemWriter(writtenItems));
Chunk<FutureTask<String>> 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<String> processedItem : processedItems) {

Some files were not shown because too many files have changed in this diff Show More