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

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