diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/ItemWriteListener.java b/spring-batch-core/src/main/java/org/springframework/batch/core/ItemWriteListener.java index bcb388960..c89e3da6c 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/ItemWriteListener.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/ItemWriteListener.java @@ -18,12 +18,13 @@ package org.springframework.batch.core; import java.util.List; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** *

* Listener interface for the writing of items. Implementations of this interface are - * notified before, after, and in case of any exception thrown while writing a list of + * notified before, after, and in case of any exception thrown while writing a chunk of * items. *

* @@ -42,19 +43,18 @@ import org.springframework.batch.item.ItemWriter; public interface ItemWriteListener extends StepListener { /** - * Called before {@link ItemWriter#write(java.util.List)} + * Called before {@link ItemWriter#write(Chunk)} * @param items to be written */ - default void beforeWrite(List items) { + default void beforeWrite(Chunk items) { } /** - * Called after {@link ItemWriter#write(java.util.List)}. This is called before any - * transaction is committed, and before - * {@link ChunkListener#afterChunk(ChunkContext)}. + * Called after {@link ItemWriter#write(Chunk)}. This is called before any transaction + * is committed, and before {@link ChunkListener#afterChunk(ChunkContext)}. * @param items written items */ - default void afterWrite(List items) { + default void afterWrite(Chunk items) { } /** @@ -64,7 +64,7 @@ public interface ItemWriteListener extends StepListener { * @param exception thrown from {@link ItemWriter} * @param items attempted to be written. */ - default void onWriteError(Exception exception, List items) { + default void onWriteError(Exception exception, Chunk items) { } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/AfterWrite.java b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/AfterWrite.java index 9d8bda813..8a15a1739 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/AfterWrite.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/AfterWrite.java @@ -27,12 +27,14 @@ import org.springframework.batch.item.ItemWriter; /** * Marks a method to be called after an item is passed to an {@link ItemWriter}. Note that - * this annotation takes a {@link List} because Spring Batch generally processes a group - * of items (for the sake of efficiency).
+ * this annotation takes a {@link org.springframework.batch.item.Chunk} because Spring + * Batch generally processes a group of items (for the sake of efficiency).
*
- * Expected signature: void afterWrite({@link List}<? extends S> items) + * Expected signature: void afterWrite({@link org.springframework.batch.item.Chunk}<? + * extends S> items) * * @author Lucas Ward + * @author Mahmoud Ben Hassine * @since 2.0 * @see ItemWriteListener */ diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/BeforeWrite.java b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/BeforeWrite.java index 7c5eb1ce8..58812a540 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/BeforeWrite.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/BeforeWrite.java @@ -26,11 +26,13 @@ import org.springframework.batch.core.ItemWriteListener; import org.springframework.batch.item.ItemWriter; /** - * Marks a method to be called before an item is passed to an {@link ItemWriter}.
+ * Marks a method to be called before a chunk is passed to an {@link ItemWriter}.
*
- * Expected signature: void beforeWrite({@link List}<? extends S> items) + * Expected signature: void beforeWrite({@link org.springframework.batch.item.Chunk}<? + * extends S> items) * * @author Lucas Ward + * @author Mahmoud Ben Hassine * @since 2.0 * @see ItemWriteListener */ diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/OnWriteError.java b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/OnWriteError.java index 7d8283ba0..fe71f0870 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/OnWriteError.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/annotation/OnWriteError.java @@ -27,13 +27,14 @@ import org.springframework.batch.item.ItemWriter; /** * Marks a method to be called if an exception is thrown by an {@link ItemWriter}. Note - * that this annotation takes a {@link List} because Spring Batch generally processes a - * group of items (for the sake of efficiency).
+ * that this annotation takes a {@link org.springframework.batch.item.Chunk} because + * Spring Batch generally processes a group of items (for the sake of efficiency).
*
- * Expected signature: void onWriteError({@link Exception} exception, {@link List}<? - * extends S> items) + * Expected signature: void onWriteError({@link Exception} exception, + * {@link org.springframework.batch.item.Chunk}<? extends S> items) * * @author Lucas Ward + * @author Mahmoud Ben Hassine * @since 2.0 * @see ItemWriteListener */ diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemWriteListener.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemWriteListener.java index de28c07e6..9c00e4ae5 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemWriteListener.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/CompositeItemWriteListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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,11 +19,13 @@ import java.util.Iterator; import java.util.List; import org.springframework.batch.core.ItemWriteListener; +import org.springframework.batch.item.Chunk; import org.springframework.core.Ordered; /** * @author Lucas Ward * @author Dave Syer + * @author Mahmoud Ben Hassine * */ public class CompositeItemWriteListener implements ItemWriteListener { @@ -50,10 +52,10 @@ public class CompositeItemWriteListener implements ItemWriteListener { /** * Call the registered listeners in reverse order, respecting and prioritising those * that implement {@link Ordered}. - * @see ItemWriteListener#afterWrite(java.util.List) + * @see ItemWriteListener#afterWrite(Chunk) */ @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { for (Iterator> iterator = listeners.reverse(); iterator.hasNext();) { ItemWriteListener listener = iterator.next(); listener.afterWrite(items); @@ -63,10 +65,10 @@ public class CompositeItemWriteListener implements ItemWriteListener { /** * Call the registered listeners in order, respecting and prioritising those that * implement {@link Ordered}. - * @see ItemWriteListener#beforeWrite(List) + * @see ItemWriteListener#beforeWrite(Chunk) */ @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { for (Iterator> iterator = listeners.iterator(); iterator.hasNext();) { ItemWriteListener listener = iterator.next(); listener.beforeWrite(items); @@ -76,10 +78,10 @@ public class CompositeItemWriteListener implements ItemWriteListener { /** * Call the registered listeners in reverse order, respecting and prioritising those * that implement {@link Ordered}. - * @see ItemWriteListener#onWriteError(Exception, List) + * @see ItemWriteListener#onWriteError(Exception, Chunk) */ @Override - public void onWriteError(Exception ex, List items) { + public void onWriteError(Exception ex, Chunk items) { for (Iterator> iterator = listeners.reverse(); iterator.hasNext();) { ItemWriteListener listener = iterator.next(); listener.onWriteError(ex, items); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java index 90170a4a7..fe517bebe 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.core.StepListener; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemStream; import org.springframework.lang.Nullable; @@ -241,10 +242,10 @@ public class MulticasterBatchListener implements StepExecutionListener, Ch } /** - * @see ItemWriteListener#afterWrite(List) + * @see ItemWriteListener#afterWrite(Chunk) */ @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { try { itemWriteListener.afterWrite(items); } @@ -254,10 +255,10 @@ public class MulticasterBatchListener implements StepExecutionListener, Ch } /** - * @see ItemWriteListener#beforeWrite(List) + * @see ItemWriteListener#beforeWrite(Chunk) */ @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { try { itemWriteListener.beforeWrite(items); } @@ -267,10 +268,10 @@ public class MulticasterBatchListener implements StepExecutionListener, Ch } /** - * @see ItemWriteListener#onWriteError(Exception, List) + * @see ItemWriteListener#onWriteError(Exception, Chunk) */ @Override - public void onWriteError(Exception ex, List items) { + public void onWriteError(Exception ex, Chunk items) { try { itemWriteListener.onWriteError(ex, items); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/StepListenerMetaData.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/StepListenerMetaData.java index df4b988a2..4ef713a61 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/StepListenerMetaData.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/StepListenerMetaData.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2022 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. @@ -46,6 +46,7 @@ import org.springframework.batch.core.annotation.OnSkipInRead; import org.springframework.batch.core.annotation.OnSkipInWrite; import org.springframework.batch.core.annotation.OnWriteError; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; /** * Enumeration for {@link StepListener} meta data, which ties together the names of @@ -72,10 +73,10 @@ public enum StepListenerMetaData implements ListenerMetaData { Object.class), ON_PROCESS_ERROR("onProcessError", "on-process-error-method", OnProcessError.class, ItemProcessListener.class, Object.class, Exception.class), - BEFORE_WRITE("beforeWrite", "before-write-method", BeforeWrite.class, ItemWriteListener.class, List.class), - AFTER_WRITE("afterWrite", "after-write-method", AfterWrite.class, ItemWriteListener.class, List.class), + BEFORE_WRITE("beforeWrite", "before-write-method", BeforeWrite.class, ItemWriteListener.class, Chunk.class), + AFTER_WRITE("afterWrite", "after-write-method", AfterWrite.class, ItemWriteListener.class, Chunk.class), ON_WRITE_ERROR("onWriteError", "on-write-error-method", OnWriteError.class, ItemWriteListener.class, - Exception.class, List.class), + Exception.class, Chunk.class), ON_SKIP_IN_READ("onSkipInRead", "on-skip-in-read-method", OnSkipInRead.class, SkipListener.class, Throwable.class), ON_SKIP_IN_PROCESS("onSkipInProcess", "on-skip-in-process-method", OnSkipInProcess.class, SkipListener.class, Object.class, Throwable.class), diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkOrientedTasklet.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkOrientedTasklet.java index 1a7fc7d0a..fbeb0425b 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkOrientedTasklet.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkOrientedTasklet.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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,6 +21,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.item.Chunk; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.lang.Nullable; @@ -28,6 +29,7 @@ import org.springframework.lang.Nullable; * A {@link Tasklet} implementing variations on read-process-write item handling. * * @author Dave Syer + * @author Mahmoud Ben Hassine * @param input item type */ public class ChunkOrientedTasklet implements Tasklet { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProcessor.java index 5ca36744d..3bab818b8 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,9 +17,10 @@ package org.springframework.batch.core.step.item; import org.springframework.batch.core.StepContribution; +import org.springframework.batch.item.Chunk; /** - * Interface defined for processing {@link Chunk}s. + * Interface defined for processing {@link org.springframework.batch.item.Chunk}s. * * @since 2.0 */ diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProvider.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProvider.java index 36b778d2c..f713af61f 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProvider.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,11 @@ package org.springframework.batch.core.step.item; import org.springframework.batch.core.StepContribution; +import org.springframework.batch.item.Chunk; /** - * Interface for providing {@link Chunk}s to be processed, used by the - * {@link ChunkOrientedTasklet} + * Interface for providing {@link org.springframework.batch.item.Chunk}s to be processed, + * used by the {@link ChunkOrientedTasklet} * * @since 2.0 * @see ChunkOrientedTasklet diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/DefaultItemFailureHandler.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/DefaultItemFailureHandler.java index 77c5c5225..d43dd1b20 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/DefaultItemFailureHandler.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/DefaultItemFailureHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008 the original author or authors. + * Copyright 2006-2022 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,6 +20,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.Chunk; /** * Default implementation of the {@link ItemListenerSupport} class that writes all @@ -28,6 +29,7 @@ import org.springframework.batch.core.listener.ItemListenerSupport; * object. * * @author Lucas Ward + * @author Mahmoud Ben Hassine * */ public class DefaultItemFailureHandler extends ItemListenerSupport { @@ -45,7 +47,7 @@ public class DefaultItemFailureHandler extends ItemListenerSupport item) { + public void onWriteError(Exception ex, Chunk item) { try { logger.error("Error encountered while writing item: [ " + item + "]", ex); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java index dbcdc8370..821400209 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java @@ -34,8 +34,10 @@ import org.springframework.batch.core.step.skip.NonSkippableProcessException; import org.springframework.batch.core.step.skip.SkipLimitExceededException; import org.springframework.batch.core.step.skip.SkipListenerFailedException; import org.springframework.batch.core.step.skip.SkipPolicy; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; +import org.springframework.batch.item.SkipWrapper; import org.springframework.classify.BinaryExceptionClassifier; import org.springframework.classify.Classifier; import org.springframework.retry.ExhaustedRetryException; @@ -337,7 +339,7 @@ public class FaultTolerantChunkProcessor extends SimpleChunkProcessor extends SimpleChunkProcessor items = Collections.singletonList(outputIterator.next()); + Chunk items = Chunk.of(outputIterator.next()); inputIterator.next(); try { writeItems(items); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProvider.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProvider.java index 47ec677fb..768bf0f79 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProvider.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProvider.java @@ -23,6 +23,7 @@ import org.springframework.batch.core.step.skip.SkipException; import org.springframework.batch.core.step.skip.SkipListenerFailedException; import org.springframework.batch.core.step.skip.SkipPolicy; import org.springframework.batch.core.step.skip.SkipPolicyFailedException; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.repeat.RepeatOperations; import org.springframework.classify.BinaryExceptionClassifier; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProcessor.java index 0799d2453..193cf5681 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProcessor.java @@ -26,6 +26,7 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepListener; 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.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; @@ -145,7 +146,7 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi * @param items list of items to be written. * @throws Exception thrown if error occurs. */ - protected final void doWrite(List items) throws Exception { + protected final void doWrite(Chunk items) throws Exception { if (itemWriter == null) { return; @@ -167,7 +168,7 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi * Call the listener's after write method. * @param items list of items that were just written. */ - protected final void doAfterWrite(List items) { + protected final void doAfterWrite(Chunk items) { listener.afterWrite(items); } @@ -176,7 +177,7 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi * @param e exception that occurred. * @param items list of items that failed to be written. */ - protected final void doOnWriteError(Exception e, List items) { + protected final void doOnWriteError(Exception e, Chunk items) { listener.onWriteError(e, items); } @@ -184,7 +185,7 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi * @param items list of items to be written. * @throws Exception thrown if error occurs. */ - protected void writeItems(List items) throws Exception { + protected void writeItems(Chunk items) throws Exception { if (itemWriter != null) { itemWriter.write(items); } @@ -267,10 +268,10 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi } /** - * Simple implementation delegates to the {@link #doWrite(List)} method and increments - * the write count in the contribution. Subclasses can handle more complicated - * scenarios, e.g.with fault tolerance. If output items are skipped they should be - * removed from the inputs as well. + * Simple implementation delegates to the {@link #doWrite(Chunk)} method and + * increments the write count in the contribution. Subclasses can handle more + * complicated scenarios, e.g.with fault tolerance. If output items are skipped they + * should be removed from the inputs as well. * @param contribution the current step contribution * @param inputs the inputs that gave rise to the outputs * @param outputs the outputs to write @@ -280,7 +281,7 @@ public class SimpleChunkProcessor implements ChunkProcessor, Initializi Timer.Sample sample = BatchMetrics.createTimerSample(); String status = BatchMetrics.STATUS_SUCCESS; try { - doWrite(outputs.getItems()); + doWrite(outputs); } catch (Exception e) { /* diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java index 6bb97894f..8cb63e60c 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SimpleChunkProvider.java @@ -28,6 +28,7 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepListener; 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; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DummyItemWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DummyItemWriter.java index 53b10ea64..0dc213739 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DummyItemWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/DummyItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2012 the original author or authors. + * Copyright 2009-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,18 @@ package org.springframework.batch.core.configuration.xml; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** * @author Dan Garrette + * @author Mahmoud Ben Hassine * @since 2.0 */ public class DummyItemWriter implements ItemWriter { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestPojoListener.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestPojoListener.java index 51628e3b3..ed4b52db3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestPojoListener.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestPojoListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2010 the original author or authors. + * Copyright 2010-2022 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,11 +18,12 @@ package org.springframework.batch.core.configuration.xml; import java.util.List; import org.springframework.batch.core.annotation.AfterWrite; +import org.springframework.batch.item.Chunk; public class TestPojoListener extends AbstractTestComponent { @AfterWrite - public void after(List items) { + public void after(Chunk items) { executed = true; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestWriter.java index 6f8635516..779501a7e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/xml/TestWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,13 @@ package org.springframework.batch.core.configuration.xml; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; public class TestWriter extends AbstractTestComponent implements ItemWriter { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { executed = true; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/EmptyItemWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/EmptyItemWriter.java index ae2bd100b..c98e64d40 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/EmptyItemWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/EmptyItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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,6 +20,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.support.transaction.TransactionAwareProxyFactory; import org.springframework.beans.factory.InitializingBean; @@ -49,7 +51,7 @@ public class EmptyItemWriter implements ItemWriter, InitializingBean { } @Override - public void write(List items) { + public void write(Chunk items) { for (T data : items) { if (!failed && list.size() == failurePoint) { failed = true; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java index f57683061..3136ca4c6 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java @@ -24,10 +24,12 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.batch.core.ItemWriteListener; +import org.springframework.batch.item.Chunk; /** * @author Lucas Ward * @author Will Schipp + * @author Mahmoud Ben Hassine * */ class CompositeItemWriteListenerTests { @@ -46,21 +48,21 @@ class CompositeItemWriteListenerTests { @Test void testBeforeWrite() { - List item = Collections.singletonList(new Object()); + Chunk item = Chunk.of(new Object()); listener.beforeWrite(item); compositeListener.beforeWrite(item); } @Test void testAfterWrite() { - List item = Collections.singletonList(new Object()); + Chunk item = Chunk.of(new Object()); listener.afterWrite(item); compositeListener.afterWrite(item); } @Test void testOnWriteError() { - List item = Collections.singletonList(new Object()); + Chunk item = Chunk.of(new Object()); Exception ex = new Exception(); listener.onWriteError(ex, item); compositeListener.onWriteError(ex, item); @@ -73,7 +75,7 @@ class CompositeItemWriteListenerTests { add(listener); } }); - List item = Collections.singletonList(new Object()); + Chunk item = Chunk.of(new Object()); listener.beforeWrite(item); compositeListener.beforeWrite(item); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java index 25d6c8cb4..50ca6bc75 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/ItemListenerErrorTests.java @@ -37,6 +37,7 @@ import org.springframework.batch.core.configuration.annotation.JobBuilderFactory import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.launch.support.RunIdIncrementer; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -175,7 +176,7 @@ class ItemListenerErrorTests { private boolean goingToFail = false; @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { if (goingToFail) { throw new RuntimeException("failure in the writer"); } @@ -294,21 +295,21 @@ class ItemListenerErrorTests { } @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { if (methodToThrowExceptionFrom.equals("beforeWrite")) { throw new RuntimeException("beforeWrite caused this Exception"); } } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { if (methodToThrowExceptionFrom.equals("afterWrite")) { throw new RuntimeException("afterWrite caused this Exception"); } } @Override - public void onWriteError(Exception ex, List item) { + public void onWriteError(Exception ex, Chunk item) { if (methodToThrowExceptionFrom.equals("onWriteError")) { throw new RuntimeException("onWriteError caused this Exception"); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java index 63bcb291f..a4427c4af 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java @@ -38,6 +38,7 @@ import org.springframework.batch.core.annotation.BeforeProcess; import org.springframework.batch.core.annotation.BeforeRead; import org.springframework.batch.core.annotation.BeforeWrite; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.lang.Nullable; /** @@ -703,7 +704,7 @@ class MulticasterBatchListenerTests { * (java.util.List) */ @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { count++; if (error) { throw new RuntimeException("listener error"); @@ -718,7 +719,7 @@ class MulticasterBatchListenerTests { * (java.util.List) */ @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { count++; if (error) { throw new RuntimeException("listener error"); @@ -733,7 +734,7 @@ class MulticasterBatchListenerTests { * (java.lang.Exception, java.util.List) */ @Override - public void onWriteError(Exception exception, List items) { + public void onWriteError(Exception exception, Chunk items) { count++; if (error) { throw new RuntimeException("listener error"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java index 44bb58098..4ba08740f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java @@ -52,6 +52,7 @@ import org.springframework.batch.core.annotation.OnReadError; import org.springframework.batch.core.annotation.OnWriteError; import org.springframework.batch.core.configuration.xml.AbstractTestComponent; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.Ordered; import org.springframework.lang.Nullable; @@ -66,6 +67,7 @@ import static org.springframework.batch.core.listener.StepListenerMetaData.AFTER /** * @author Lucas Ward + * @author Mahmoud Ben Hassine * */ class StepListenerFactoryBeanTests { @@ -87,7 +89,7 @@ class StepListenerFactoryBeanTests { // factoryBean.setMetaDataMap(metaDataMap); String readItem = "item"; Integer writeItem = 2; - List writeItems = Arrays.asList(writeItem); + Chunk writeItems = Chunk.of(writeItem); StepListener listener = (StepListener) factoryBean.getObject(); ((StepExecutionListener) listener).beforeStep(stepExecution); ((StepExecutionListener) listener).afterStep(stepExecution); @@ -283,7 +285,7 @@ class StepListenerFactoryBeanTests { factoryBean.setDelegate(delegate); @SuppressWarnings("unchecked") ItemWriteListener listener = (ItemWriteListener) factoryBean.getObject(); - listener.afterWrite(Arrays.asList("foo", "bar")); + listener.afterWrite(Chunk.of("foo", "bar")); assertTrue(delegate.isExecuted()); } @@ -291,16 +293,16 @@ class StepListenerFactoryBeanTests { void testRightSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterWrite - public void aMethod(List items) { + public void aMethod(Chunk chunk) { executed = true; - assertEquals("foo", items.get(0)); - assertEquals("bar", items.get(1)); + assertEquals("foo", chunk.getItems().get(0)); + assertEquals("bar", chunk.getItems().get(1)); } }; factoryBean.setDelegate(delegate); @SuppressWarnings("unchecked") ItemWriteListener listener = (ItemWriteListener) factoryBean.getObject(); - listener.afterWrite(Arrays.asList("foo", "bar")); + listener.afterWrite(Chunk.of("foo", "bar")); assertTrue(delegate.isExecuted()); } @@ -330,7 +332,7 @@ class StepListenerFactoryBeanTests { factoryBean.setMetaDataMap(metaDataMap); @SuppressWarnings("unchecked") ItemWriteListener listener = (ItemWriteListener) factoryBean.getObject(); - listener.afterWrite(Arrays.asList("foo", "bar")); + listener.afterWrite(Chunk.of("foo", "bar")); assertTrue(delegate.isExecuted()); } @@ -338,19 +340,18 @@ class StepListenerFactoryBeanTests { void testRightSignatureNamedMethod() { AbstractTestComponent delegate = new AbstractTestComponent() { @SuppressWarnings("unused") - public void aMethod(List items) { + public void aMethod(Chunk chunk) { executed = true; - assertEquals("foo", items.get(0)); - assertEquals("bar", items.get(1)); + assertEquals("foo", chunk.getItems().get(0)); + assertEquals("bar", chunk.getItems().get(1)); } }; factoryBean.setDelegate(delegate); Map metaDataMap = new HashMap<>(); metaDataMap.put(AFTER_WRITE.getPropertyName(), "aMethod"); factoryBean.setMetaDataMap(metaDataMap); - @SuppressWarnings("unchecked") ItemWriteListener listener = (ItemWriteListener) factoryBean.getObject(); - listener.afterWrite(Arrays.asList("foo", "bar")); + listener.afterWrite(Chunk.of("foo", "bar")); assertTrue(delegate.isExecuted()); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemWriter.java index d142e3219..53b8beab7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/ExampleItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2012 the original author or authors. + * Copyright 2008-2022 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,6 +20,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** @@ -40,12 +42,12 @@ public class ExampleItemWriter implements ItemWriter { } /** - * @see ItemWriter#write(List) + * @see ItemWriter#write(Chunk) */ @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { log.info(data); - items.addAll(data); + items.addAll(data.getItems()); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java index 6cf4256f1..ce5deb721 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/OptimisticLockingFailureTests.java @@ -36,6 +36,7 @@ import org.springframework.batch.core.launch.JobOperator; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.context.ApplicationContext; @@ -109,7 +110,7 @@ class OptimisticLockingFailureTests { public static class Writer implements ItemWriter { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (String item : items) { System.out.println(item); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java index 5add11994..cc0da6966 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/builder/RegisterMultiListenerTests.java @@ -38,6 +38,7 @@ import org.springframework.batch.core.configuration.annotation.JobBuilderFactory import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.NonTransientResourceException; @@ -61,6 +62,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * * @author Tobias Flohre * @author Michael Minella + * @author Mahmoud Ben Hassine */ class RegisterMultiListenerTests { @@ -174,8 +176,8 @@ class RegisterMultiListenerTests { return new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("item2")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("item2")) { throw new MySkippableException(); } } @@ -267,16 +269,16 @@ class RegisterMultiListenerTests { } @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { callChecker.beforeWriteCalled++; } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { } @Override - public void onWriteError(Exception exception, List items) { + public void onWriteError(Exception exception, Chunk items) { } @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java index f9cd6c3f2..7a7165327 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AlmostStatefulRetryChunkTests.java @@ -26,12 +26,15 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.batch.item.Chunk; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class AlmostStatefulRetryChunkTests { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java index c883e59a2..fefd08c95 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ChunkOrientedTaskletTests.java @@ -27,9 +27,11 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.item.Chunk; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class ChunkOrientedTaskletTests { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java index 24d209921..99428a5b8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessorTests.java @@ -36,6 +36,7 @@ import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.listener.ItemListenerSupport; 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; @@ -66,11 +67,11 @@ class FaultTolerantChunkProcessorTests { batchRetryTemplate = new BatchRetryTemplate(); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new RuntimeException("Planned failure!"); } - list.addAll(items); + list.addAll(chunk.getItems()); } }, batchRetryTemplate); batchRetryTemplate.setRetryPolicy(new NeverRetryPolicy()); @@ -193,8 +194,8 @@ class FaultTolerantChunkProcessorTests { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { fail("Expected Error!"); } } @@ -210,8 +211,8 @@ class FaultTolerantChunkProcessorTests { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new RuntimeException("Expected Exception!"); } } @@ -232,8 +233,8 @@ class FaultTolerantChunkProcessorTests { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new RuntimeException("Expected Exception!"); } } @@ -276,8 +277,8 @@ class FaultTolerantChunkProcessorTests { Chunk chunk = new Chunk<>(Arrays.asList("foo", "fail", "bar")); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override - public void afterWrite(List item) { - after.addAll(item); + public void afterWrite(Chunk chunk) { + after.addAll(chunk.getItems()); } })); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -301,18 +302,18 @@ class FaultTolerantChunkProcessorTests { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override - public void write(List items) throws Exception { + public void write(Chunk chunk) throws Exception { // Fail if there is more than one item - if (items.size() > 1) { + if (chunk.size() > 1) { throw new RuntimeException("Planned failure!"); } - list.addAll(items); + list.addAll(chunk.getItems()); } }, batchRetryTemplate); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override - public void afterWrite(List item) { - after.addAll(item); + public void afterWrite(Chunk chunk) { + after.addAll(chunk.getItems()); } })); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -330,8 +331,8 @@ class FaultTolerantChunkProcessorTests { Chunk chunk = new Chunk<>(Arrays.asList("foo", "fail")); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override - public void onWriteError(Exception e, List item) { - writeError.addAll(item); + public void onWriteError(Exception e, Chunk chunk) { + writeError.addAll(chunk.getItems()); } })); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -348,15 +349,15 @@ class FaultTolerantChunkProcessorTests { Chunk chunk = new Chunk<>(Arrays.asList("foo", "bar")); processor = new FaultTolerantChunkProcessor<>(new PassThroughItemProcessor<>(), new ItemWriter() { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { // Always fail in writer throw new RuntimeException("Planned failure!"); } }, batchRetryTemplate); processor.setListeners(Arrays.asList(new ItemListenerSupport() { @Override - public void onWriteError(Exception e, List item) { - writeError.addAll(item); + public void onWriteError(Exception e, Chunk chunk) { + writeError.addAll(chunk.getItems()); } })); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); @@ -376,8 +377,8 @@ class FaultTolerantChunkProcessorTests { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new IllegalArgumentException("Expected Exception!"); } } @@ -408,8 +409,8 @@ class FaultTolerantChunkProcessorTests { processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new IllegalArgumentException("Expected Exception!"); } } @@ -445,11 +446,11 @@ class FaultTolerantChunkProcessorTests { Collections., Boolean>singletonMap(IllegalArgumentException.class, true))); processor.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new IllegalArgumentException("Expected Exception!"); } - if (items.contains("2")) { + if (chunk.getItems().contains("2")) { throw new RuntimeException("Expected Non-Skippable Exception!"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java index e418b747b..b0f87b7ed 100755 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java @@ -28,6 +28,7 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.step.skip.LimitCheckingItemSkipPolicy; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ParseException; import org.springframework.batch.item.UnexpectedInputException; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java index 975335e29..f5c2fbe6d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java @@ -35,6 +35,7 @@ import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.step.JobRepositorySupport; import org.springframework.batch.core.step.factory.FaultTolerantStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.support.ListItemReader; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; @@ -141,7 +142,7 @@ class FaultTolerantStepFactoryBeanNonBufferingTests { } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { logger.debug("Writing: " + items); for (String item : items) { if (failures.contains(item)) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java index 1a90673aa..28e53caaf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java @@ -41,6 +41,7 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; import org.springframework.batch.core.step.AbstractStep; import org.springframework.batch.core.step.factory.FaultTolerantStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; @@ -91,8 +92,8 @@ class FaultTolerantStepFactoryBeanRetryTests { private ItemWriter writer = new ItemWriter() { @Override - public void write(List data) throws Exception { - processed.addAll(data); + public void write(Chunk data) throws Exception { + processed.addAll(data.getItems()); } }; @@ -152,7 +153,7 @@ class FaultTolerantStepFactoryBeanRetryTests { factory.setTransactionManager(new ResourcelessTransactionManager()); ItemWriter failingWriter = new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { int count = 0; for (Integer item : data) { if (count++ == 2) { @@ -202,7 +203,7 @@ class FaultTolerantStepFactoryBeanRetryTests { final List ITEM_LIST = Arrays.asList("a", "b", "c"); ItemWriter failingWriter = new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { int count = 0; for (String item : data) { if (count++ == 2) { @@ -248,7 +249,7 @@ class FaultTolerantStepFactoryBeanRetryTests { void testNoItemsReprocessedWhenErrorInWriterAndProcessorNotTransactional() throws Exception { ItemWriter failingWriter = new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { int count = 0; for (String item : data) { if (count++ == 2) { @@ -358,11 +359,11 @@ class FaultTolerantStepFactoryBeanRetryTests { factory.setStreams(new ItemStream[] { reader }); factory.setItemWriter(new ItemWriter() { @Override - public void write(List items) throws Exception { - if (fail && items.contains("e")) { + public void write(Chunk chunk) throws Exception { + if (fail && chunk.getItems().contains("e")) { throw new RuntimeException("Planned failure"); } - processed.addAll(items); + processed.addAll(chunk.getItems()); } }); factory.setRetryLimit(0); @@ -445,11 +446,11 @@ class FaultTolerantStepFactoryBeanRetryTests { ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - logger.debug("Write Called! Item: [" + item + "]"); - processed.addAll(item); - written.addAll(item); - if (item.contains("b") || item.contains("d")) { + public void write(Chunk chunk) throws Exception { + logger.debug("Write Called! Item: [" + chunk.getItems() + "]"); + processed.addAll(chunk.getItems()); + written.addAll(chunk.getItems()); + if (chunk.getItems().contains("b") || chunk.getItems().contains("d")) { throw new RuntimeException("Write error - planned but recoverable."); } } @@ -503,11 +504,11 @@ class FaultTolerantStepFactoryBeanRetryTests { ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - logger.debug("Write Called! Item: [" + item + "]"); - processed.addAll(item); - written.addAll(item); - if (item.contains("b") || item.contains("d")) { + public void write(Chunk chunk) throws Exception { + logger.debug("Write Called! Item: [" + chunk + "]"); + processed.addAll(chunk.getItems()); + written.addAll(chunk.getItems()); + if (chunk.getItems().contains("b") || chunk.getItems().contains("d")) { throw new RuntimeException("Write error - planned but recoverable."); } } @@ -556,10 +557,10 @@ class FaultTolerantStepFactoryBeanRetryTests { }; ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - processed.addAll(item); - written.addAll(item); - logger.debug("Write Called! Item: [" + item + "]"); + public void write(Chunk chunk) throws Exception { + processed.addAll(chunk.getItems()); + written.addAll(chunk.getItems()); + logger.debug("Write Called! Item: [" + chunk.getItems() + "]"); throw new RuntimeException("Write error - planned but retryable."); } }; @@ -608,10 +609,10 @@ class FaultTolerantStepFactoryBeanRetryTests { }; ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - processed.addAll(item); - written.addAll(item); - logger.debug("Write Called! Item: [" + item + "]"); + public void write(Chunk chunk) throws Exception { + processed.addAll(chunk.getItems()); + written.addAll(chunk.getItems()); + logger.debug("Write Called! Item: [" + chunk.getItems() + "]"); throw new RuntimeException("Write error - planned but not skippable."); } }; @@ -655,10 +656,10 @@ class FaultTolerantStepFactoryBeanRetryTests { }; ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - processed.addAll(item); - written.addAll(item); - logger.debug("Write Called! Item: [" + item + "]"); + public void write(Chunk chunk) throws Exception { + processed.addAll(chunk.getItems()); + written.addAll(chunk.getItems()); + logger.debug("Write Called! Item: [" + chunk.getItems() + "]"); throw new RuntimeException("Write error - planned but retryable."); } }; @@ -707,9 +708,9 @@ class FaultTolerantStepFactoryBeanRetryTests { }; ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { - processed.addAll(item); - logger.debug("Write Called! Item: [" + item + "]"); + public void write(Chunk chunk) throws Exception { + processed.addAll(chunk.getItems()); + logger.debug("Write Called! Item: [" + chunk.getItems() + "]"); throw new RuntimeException("Write error - planned but retryable."); } }; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java index abfeef5cf..1bbfd40d8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanTests.java @@ -49,6 +49,7 @@ 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; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemStream; @@ -451,7 +452,7 @@ public class FaultTolerantStepFactoryBeanTests { factory.setSkippableExceptionClasses(map); factory.setItemWriter(new ItemWriter() { @Override - public void write(List items) { + public void write(Chunk items) { throw new FatalRuntimeException("Ouch!"); } }); @@ -766,8 +767,8 @@ public class FaultTolerantStepFactoryBeanTests { ItemProcessListener, SkipListener, ChunkListener { @Override - public void write(List items) throws Exception { - if (items.contains("4")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("4")) { throw new SkippableException("skippable"); } } @@ -786,16 +787,16 @@ public class FaultTolerantStepFactoryBeanTests { } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { listenerCalls.add(2); } @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { } @Override - public void onWriteError(Exception exception, List items) { + public void onWriteError(Exception exception, Chunk items) { } @Override diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java index 3b86a7bcf..36363302f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/ScriptItemProcessorTests.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Test; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -33,6 +34,7 @@ import java.util.List; *

* * @author Chris Schaefer + * @author Mahmoud Ben Hassine * @since 3.1 */ @SpringJUnitConfig @@ -52,12 +54,12 @@ class ScriptItemProcessorTests { public static class TestItemWriter implements ItemWriter { @Override - public void write(List items) throws Exception { - Assert.notNull(items, "Items cannot be null"); - Assert.isTrue(!items.isEmpty(), "Items cannot be empty"); - Assert.isTrue(items.size() == 1, "Items should only contain one entry"); + public void write(Chunk chunk) throws Exception { + Assert.notNull(chunk.getItems(), "Items cannot be null"); + Assert.isTrue(!chunk.getItems().isEmpty(), "Items cannot be empty"); + Assert.isTrue(chunk.getItems().size() == 1, "Items should only contain one entry"); - String item = items.get(0); + String item = chunk.getItems().get(0); Assert.isTrue("BLAH".equals(item), "Transformed item to write should have been: BLAH but got: " + item); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java index 7b1f48779..85b92b857 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProcessorTests.java @@ -28,6 +28,7 @@ import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.lang.Nullable; @@ -46,11 +47,11 @@ class SimpleChunkProcessorTests { } }, new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains("fail")) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains("fail")) { throw new RuntimeException("Planned failure!"); } - list.addAll(items); + list.addAll(chunk.getItems()); } }); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java index b4161133c..eb5f4196d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java @@ -26,6 +26,7 @@ import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.support.ListItemReader; import org.springframework.batch.repeat.support.RepeatTemplate; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java index 0e2a3ef56..a85f0c043 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleStepFactoryBeanTests.java @@ -46,6 +46,7 @@ import org.springframework.batch.core.repository.support.JobRepositoryFactoryBea import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.AbstractStep; import org.springframework.batch.core.step.factory.SimpleStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -72,8 +73,8 @@ class SimpleStepFactoryBeanTests { private final ItemWriter writer = new ItemWriter() { @Override - public void write(List data) throws Exception { - written.addAll(data); + public void write(Chunk data) throws Exception { + written.addAll(data.getItems()); } }; @@ -174,7 +175,7 @@ class SimpleStepFactoryBeanTests { factory.setItemWriter(new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { throw new RuntimeException("Error!"); } }); @@ -185,7 +186,7 @@ class SimpleStepFactoryBeanTests { } @Override - public void onWriteError(Exception ex, List item) { + public void onWriteError(Exception ex, Chunk item) { listened.add(ex); } } }); @@ -212,7 +213,7 @@ class SimpleStepFactoryBeanTests { factory.setBeanName("exceptionStep"); factory.setItemWriter(new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { throw new RuntimeException("Foo"); } }); @@ -237,7 +238,7 @@ class SimpleStepFactoryBeanTests { int count = 0; @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { if (count++ == 0) { throw new RuntimeException("Foo"); } @@ -264,8 +265,8 @@ class SimpleStepFactoryBeanTests { String trail = ""; @Override - public void beforeWrite(List items) { - if (items.contains("error")) { + public void beforeWrite(Chunk chunk) { + if (chunk.getItems().contains("error")) { throw new RuntimeException("rollback the last chunk"); } @@ -273,7 +274,7 @@ class SimpleStepFactoryBeanTests { } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { trail = trail + "3"; } @@ -379,7 +380,7 @@ class SimpleStepFactoryBeanTests { ItemWriteListener, ItemProcessListener, ChunkListener { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { } @Nullable @@ -402,16 +403,16 @@ class SimpleStepFactoryBeanTests { } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { listenerCalls.add("write"); } @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { } @Override - public void onWriteError(Exception exception, List items) { + public void onWriteError(Exception exception, Chunk items) { } @Override @@ -470,20 +471,20 @@ class SimpleStepFactoryBeanTests { class TestItemListenerWriter implements ItemWriter, ItemWriteListener { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { } @Override - public void afterWrite(List items) { + public void afterWrite(Chunk items) { listenerCalls.add("write"); } @Override - public void beforeWrite(List items) { + public void beforeWrite(Chunk items) { } @Override - public void onWriteError(Exception exception, List items) { + public void onWriteError(Exception exception, Chunk items) { } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java index 32a3cf667..9b024669b 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWrapperTests.java @@ -21,8 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.SkipWrapper; + /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class SkipWrapperTests { @@ -41,7 +44,7 @@ class SkipWrapperTests { /** * Test method for - * {@link org.springframework.batch.core.step.item.SkipWrapper#SkipWrapper(java.lang.Object, java.lang.Throwable)}. + * {@link SkipWrapper#SkipWrapper(java.lang.Object, java.lang.Throwable)}. */ @Test void testItemWrapperTException() { @@ -51,8 +54,7 @@ class SkipWrapperTests { } /** - * Test method for - * {@link org.springframework.batch.core.step.item.SkipWrapper#toString()}. + * Test method for {@link SkipWrapper#toString()}. */ @Test void testToString() { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWriterStub.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWriterStub.java index f02d2c777..aafad502c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWriterStub.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SkipWriterStub.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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,11 +18,13 @@ package org.springframework.batch.core.step.item; import java.util.ArrayList; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.support.transaction.TransactionAwareProxyFactory; /** * @author Dan Garrette + * @author Mahmoud Ben Hassine * @since 2.0.1 */ public class SkipWriterStub extends AbstractExceptionThrowingItemHandlerStub implements ItemWriter { @@ -49,7 +51,7 @@ public class SkipWriterStub extends AbstractExceptionThrowingItemHandlerStub< } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { logger.debug("Writing: " + items); for (T item : items) { written.add(item); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java index ea4bce0a5..d5dd29b9e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/skip/ReprocessExceptionTests.java @@ -21,6 +21,7 @@ import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; @@ -33,6 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mminella + * @author Mahmoud Ben Hassine */ @SpringJUnitConfig public class ReprocessExceptionTests { @@ -77,7 +79,7 @@ public class ReprocessExceptionTests { public static class PersonItemWriter implements ItemWriter { @Override - public void write(List persons) throws Exception { + public void write(Chunk persons) throws Exception { for (Person person : persons) { System.out.println(person.getFirstName() + " " + person.getLastName()); if (person.getFirstName().equals("JANE")) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java index f117d7395..ab36006e0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncChunkOrientedStepIntegrationTests.java @@ -34,6 +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; @@ -53,6 +54,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ @SpringJUnitConfig(locations = "/org/springframework/batch/core/repository/dao/sql-dao-test.xml") @@ -125,8 +127,8 @@ class AsyncChunkOrientedStepIntegrationTests { getReader(new String[] { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c" }), new ItemWriter() { @Override - public void write(List data) throws Exception { - written.addAll(data); + public void write(Chunk data) throws Exception { + written.addAll(data.getItems()); } }, chunkOperations)); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java index f81e3d23b..949701941 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/AsyncTaskletStepTests.java @@ -33,6 +33,7 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.JobRepositorySupport; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemStreamSupport; @@ -59,11 +60,11 @@ class AsyncTaskletStepTests { ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { // Thread.sleep(100L); logger.info("Items: " + data); - processed.addAll(data); - if (data.contains("fail")) { + processed.addAll(data.getItems()); + if (data.getItems().contains("fail")) { throw new RuntimeException("Planned"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java index 384b89f6f..ee82396cf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java @@ -37,6 +37,7 @@ 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; @@ -88,7 +89,7 @@ class StepExecutorInterruptionTests { step.setTransactionManager(this.transactionManager); itemWriter = new ItemWriter() { @Override - public void write(List item) throws Exception { + public void write(Chunk item) throws Exception { } }; stepExecution = new StepExecution(step.getName(), jobExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java index 36492f980..ca57da591 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java @@ -45,6 +45,7 @@ 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; @@ -75,8 +76,8 @@ class TaskletStepTests { ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List data) throws Exception { - processed.addAll(data); + public void write(Chunk data) throws Exception { + processed.addAll(data.getItems()); } }; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcGameDao.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcGameDao.java index 7bdbd9e65..ad0bcb9bd 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcGameDao.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcGameDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.core.test.football.internal; import java.util.List; import org.springframework.batch.core.test.football.domain.Game; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; @@ -38,7 +39,7 @@ public class JdbcGameDao extends JdbcDaoSupport implements ItemWriter { } @Override - public void write(List games) { + public void write(Chunk games) { for (Game game : games) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcPlayerSummaryDao.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcPlayerSummaryDao.java index 062e058fd..83948e099 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcPlayerSummaryDao.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/JdbcPlayerSummaryDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.core.test.football.internal; import java.util.List; import org.springframework.batch.core.test.football.domain.PlayerSummary; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @@ -35,7 +36,7 @@ public class JdbcPlayerSummaryDao implements ItemWriter { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override - public void write(List summaries) { + public void write(Chunk summaries) { for (PlayerSummary summary : summaries) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/PlayerItemWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/PlayerItemWriter.java index fd83d6ea2..38df58995 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/PlayerItemWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/football/internal/PlayerItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +20,7 @@ import java.util.List; import org.springframework.batch.core.test.football.domain.Player; import org.springframework.batch.core.test.football.domain.PlayerDao; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; public class PlayerItemWriter implements ItemWriter { @@ -27,7 +28,7 @@ public class PlayerItemWriter implements ItemWriter { private PlayerDao playerDao; @Override - public void write(List players) throws Exception { + public void write(Chunk players) throws Exception { for (Player player : players) { playerDao.savePlayer(player); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java index 946f578b0..16201a713 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanIntegrationTests.java @@ -39,6 +39,7 @@ import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.factory.FaultTolerantStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -111,7 +112,7 @@ class FaultTolerantStepFactoryBeanIntegrationTests { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - writer.write(Arrays.asList("foo", "bar")); + writer.write(Chunk.of("foo", "bar")); processor.process("spam"); assertEquals(3, JdbcTestUtils.countRowsInTable(jdbcTemplate, "ERROR_LOG")); @@ -228,7 +229,7 @@ class FaultTolerantStepFactoryBeanIntegrationTests { } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (String item : items) { written.add(item); jdbcTemplate.update("INSERT INTO ERROR_LOG (MESSAGE, STEP_NAME) VALUES (?, ?)", item, "written"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java index ddffda568..080d6e053 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepFactoryBeanRollbackIntegrationTests.java @@ -39,6 +39,7 @@ import org.springframework.batch.core.Step; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.factory.FaultTolerantStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -108,7 +109,7 @@ class FaultTolerantStepFactoryBeanRollbackIntegrationTests { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); - writer.write(Arrays.asList("foo", "bar")); + writer.write(Chunk.of("foo", "bar")); processor.process("spam"); assertEquals(3, JdbcTestUtils.countRowsInTable(jdbcTemplate, "ERROR_LOG")); @@ -253,7 +254,7 @@ class FaultTolerantStepFactoryBeanRollbackIntegrationTests { } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (String item : items) { written.add(item); jdbcTemplate.update("INSERT INTO ERROR_LOG (MESSAGE, STEP_NAME) VALUES (?, ?)", item, "written"); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java index 08513018f..14611d328 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/step/FaultTolerantStepIntegrationTests.java @@ -35,6 +35,7 @@ import org.springframework.batch.core.step.builder.FaultTolerantStepBuilder; import org.springframework.batch.core.step.skip.AlwaysSkipItemSkipPolicy; 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.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -71,7 +72,7 @@ class FaultTolerantStepIntegrationTests { void setUp() { ItemReader itemReader = new ListItemReader<>(createItems()); ItemWriter itemWriter = chunk -> { - if (chunk.contains(1)) { + if (chunk.getItems().contains(1)) { throw new IllegalArgumentException(); } }; @@ -169,7 +170,7 @@ class FaultTolerantStepIntegrationTests { private int cpt; @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { cpt++; if (cpt == 1) { throw new Exception("Error during write"); @@ -210,8 +211,8 @@ class FaultTolerantStepIntegrationTests { ItemWriter itemWriter = new ItemWriter() { @Override - public void write(List items) throws Exception { - if (items.contains(3)) { + public void write(Chunk chunk) throws Exception { + if (chunk.getItems().contains(3)) { throw new Exception("Error during write"); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/LoggingItemWriter.java b/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/LoggingItemWriter.java index 43904fc25..3a4ef2de3 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/LoggingItemWriter.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/test/timeout/LoggingItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; public class LoggingItemWriter implements ItemWriter { @@ -26,7 +28,7 @@ public class LoggingItemWriter implements ItemWriter { protected Log logger = LogFactory.getLog(LoggingItemWriter.class); @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { logger.info(items); } diff --git a/spring-batch-docs/src/main/asciidoc/common-patterns.adoc b/spring-batch-docs/src/main/asciidoc/common-patterns.adoc index 30a116a64..f59e840bd 100644 --- a/spring-batch-docs/src/main/asciidoc/common-patterns.adoc +++ b/spring-batch-docs/src/main/asciidoc/common-patterns.adoc @@ -277,7 +277,7 @@ public class TradeItemWriter implements ItemWriter, private BigDecimal totalAmount = BigDecimal.ZERO; - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { BigDecimal chunkTotal = BigDecimal.ZERO; for (Trade trade : items) { chunkTotal = chunkTotal.add(trade.getAmount()); @@ -665,7 +665,7 @@ then it is not persisted during `Step` execution. If the `Step` fails, that data public class SavingItemWriter implements ItemWriter { private StepExecution stepExecution; - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { // ... ExecutionContext stepContext = this.stepExecution.getExecutionContext(); @@ -759,7 +759,7 @@ in the following example: public class RetrievingItemWriter implements ItemWriter { private Object someObject; - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { // ... } diff --git a/spring-batch-docs/src/main/asciidoc/processor.adoc b/spring-batch-docs/src/main/asciidoc/processor.adoc index 8c3351241..c4e08f1fd 100644 --- a/spring-batch-docs/src/main/asciidoc/processor.adoc +++ b/spring-batch-docs/src/main/asciidoc/processor.adoc @@ -25,7 +25,7 @@ public class CompositeItemWriter implements ItemWriter { this.itemWriter = itemWriter; } - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { //Add business logic here itemWriter.write(items); } @@ -77,7 +77,7 @@ public class FooProcessor implements ItemProcessor { } public class BarWriter implements ItemWriter { - public void write(List bars) throws Exception { + public void write(Chunk bars) throws Exception { //write bars } } @@ -162,7 +162,7 @@ public class BarProcessor implements ItemProcessor { } public class FoobarWriter implements ItemWriter{ - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { //write items } } diff --git a/spring-batch-docs/src/main/asciidoc/readersAndWriters.adoc b/spring-batch-docs/src/main/asciidoc/readersAndWriters.adoc index ce60b65e0..d2d0cbceb 100644 --- a/spring-batch-docs/src/main/asciidoc/readersAndWriters.adoc +++ b/spring-batch-docs/src/main/asciidoc/readersAndWriters.adoc @@ -78,7 +78,7 @@ As with `ItemReader`, ---- public interface ItemWriter { - void write(List items) throws Exception; + void write(Chunk items) throws Exception; } ---- @@ -2732,7 +2732,7 @@ public class CustomItemWriter implements ItemWriter { List output = TransactionAwareProxyFactory.createTransactionalList(); - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { output.addAll(items); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/Chunk.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java similarity index 86% rename from spring-batch-core/src/main/java/org/springframework/batch/core/step/item/Chunk.java rename to spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java index 9fa7f4682..5e778ac62 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/Chunk.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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. @@ -14,9 +14,11 @@ * limitations under the License. */ -package org.springframework.batch.core.step.item; +package org.springframework.batch.item; +import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -26,13 +28,14 @@ import java.util.List; * Encapsulation of a list of items to be processed and possibly a list of failed items to * be skipped. To mark an item as skipped clients should iterate over the chunk using the * {@link #iterator()} method, and if there is a failure call - * {@link org.springframework.batch.core.step.item.Chunk.ChunkIterator#remove()} on the - * iterator. The skipped items are then available through the chunk. + * {@link Chunk.ChunkIterator#remove()} on the iterator. The skipped items are then + * available through the chunk. * * @author Dave Syer + * @author Mahmoud Ben Hassine * @since 2.0 */ -public class Chunk implements Iterable { +public class Chunk implements Iterable, Serializable { private List items = new ArrayList<>(); @@ -46,15 +49,19 @@ public class Chunk implements Iterable { private boolean busy; - public Chunk() { - this(null, null); + public Chunk(W... items) { + this(Arrays.stream(items).toList()); } - public Chunk(Collection items) { + public static Chunk of(W... items) { + return new Chunk<>(items); + } + + public Chunk(List items) { this(items, null); } - public Chunk(Collection items, List> skips) { + public Chunk(List items, List> skips) { super(); if (items != null) { this.items = new ArrayList<>(items); @@ -72,6 +79,14 @@ public class Chunk implements Iterable { items.add(item); } + /** + * Add all items to the chunk. + * @param items the items to add + */ + public void addAll(List items) { + this.items.addAll(items); + } + /** * Clear the items down to signal that we are done. */ diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ItemWriter.java index c5af2028d..005535103 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ItemWriter.java @@ -18,6 +18,8 @@ package org.springframework.batch.item; import java.util.List; +import org.springframework.lang.NonNull; + /** *

* Basic interface for generic output operations. Class implementing this interface will @@ -36,6 +38,7 @@ import java.util.List; * @author Dave Syer * @author Lucas Ward * @author Taeik Lim + * @author Mahmoud Ben Hassine */ @FunctionalInterface public interface ItemWriter { @@ -43,10 +46,10 @@ public interface ItemWriter { /** * Process the supplied data element. Will not be called with any null items in normal * operation. - * @param items items to be written + * @param chunk of items to be written. Must not be {@code null}. * @throws Exception if there are errors. The framework will catch the exception and * convert or rethrow it as appropriate. */ - void write(List items) throws Exception; + void write(@NonNull Chunk chunk) throws Exception; } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/KeyValueItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/KeyValueItemWriter.java index ecf42abf2..1b5997f13 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/KeyValueItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/KeyValueItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2021 the original author or authors. + * Copyright 2002-2022 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. You may obtain a copy of the License at @@ -23,6 +23,7 @@ import org.springframework.util.Assert; * a {@link Converter} to derive a key from an item * * @author David Turanski + * @author Mahmoud Ben Hassine * @since 2.2 * */ @@ -38,7 +39,7 @@ public abstract class KeyValueItemWriter implements ItemWriter, Initial * @see org.springframework.batch.item.ItemWriter#write(java.util.List) */ @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { if (items == null) { return; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SkipWrapper.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/SkipWrapper.java similarity index 93% rename from spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SkipWrapper.java rename to spring-batch-infrastructure/src/main/java/org/springframework/batch/item/SkipWrapper.java index 2ad4eac4b..41b5dd977 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/SkipWrapper.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/SkipWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-2022 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. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.batch.core.step.item; +package org.springframework.batch.item; import org.springframework.lang.Nullable; diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/ItemWriterAdapter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/ItemWriterAdapter.java index 384065e21..3abd77124 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/ItemWriterAdapter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/ItemWriterAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.item.adapter; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** @@ -26,11 +27,12 @@ import org.springframework.batch.item.ItemWriter; * * @see PropertyExtractingDelegatingItemWriter * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class ItemWriterAdapter extends AbstractMethodInvokingDelegator implements ItemWriter { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (T item : items) { invokeDelegateMethodWithArgument(item); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java index 58da807d1..609d6f3d0 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.item.adapter; import java.util.Arrays; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; @@ -30,6 +31,7 @@ import org.springframework.util.Assert; * * @see ItemWriterAdapter * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class PropertyExtractingDelegatingItemWriter extends AbstractMethodInvokingDelegator implements ItemWriter { @@ -41,7 +43,7 @@ public class PropertyExtractingDelegatingItemWriter extends AbstractMethodInv * passes them as arguments to the delegate method. */ @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (T item : items) { // helper for extracting property values from a bean diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/amqp/AmqpItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/amqp/AmqpItemWriter.java index 399040de2..9a2b8f975 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/amqp/AmqpItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/amqp/AmqpItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.item.amqp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.util.Assert; @@ -47,7 +48,7 @@ public class AmqpItemWriter implements ItemWriter { } @Override - public void write(final List items) throws Exception { + public void write(final Chunk items) throws Exception { if (log.isDebugEnabled()) { log.debug("Writing to AMQP with " + items.size() + " items."); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/avro/AvroItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/avro/AvroItemWriter.java index 66ade7282..1e791bd22 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/avro/AvroItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/avro/AvroItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2019-2021 the original author or authors. + * Copyright 2019-2022 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,6 +31,7 @@ import org.apache.avro.reflect.ReflectDatumWriter; import org.apache.avro.specific.SpecificDatumWriter; import org.apache.avro.specific.SpecificRecordBase; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.ItemWriter; @@ -84,7 +85,7 @@ public class AvroItemWriter extends AbstractItemStreamItemWriter { } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { items.forEach(item -> { try { if (this.dataFileWriter != null) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/MongoItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/MongoItemWriter.java index 85fff8b46..cff4fce4b 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/MongoItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/MongoItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2022 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. @@ -22,6 +22,7 @@ import java.util.List; import org.bson.Document; import org.bson.types.ObjectId; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; import org.springframework.data.mongodb.core.BulkOperations; @@ -113,39 +114,39 @@ public class MongoItemWriter implements ItemWriter, InitializingBean { * If a transaction is active, buffer items to be written just before commit. * Otherwise write items using the provided template. * - * @see org.springframework.batch.item.ItemWriter#write(List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) throws Exception { + public void write(Chunk chunk) throws Exception { if (!transactionActive()) { - doWrite(items); + doWrite(chunk); return; } - List bufferedItems = getCurrentBuffer(); - bufferedItems.addAll(items); + Chunk bufferedItems = getCurrentBuffer(); + bufferedItems.addAll(chunk.getItems()); } /** * Performs the actual write to the store via the template. This can be overridden by * a subclass if necessary. - * @param items the list of items to be persisted. + * @param chunk the chunk of items to be persisted. */ - protected void doWrite(List items) { - if (!CollectionUtils.isEmpty(items)) { + protected void doWrite(Chunk chunk) { + if (!CollectionUtils.isEmpty(chunk.getItems())) { if (this.delete) { - delete(items); + delete(chunk); } else { - saveOrUpdate(items); + saveOrUpdate(chunk); } } } - private void delete(List items) { - BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, items.get(0)); + private void delete(Chunk chunk) { + BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, chunk.getItems().get(0)); MongoConverter mongoConverter = this.template.getConverter(); - for (Object item : items) { + for (Object item : chunk) { Document document = new Document(); mongoConverter.write(item, document); Object objectId = document.get(ID_KEY); @@ -157,11 +158,11 @@ public class MongoItemWriter implements ItemWriter, InitializingBean { bulkOperations.execute(); } - private void saveOrUpdate(List items) { - BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, items.get(0)); + private void saveOrUpdate(Chunk chunk) { + BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, chunk.getItems().get(0)); MongoConverter mongoConverter = this.template.getConverter(); FindAndReplaceOptions upsert = new FindAndReplaceOptions().upsert(); - for (Object item : items) { + for (Object item : chunk) { Document document = new Document(); mongoConverter.write(item, document); Object objectId = document.get(ID_KEY) != null ? document.get(ID_KEY) : new ObjectId(); @@ -186,19 +187,18 @@ public class MongoItemWriter implements ItemWriter, InitializingBean { return TransactionSynchronizationManager.isActualTransactionActive(); } - @SuppressWarnings("unchecked") - private List getCurrentBuffer() { + private Chunk getCurrentBuffer() { if (!TransactionSynchronizationManager.hasResource(bufferKey)) { - TransactionSynchronizationManager.bindResource(bufferKey, new ArrayList()); + TransactionSynchronizationManager.bindResource(bufferKey, new Chunk()); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override public void beforeCommit(boolean readOnly) { - List items = (List) TransactionSynchronizationManager.getResource(bufferKey); + Chunk chunk = (Chunk) TransactionSynchronizationManager.getResource(bufferKey); - if (!CollectionUtils.isEmpty(items)) { + if (!CollectionUtils.isEmpty(chunk.getItems())) { if (!readOnly) { - doWrite(items); + doWrite(chunk); } } } @@ -212,7 +212,7 @@ public class MongoItemWriter implements ItemWriter, InitializingBean { }); } - return (List) TransactionSynchronizationManager.getResource(bufferKey); + return (Chunk) TransactionSynchronizationManager.getResource(bufferKey); } @Override diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/Neo4jItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/Neo4jItemWriter.java index 6d6f826f9..75316655d 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/Neo4jItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/Neo4jItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2021 the original author or authors. + * Copyright 2012-2022 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. @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; @@ -86,12 +87,12 @@ public class Neo4jItemWriter implements ItemWriter, InitializingBean { /** * Write all items to the data store. * - * @see org.springframework.batch.item.ItemWriter#write(java.util.List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) throws Exception { - if (!CollectionUtils.isEmpty(items)) { - doWrite(items); + public void write(Chunk chunk) throws Exception { + if (!CollectionUtils.isEmpty(chunk.getItems())) { + doWrite(chunk); } } @@ -100,7 +101,7 @@ public class Neo4jItemWriter implements ItemWriter, InitializingBean { * if necessary. * @param items the list of items to be persisted. */ - protected void doWrite(List items) { + protected void doWrite(Chunk items) { if (delete) { delete(items); } @@ -109,7 +110,7 @@ public class Neo4jItemWriter implements ItemWriter, InitializingBean { } } - private void delete(List items) { + private void delete(Chunk items) { Session session = this.sessionFactory.openSession(); for (T item : items) { @@ -117,7 +118,7 @@ public class Neo4jItemWriter implements ItemWriter, InitializingBean { } } - private void save(List items) { + private void save(Chunk items) { Session session = this.sessionFactory.openSession(); for (T item : items) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemWriter.java index 808b33270..4ce7c96e4 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 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,6 +20,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.adapter.AbstractMethodInvokingDelegator.InvocationTargetThrowableWrapper; import org.springframework.batch.item.adapter.DynamicMethodInvocationException; @@ -87,12 +89,12 @@ public class RepositoryItemWriter implements ItemWriter, InitializingBean /** * Write all items to the data store via a Spring Data repository. * - * @see org.springframework.batch.item.ItemWriter#write(java.util.List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) throws Exception { - if (!CollectionUtils.isEmpty(items)) { - doWrite(items); + public void write(Chunk chunk) throws Exception { + if (!CollectionUtils.isEmpty(chunk.getItems())) { + doWrite(chunk); } } @@ -102,7 +104,7 @@ public class RepositoryItemWriter implements ItemWriter, InitializingBean * @param items the list of items to be persisted. * @throws Exception thrown if error occurs during writing. */ - protected void doWrite(List items) throws Exception { + protected void doWrite(Chunk items) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Writing to the repository with " + items.size() + " items."); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/HibernateItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/HibernateItemWriter.java index f9b621804..4ca03a6cb 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/HibernateItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/HibernateItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -23,6 +23,7 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.context.spi.CurrentSessionContext; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; @@ -81,10 +82,10 @@ public class HibernateItemWriter implements ItemWriter, InitializingBean { * Save or update any entities not in the current hibernate session and then flush the * hibernate session. * - * @see org.springframework.batch.item.ItemWriter#write(java.util.List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) { + public void write(Chunk items) { doWrite(sessionFactory, items); sessionFactory.getCurrentSession().flush(); if (clearSession) { @@ -98,7 +99,7 @@ public class HibernateItemWriter implements ItemWriter, InitializingBean { * @param sessionFactory Hibernate SessionFactory to be used * @param items the list of items to use for the write */ - protected void doWrite(SessionFactory sessionFactory, List items) { + protected void doWrite(SessionFactory sessionFactory, Chunk items) { if (logger.isDebugEnabled()) { logger.debug("Writing to Hibernate with " + items.size() + " items."); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java index 9e19791f6..d98e950bb 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JdbcBatchItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,6 +25,7 @@ import javax.sql.DataSource; import org.apache.commons.logging.Log; 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; @@ -51,7 +52,7 @@ import org.springframework.util.Assert; * be responsible for mapping the item to the parameters needed to execute the SQL * statement.
* - * It is expected that {@link #write(List)} is called inside a transaction.
+ * It is expected that {@link #write(Chunk)} is called inside a transaction.
* * The writer is thread-safe after its properties are set (normal singleton behavior), so * it can be used to write in multiple concurrent transactions. @@ -59,6 +60,7 @@ import org.springframework.util.Assert; * @author Dave Syer * @author Thomas Risberg * @author Michael Minella + * @author Mahmoud Ben Hassine * @since 2.0 */ public class JdbcBatchItemWriter implements ItemWriter, InitializingBean { @@ -164,24 +166,25 @@ public class JdbcBatchItemWriter implements ItemWriter, InitializingBean { */ @SuppressWarnings("unchecked") @Override - public void write(final List items) throws Exception { + public void write(final Chunk chunk) throws Exception { - if (!items.isEmpty()) { + if (!chunk.isEmpty()) { if (logger.isDebugEnabled()) { - logger.debug("Executing batch with " + items.size() + " items."); + logger.debug("Executing batch with " + chunk.size() + " items."); } int[] updateCounts; if (usingNamedParameters) { - if (items.get(0) instanceof Map && this.itemSqlParameterSourceProvider == null) { - updateCounts = namedParameterJdbcTemplate.batchUpdate(sql, items.toArray(new Map[items.size()])); + if (chunk.getItems().get(0) instanceof Map && this.itemSqlParameterSourceProvider == null) { + updateCounts = namedParameterJdbcTemplate.batchUpdate(sql, + chunk.getItems().toArray(new Map[chunk.size()])); } else { - SqlParameterSource[] batchArgs = new SqlParameterSource[items.size()]; + SqlParameterSource[] batchArgs = new SqlParameterSource[chunk.size()]; int i = 0; - for (T item : items) { + for (T item : chunk) { batchArgs[i++] = itemSqlParameterSourceProvider.createSqlParameterSource(item); } updateCounts = namedParameterJdbcTemplate.batchUpdate(sql, batchArgs); @@ -193,7 +196,7 @@ public class JdbcBatchItemWriter implements ItemWriter, InitializingBean { @Override public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { - for (T item : items) { + for (T item : chunk) { itemPreparedStatementSetter.setValues(item, ps); ps.addBatch(); } @@ -207,7 +210,7 @@ public class JdbcBatchItemWriter implements ItemWriter, InitializingBean { int value = updateCounts[i]; if (value == 0) { throw new EmptyResultDataAccessException("Item " + i + " of " + updateCounts.length - + " did not update any rows: [" + items.get(i) + "]", 1); + + " did not update any rows: [" + chunk.getItems().get(i) + "]", 1); } } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JpaItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JpaItemWriter.java index 8ca7b0c01..d526af59a 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JpaItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/JpaItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,6 +18,8 @@ package org.springframework.batch.item.database; import org.apache.commons.logging.Log; 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.DataAccessResourceFailureException; @@ -32,7 +34,7 @@ import java.util.List; * {@link org.springframework.batch.item.ItemWriter} that is using a JPA * EntityManagerFactory to merge any Entities that aren't part of the persistence context. * - * It is required that {@link #write(List)} is called inside a transaction.
+ * It is required that {@link #write(Chunk)} is called inside a transaction.
* * The reader must be configured with an {@link jakarta.persistence.EntityManagerFactory} * that is capable of participating in Spring managed transactions. @@ -80,10 +82,10 @@ public class JpaItemWriter implements ItemWriter, InitializingBean { * Merge all provided items that aren't already in the persistence context and then * flush the entity manager. * - * @see org.springframework.batch.item.ItemWriter#write(java.util.List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) { + public void write(Chunk items) { EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory); if (entityManager == null) { throw new DataAccessResourceFailureException("Unable to obtain a transactional EntityManager"); @@ -98,7 +100,7 @@ public class JpaItemWriter implements ItemWriter, InitializingBean { * @param entityManager the EntityManager to use for the operation * @param items the list of items to use for the write */ - protected void doWrite(EntityManager entityManager, List items) { + protected void doWrite(EntityManager entityManager, Chunk items) { if (logger.isDebugEnabled()) { logger.debug("Writing to JPA with " + items.size() + " items."); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/FlatFileItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/FlatFileItemWriter.java index 2202d52af..520b41d31 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/FlatFileItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/FlatFileItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.item.file; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.file.transform.LineAggregator; import org.springframework.batch.item.support.AbstractFileItemWriter; import org.springframework.core.io.Resource; @@ -71,7 +72,7 @@ public class FlatFileItemWriter extends AbstractFileItemWriter { } @Override - public String doWrite(List items) { + public String doWrite(Chunk items) { StringBuilder lines = new StringBuilder(); for (T item : items) { lines.append(this.lineAggregator.aggregate(item)).append(this.lineSeparator); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemWriter.java index 776dd217b..65f72a925 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2017 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ package org.springframework.batch.item.file; import java.io.File; import java.io.IOException; import java.util.List; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.support.AbstractItemStreamItemWriter; @@ -39,6 +41,7 @@ import org.springframework.util.ClassUtils; * * @param item type * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class MultiResourceItemWriter extends AbstractItemStreamItemWriter { @@ -67,7 +70,7 @@ public class MultiResourceItemWriter extends AbstractItemStreamItemWriter } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { if (!opened) { File file = setResourceToDelegate(); // create only if write is called diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemWriter.java index 934963e95..90f95cff5 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,8 @@ package org.springframework.batch.item.jms; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.jms.core.JmsOperations; import org.springframework.jms.core.JmsTemplate; @@ -27,13 +29,14 @@ import java.util.List; /** * An {@link ItemWriter} for JMS using a {@link JmsTemplate}. The template should have a - * default destination, which will be used to send items in {@link #write(List)}.
+ * default destination, which will be used to send items in {@link #write(Chunk)}.
*
* * The implementation is thread-safe after its properties are set (normal singleton * behavior). * * @author Dave Syer + * @author Mahmoud Ben Hassine * */ public class JmsItemWriter implements ItemWriter { @@ -58,10 +61,10 @@ public class JmsItemWriter implements ItemWriter { /** * Send the items one-by-one to the default destination of the JMS template. * - * @see org.springframework.batch.item.ItemWriter#write(java.util.List) + * @see org.springframework.batch.item.ItemWriter#write(Chunk) */ @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Writing to JMS with " + items.size() + " items."); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonFileItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonFileItemWriter.java index d41e8d015..b08aaa20f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonFileItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/json/JsonFileItemWriter.java @@ -19,6 +19,7 @@ package org.springframework.batch.item.json; import java.util.Iterator; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.support.AbstractFileItemWriter; import org.springframework.core.io.WritableResource; import org.springframework.util.Assert; @@ -94,7 +95,7 @@ public class JsonFileItemWriter extends AbstractFileItemWriter { } @Override - public String doWrite(List items) { + public String doWrite(Chunk items) { StringBuilder lines = new StringBuilder(); Iterator iterator = items.iterator(); if (!items.isEmpty() && state.getLinesWritten() > 0) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriter.java index b9df93a2c..24b0ead87 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2010 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.InitializingBean; import org.springframework.mail.MailException; @@ -50,6 +51,7 @@ import org.springframework.util.Assert; *

* * @author Dave Syer + * @author Mahmoud Ben Hassine * @since 2.1 * */ @@ -60,7 +62,7 @@ public class SimpleMailMessageItemWriter implements ItemWriter items) throws MailException { + public void write(Chunk chunk) throws MailException { try { - mailSender.send(items.toArray(new SimpleMailMessage[items.size()])); + mailSender.send(chunk.getItems().toArray(new SimpleMailMessage[chunk.size()])); } catch (MailSendException e) { Map failedMessages = e.getFailedMessages(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilder.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilder.java index d8e1fee7f..8f8d7dcce 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilder.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import org.springframework.util.Assert; * Creates a fully qualified SimpleMailMessageItemWriter. * * @author Glenn Renfro + * @author Mahmoud Ben Hassine * @since 4.0 */ @@ -39,7 +40,7 @@ public class SimpleMailMessageItemWriterBuilder { /** * A {@link MailSender} to be used to send messages in - * {@link SimpleMailMessageItemWriter#write(List)}. + * {@link SimpleMailMessageItemWriter#write(Chunk)}. * @param mailSender strategy for sending simple mails. * @return this instance for method chaining. * @see SimpleMailMessageItemWriter#setMailSender(MailSender) diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriter.java index ae3d2f955..8fa531032 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,6 +15,7 @@ */ package org.springframework.batch.item.mail.javamail; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.mail.DefaultMailErrorHandler; import org.springframework.batch.item.mail.MailErrorHandler; @@ -64,7 +65,7 @@ public class MimeMessageItemWriter implements ItemWriter { private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler(); /** - * A {@link JavaMailSender} to be used to send messages in {@link #write(List)}. + * A {@link JavaMailSender} to be used to send messages in {@link #write(Chunk)}. * @param mailSender service for doing the work of sending a MIME message */ public void setJavaMailSender(JavaMailSender mailSender) { @@ -90,13 +91,13 @@ public class MimeMessageItemWriter implements ItemWriter { } /** - * @param items the items to send - * @see ItemWriter#write(List) + * @param chunk the chunk of items to send + * @see ItemWriter#write(Chunk) */ @Override - public void write(List items) throws MailException { + public void write(Chunk chunk) throws MailException { try { - mailSender.send(items.toArray(new MimeMessage[items.size()])); + mailSender.send(chunk.getItems().toArray(new MimeMessage[chunk.size()])); } catch (MailSendException e) { Map failedMessages = e.getFailedMessages(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java index dd376307c..cf04d21eb 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java @@ -31,6 +31,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; @@ -220,7 +221,7 @@ public abstract class AbstractFileItemWriter extends AbstractItemStreamItemWr * @throws Exception if an error occurs while writing items to the output stream */ @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { if (!getOutputState().isInitialized()) { throw new WriterNotOpenException("Writer must be open before it can be written to"); } @@ -247,7 +248,7 @@ public abstract class AbstractFileItemWriter extends AbstractItemStreamItemWr * @param items to be written * @return written lines */ - protected abstract String doWrite(List items); + protected abstract String doWrite(Chunk items); /** * @see ItemStream#close() diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ClassifierCompositeItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ClassifierCompositeItemWriter.java index 4b3f243fa..17f818544 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ClassifierCompositeItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ClassifierCompositeItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +21,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.springframework.batch.item.Chunk; import org.springframework.classify.Classifier; import org.springframework.classify.ClassifierSupport; import org.springframework.batch.item.ItemWriter; @@ -34,6 +35,7 @@ import org.springframework.util.Assert; * * @author Dave Syer * @author Glenn Renfro + * @author Mahmoud Ben Hassine * @since 2.0 */ public class ClassifierCompositeItemWriter implements ItemWriter { @@ -53,14 +55,14 @@ public class ClassifierCompositeItemWriter implements ItemWriter { * classification by the {@link Classifier}. */ @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { - Map, List> map = new LinkedHashMap<>(); + Map, Chunk> map = new LinkedHashMap<>(); for (T item : items) { ItemWriter key = classifier.classify(item); if (!map.containsKey(key)) { - map.put(key, new ArrayList<>()); + map.put(key, new Chunk<>()); } map.get(key).add(item); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java index 73051efe7..5613f16a6 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java @@ -16,6 +16,7 @@ package org.springframework.batch.item.support; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; @@ -35,6 +36,7 @@ import java.util.List; * * @author Robert Kasanicky * @author Dave Syer + * @author Mahmoud Ben Hassine */ public class CompositeItemWriter implements ItemStreamWriter, InitializingBean { @@ -78,9 +80,9 @@ public class CompositeItemWriter implements ItemStreamWriter, Initializing } @Override - public void write(List item) throws Exception { + public void write(Chunk chunk) throws Exception { for (ItemWriter writer : delegates) { - writer.write(item); + writer.write(chunk); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemWriter.java index c51e892ed..7f3ff2626 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2019 the original author or authors. + * Copyright 2014-2022 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,6 +15,7 @@ */ package org.springframework.batch.item.support; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import java.util.ArrayList; @@ -22,14 +23,15 @@ import java.util.List; /** * @author mminella + * @author Mahmoud Ben Hassine */ public class ListItemWriter implements ItemWriter { private List writtenItems = new ArrayList<>(); @Override - public void write(List items) throws Exception { - writtenItems.addAll(items); + public void write(Chunk chunk) throws Exception { + writtenItems.addAll(chunk.getItems()); } public List getWrittenItems() { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamWriter.java index e61853a13..2cfe6fc3f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SynchronizedItemStreamWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2020 the original author or authors. + * Copyright 2020-2022 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,6 +15,7 @@ */ package org.springframework.batch.item.support; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.ItemStreamWriter; @@ -60,7 +61,7 @@ public class SynchronizedItemStreamWriter implements ItemStreamWriter, Ini * This method delegates to the {@code write} method of the {@code delegate}. */ @Override - public synchronized void write(List items) throws Exception { + public synchronized void write(Chunk items) throws Exception { this.delegate.write(items); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java index 6579fdc3e..8bf4ce9f3 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java @@ -38,6 +38,7 @@ import javax.xml.transform.Result; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.ItemWriter; @@ -761,7 +762,7 @@ public class StaxEventItemWriter extends AbstractItemStreamItemWriter * @throws XmlMappingException thrown if error occurs during XML Mapping. */ @Override - public void write(List items) throws XmlMappingException, IOException { + public void write(Chunk items) throws XmlMappingException, IOException { if (!this.initialized) { throw new WriterNotOpenException("Writer must be open before it can be written to"); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/ItemWriterAdapterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/ItemWriterAdapterTests.java index bc42e35eb..66c5d660f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/ItemWriterAdapterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/ItemWriterAdapterTests.java @@ -23,6 +23,8 @@ import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.sample.Foo; import org.springframework.batch.item.sample.FooService; @@ -33,6 +35,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; * Tests for {@link ItemWriterAdapter}. * * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ @SpringJUnitConfig(locations = "delegating-item-writer.xml") class ItemWriterAdapterTests { @@ -50,7 +53,7 @@ class ItemWriterAdapterTests { @Test void testProcess() throws Exception { Foo foo; - List foos = new ArrayList<>(); + Chunk foos = new Chunk<>(); while ((foo = fooService.generateFoo()) != null) { foos.add(foo); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemProcessorIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemProcessorIntegrationTests.java index 2d2f9e482..c943ec4a7 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemProcessorIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemProcessorIntegrationTests.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.sample.Foo; import org.springframework.batch.item.sample.FooService; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -49,7 +50,7 @@ class PropertyExtractingDelegatingItemProcessorIntegrationTests { void testProcess() throws Exception { Foo foo; while ((foo = fooService.generateFoo()) != null) { - processor.write(Collections.singletonList(foo)); + processor.write(Chunk.of(foo)); } List input = fooService.getGeneratedFoos(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/AmqpItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/AmqpItemWriterTests.java index 816eb0e95..ac79bd7a3 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/AmqpItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/AmqpItemWriterTests.java @@ -21,6 +21,7 @@ import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; import org.springframework.amqp.core.AmqpTemplate; +import org.springframework.batch.item.Chunk; import java.util.Arrays; @@ -31,6 +32,7 @@ import java.util.Arrays; * * @author Chris Schaefer * @author Will Schipp + * @author Mahmoud Ben Hassine */ class AmqpItemWriterTests { @@ -48,7 +50,7 @@ class AmqpItemWriterTests { amqpTemplate.convertAndSend("bar"); AmqpItemWriter amqpItemWriter = new AmqpItemWriter<>(amqpTemplate); - amqpItemWriter.write(Arrays.asList("foo", "bar")); + amqpItemWriter.write(Chunk.of("foo", "bar")); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/builder/AmqpItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/builder/AmqpItemWriterBuilderTests.java index 8e53b3d8c..2618a6cba 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/builder/AmqpItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/amqp/builder/AmqpItemWriterBuilderTests.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.Test; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.Message; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.amqp.AmqpItemWriter; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -31,6 +32,7 @@ import static org.mockito.Mockito.verify; /** * @author Glenn Renfro + * @author Mahmoud Ben Hassine */ class AmqpItemWriterBuilderTests { @@ -46,7 +48,7 @@ class AmqpItemWriterBuilderTests { AmqpTemplate amqpTemplate = mock(AmqpTemplate.class); AmqpItemWriter amqpItemWriter = new AmqpItemWriterBuilder().amqpTemplate(amqpTemplate).build(); - amqpItemWriter.write(Arrays.asList("foo", "bar")); + amqpItemWriter.write(Chunk.of("foo", "bar")); verify(amqpTemplate).convertAndSend("foo"); verify(amqpTemplate).convertAndSend("bar"); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemReaderTestSupport.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemReaderTestSupport.java index 76dc7e4b3..9618b7d1b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemReaderTestSupport.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemReaderTestSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2019 the original author or authors. + * Copyright 2019-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.item.avro.support; import java.util.ArrayList; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.avro.AvroItemReader; @@ -26,10 +27,11 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author David Turanski + * @author Mahmoud Ben Hassine */ public abstract class AvroItemReaderTestSupport extends AvroTestFixtures { - protected void verify(AvroItemReader avroItemReader, List actual) throws Exception { + protected void verify(AvroItemReader avroItemReader, Chunk actual) throws Exception { avroItemReader.open(new ExecutionContext()); List users = new ArrayList<>(); @@ -40,7 +42,9 @@ public abstract class AvroItemReaderTestSupport extends AvroTestFixtures { } assertThat(users).hasSize(4); - assertThat(users).containsExactlyInAnyOrder(actual.get(0), actual.get(1), actual.get(2), actual.get(3)); + List actualItems = actual.getItems(); + assertThat(users).containsExactlyInAnyOrder(actualItems.get(0), actualItems.get(1), actualItems.get(2), + actualItems.get(3)); avroItemReader.close(); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemWriterTestSupport.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemWriterTestSupport.java index 4586b0f87..eb1275f31 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemWriterTestSupport.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroItemWriterTestSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2019 the original author or authors. + * Copyright 2019-2022 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,6 +25,7 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.avro.AvroItemReader; import org.springframework.batch.item.avro.builder.AvroItemReaderBuilder; @@ -36,22 +37,23 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author David Turanski + * @author Mahmoud Ben Hassine */ public abstract class AvroItemWriterTestSupport extends AvroTestFixtures { /* * This item reader configured for Specific Avro types. */ - protected void verifyRecords(byte[] bytes, List actual, Class clazz, boolean embeddedSchema) + protected void verifyRecords(byte[] bytes, Chunk actual, Class clazz, boolean embeddedSchema) throws Exception { doVerify(bytes, clazz, actual, embeddedSchema); } - protected void verifyRecordsWithEmbeddedHeader(byte[] bytes, List actual, Class clazz) throws Exception { + protected void verifyRecordsWithEmbeddedHeader(byte[] bytes, Chunk actual, Class clazz) throws Exception { doVerify(bytes, clazz, actual, true); } - private void doVerify(byte[] bytes, Class clazz, List actual, boolean embeddedSchema) throws Exception { + private void doVerify(byte[] bytes, Class clazz, Chunk actual, boolean embeddedSchema) throws Exception { AvroItemReader avroItemReader = new AvroItemReaderBuilder().type(clazz) .resource(new ByteArrayResource(bytes)).embeddedSchema(embeddedSchema).build(); @@ -63,7 +65,9 @@ public abstract class AvroItemWriterTestSupport extends AvroTestFixtures { records.add(record); } assertThat(records).hasSize(4); - assertThat(records).containsExactlyInAnyOrder(actual.get(0), actual.get(1), actual.get(2), actual.get(3)); + List actualItems = actual.getItems(); + assertThat(records).containsExactlyInAnyOrder(actualItems.get(0), actualItems.get(1), actualItems.get(2), + actualItems.get(3)); } protected static class OutputStreamResource implements WritableResource { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroTestFixtures.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroTestFixtures.java index 968cd84f6..cf1958d39 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroTestFixtures.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/support/AvroTestFixtures.java @@ -1,5 +1,5 @@ /* - * Copyright 2019 the original author or authors. + * Copyright 2019-2022 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. @@ -33,6 +33,8 @@ import org.apache.avro.io.Encoder; import org.apache.avro.io.EncoderFactory; import org.apache.avro.reflect.ReflectData; import org.apache.avro.reflect.ReflectDatumWriter; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.avro.example.User; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; @@ -45,13 +47,13 @@ import org.springframework.core.io.Resource; public abstract class AvroTestFixtures { //@formatter:off - private final List avroGeneratedUsers = Arrays.asList( + private final Chunk avroGeneratedUsers = Chunk.of( new User("David", 20, "blue"), new User("Sue", 4, "red"), new User("Alana", 13, "yellow"), new User("Joe", 1, "pink")); - private List plainOldUsers = Arrays.asList( + private Chunk plainOldUsers = Chunk.of( new PlainOldUser("David", 20, "blue"), new PlainOldUser("Sue", 4, "red"), new PlainOldUser("Alana", 13, "yellow"), @@ -86,27 +88,28 @@ public abstract class AvroTestFixtures { } } - protected List avroGeneratedUsers() { + protected Chunk avroGeneratedUsers() { return this.avroGeneratedUsers; } - protected List genericAvroGeneratedUsers() { - return this.avroGeneratedUsers.stream().map(u -> { + protected Chunk genericAvroGeneratedUsers() { + return new Chunk(this.avroGeneratedUsers.getItems().stream().map(u -> { GenericData.Record avroRecord; avroRecord = new GenericData.Record(u.getSchema()); avroRecord.put("name", u.getName()); avroRecord.put("favorite_number", u.getFavoriteNumber()); avroRecord.put("favorite_color", u.getFavoriteColor()); return avroRecord; - }).collect(Collectors.toList()); + }).collect(Collectors.toList())); } - protected List plainOldUsers() { + protected Chunk plainOldUsers() { return this.plainOldUsers; } - protected List genericPlainOldUsers() { - return this.plainOldUsers.stream().map(PlainOldUser::toGenericRecord).collect(Collectors.toList()); + protected Chunk genericPlainOldUsers() { + return new Chunk( + this.plainOldUsers.getItems().stream().map(PlainOldUser::toGenericRecord).collect(Collectors.toList())); } protected static class PlainOldUser { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/GemfireItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/GemfireItemWriterTests.java index 68bad56ea..651627e56 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/GemfireItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/GemfireItemWriterTests.java @@ -27,6 +27,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.SpELItemKeyMapper; import org.springframework.data.gemfire.GemfireTemplate; import org.springframework.core.convert.converter.Converter; @@ -61,29 +63,30 @@ class GemfireItemWriterTests { @Test void testBasicWrite() throws Exception { - List items = new ArrayList() { + Chunk chunk = new Chunk() { { add(new Foo(new Bar("val1"))); add(new Foo(new Bar("val2"))); } }; - writer.write(items); + writer.write(chunk); + List items = chunk.getItems(); verify(template).put("val1", items.get(0)); verify(template).put("val2", items.get(1)); } @Test void testBasicDelete() throws Exception { - List items = new ArrayList() { + Chunk chunk = new Chunk() { { add(new Foo(new Bar("val1"))); add(new Foo(new Bar("val2"))); } }; writer.setDelete(true); - writer.write(items); + writer.write(chunk); verify(template).remove("val1"); verify(template).remove("val2"); @@ -91,7 +94,7 @@ class GemfireItemWriterTests { @Test void testWriteWithCustomItemKeyMapper() throws Exception { - List items = new ArrayList() { + Chunk chunk = new Chunk() { { add(new Foo(new Bar("val1"))); add(new Foo(new Bar("val2"))); @@ -108,8 +111,9 @@ class GemfireItemWriterTests { } }); writer.afterPropertiesSet(); - writer.write(items); + writer.write(chunk); + List items = chunk.getItems(); verify(template).put("item1", items.get(0)); verify(template).put("item2", items.get(1)); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoItemWriterTests.java index ccb54fdc6..00636da4c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoItemWriterTests.java @@ -38,6 +38,8 @@ import static org.mockito.Mockito.never; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mongodb.core.BulkOperations; @@ -104,7 +106,7 @@ class MongoItemWriterTests { @Test void testWriteNoTransactionNoCollection() throws Exception { - List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.write(items); @@ -114,7 +116,7 @@ class MongoItemWriterTests { @Test void testWriteNoTransactionWithCollection() throws Exception { - List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.setCollection("collection"); @@ -126,7 +128,7 @@ class MongoItemWriterTests { @Test void testWriteNoTransactionNoItems() throws Exception { - writer.write(null); + writer.write(new Chunk<>()); verifyNoInteractions(template); verifyNoInteractions(bulkOperations); @@ -134,7 +136,7 @@ class MongoItemWriterTests { @Test void testWriteTransactionNoCollection() { - final List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + final Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { assertDoesNotThrow(() -> writer.write(items)); @@ -147,7 +149,7 @@ class MongoItemWriterTests { @Test void testWriteTransactionWithCollection() { - final List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + final Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.setCollection("collection"); @@ -162,7 +164,7 @@ class MongoItemWriterTests { @Test void testWriteTransactionFails() { - final List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + final Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.setCollection("collection"); @@ -183,7 +185,7 @@ class MongoItemWriterTests { */ @Test void testWriteTransactionReadOnly() { - final List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + final Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.setCollection("collection"); @@ -201,7 +203,7 @@ class MongoItemWriterTests { @Test void testRemoveNoObjectIdNoCollection() throws Exception { writer.setDelete(true); - List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.write(items); @@ -212,7 +214,7 @@ class MongoItemWriterTests { @Test void testRemoveNoObjectIdWithCollection() throws Exception { writer.setDelete(true); - List items = Arrays.asList(new Item("Foo"), new Item("Bar")); + Chunk items = Chunk.of(new Item("Foo"), new Item("Bar")); writer.setCollection("collection"); writer.write(items); @@ -224,7 +226,7 @@ class MongoItemWriterTests { @Test void testRemoveNoTransactionNoCollection() throws Exception { writer.setDelete(true); - List items = Arrays.asList(new Item(1), new Item(2)); + Chunk items = Chunk.of(new Item(1), new Item(2)); writer.write(items); @@ -235,7 +237,7 @@ class MongoItemWriterTests { @Test void testRemoveNoTransactionWithCollection() throws Exception { writer.setDelete(true); - List items = Arrays.asList(new Item(1), new Item(2)); + Chunk items = Chunk.of(new Item(1), new Item(2)); writer.setCollection("collection"); @@ -285,7 +287,7 @@ class MongoItemWriterTests { new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { try { for (int i = 0; i < limit; i++) { - writers.get(i).write(Collections.singletonList(String.valueOf(i))); + writers.get(i).write(Chunk.of(String.valueOf(i))); } } catch (Exception e) { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/Neo4jItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/Neo4jItemWriterTests.java index 0a9584a48..d727b1343 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/Neo4jItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/Neo4jItemWriterTests.java @@ -25,6 +25,8 @@ import org.mockito.quality.Strictness; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; +import org.springframework.batch.item.Chunk; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; @@ -62,32 +64,6 @@ class Neo4jItemWriterTests { writer.afterPropertiesSet(); } - @Test - void testWriteNullSession() throws Exception { - - writer = new Neo4jItemWriter<>(); - - writer.setSessionFactory(this.sessionFactory); - writer.afterPropertiesSet(); - - writer.write(null); - - verifyNoInteractions(this.session); - } - - @Test - void testWriteNullWithSession() throws Exception { - writer = new Neo4jItemWriter<>(); - - writer.setSessionFactory(this.sessionFactory); - writer.afterPropertiesSet(); - - when(this.sessionFactory.openSession()).thenReturn(this.session); - writer.write(null); - - verifyNoInteractions(this.session); - } - @Test void testWriteNoItemsWithSession() throws Exception { writer = new Neo4jItemWriter<>(); @@ -96,7 +72,7 @@ class Neo4jItemWriterTests { writer.afterPropertiesSet(); when(this.sessionFactory.openSession()).thenReturn(this.session); - writer.write(new ArrayList<>()); + writer.write(new Chunk<>()); verifyNoInteractions(this.session); } @@ -108,7 +84,7 @@ class Neo4jItemWriterTests { writer.setSessionFactory(this.sessionFactory); writer.afterPropertiesSet(); - List items = new ArrayList<>(); + Chunk items = new Chunk<>(); items.add("foo"); items.add("bar"); @@ -126,7 +102,7 @@ class Neo4jItemWriterTests { writer.setSessionFactory(this.sessionFactory); writer.afterPropertiesSet(); - List items = new ArrayList<>(); + Chunk items = new Chunk<>(); items.add("foo"); items.add("bar"); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/RepositoryItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/RepositoryItemWriterTests.java index 11cdbceee..d62f06ab0 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/RepositoryItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/RepositoryItemWriterTests.java @@ -31,6 +31,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.data.repository.CrudRepository; @ExtendWith(MockitoExtension.class) @@ -64,16 +66,14 @@ class RepositoryItemWriterTests { @Test void testWriteNoItems() throws Exception { - writer.write(null); - - writer.write(new ArrayList<>()); + writer.write(new Chunk<>()); verifyNoInteractions(repository); } @Test void testWriteItems() throws Exception { - List items = Collections.singletonList("foo"); + Chunk items = Chunk.of("foo"); writer.write(items); @@ -83,7 +83,7 @@ class RepositoryItemWriterTests { @Test void testWriteItemsWithDefaultMethodName() throws Exception { - List items = Collections.singletonList("foo"); + Chunk items = Chunk.of("foo"); writer.setMethodName(null); writer.write(items); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/GemfireItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/GemfireItemWriterBuilderTests.java index d451f05e5..0ffe43a52 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/GemfireItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/GemfireItemWriterBuilderTests.java @@ -24,6 +24,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.SpELItemKeyMapper; import org.springframework.batch.item.data.GemfireItemWriter; import org.springframework.data.gemfire.GemfireTemplate; @@ -35,6 +37,7 @@ import static org.mockito.Mockito.verify; /** * @author Glenn Renfro + * @author Mahmoud Ben Hassine */ @ExtendWith(MockitoExtension.class) class GemfireItemWriterBuilderTests { @@ -44,11 +47,11 @@ class GemfireItemWriterBuilderTests { private SpELItemKeyMapper itemKeyMapper; - private List items; + private Chunk items; @BeforeEach void setUp() { - this.items = Arrays.asList(new GemfireItemWriterBuilderTests.Foo(new GemfireItemWriterBuilderTests.Bar("val1")), + this.items = Chunk.of(new GemfireItemWriterBuilderTests.Foo(new GemfireItemWriterBuilderTests.Bar("val1")), new GemfireItemWriterBuilderTests.Foo(new GemfireItemWriterBuilderTests.Bar("val2"))); this.itemKeyMapper = new SpELItemKeyMapper<>("bar.val"); } @@ -60,8 +63,8 @@ class GemfireItemWriterBuilderTests { writer.write(this.items); - verify(this.template).put("val1", items.get(0)); - verify(this.template).put("val2", items.get(1)); + verify(this.template).put("val1", items.getItems().get(0)); + verify(this.template).put("val2", items.getItems().get(1)); verify(this.template, never()).remove("val1"); verify(this.template, never()).remove("val2"); } @@ -75,8 +78,8 @@ class GemfireItemWriterBuilderTests { verify(this.template).remove("val1"); verify(this.template).remove("val2"); - verify(this.template, never()).put("val1", items.get(0)); - verify(this.template, never()).put("val2", items.get(1)); + verify(this.template, never()).put("val1", items.getItems().get(0)); + verify(this.template, never()).put("val2", items.getItems().get(1)); } @Test diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoItemWriterBuilderTests.java index 7dbf19815..08c1fa34a 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoItemWriterBuilderTests.java @@ -31,6 +31,8 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.data.MongoItemWriter; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.mongodb.core.BulkOperations; @@ -68,9 +70,9 @@ class MongoItemWriterBuilderTests { private MongoConverter mongoConverter; - private List saveItems; + private Chunk saveItems; - private List removeItems; + private Chunk removeItems; @BeforeEach void setUp() { @@ -81,8 +83,8 @@ class MongoItemWriterBuilderTests { mongoConverter = spy(new MappingMongoConverter(this.dbRefResolver, mappingContext)); when(this.template.getConverter()).thenReturn(mongoConverter); - this.saveItems = Arrays.asList(new Item("Foo"), new Item("Bar")); - this.removeItems = Arrays.asList(new Item(1), new Item(2)); + this.saveItems = Chunk.of(new Item("Foo"), new Item("Bar")); + this.removeItems = Chunk.of(new Item(1), new Item(2)); } @Test @@ -91,8 +93,8 @@ class MongoItemWriterBuilderTests { writer.write(this.saveItems); verify(this.template).bulkOps(any(), any(Class.class)); - verify(this.mongoConverter).write(eq(this.saveItems.get(0)), any(Document.class)); - verify(this.mongoConverter).write(eq(this.saveItems.get(1)), any(Document.class)); + verify(this.mongoConverter).write(eq(this.saveItems.getItems().get(0)), any(Document.class)); + verify(this.mongoConverter).write(eq(this.saveItems.getItems().get(1)), any(Document.class)); verify(this.bulkOperations, times(2)).replaceOne(any(Query.class), any(Object.class), any()); verify(this.bulkOperations, never()).remove(any(Query.class)); } @@ -105,8 +107,8 @@ class MongoItemWriterBuilderTests { writer.write(this.saveItems); verify(this.template).bulkOps(any(), eq("collection")); - verify(this.mongoConverter).write(eq(this.saveItems.get(0)), any(Document.class)); - verify(this.mongoConverter).write(eq(this.saveItems.get(1)), any(Document.class)); + verify(this.mongoConverter).write(eq(this.saveItems.getItems().get(0)), any(Document.class)); + verify(this.mongoConverter).write(eq(this.saveItems.getItems().get(1)), any(Document.class)); verify(this.bulkOperations, times(2)).replaceOne(any(Query.class), any(Object.class), any()); verify(this.bulkOperations, never()).remove(any(Query.class)); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/Neo4jItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/Neo4jItemWriterBuilderTests.java index 34546077c..897277745 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/Neo4jItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/Neo4jItemWriterBuilderTests.java @@ -26,6 +26,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.data.Neo4jItemWriter; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -36,6 +37,7 @@ import static org.mockito.Mockito.when; /** * @author Glenn Renfro + * @author Mahmoud Ben Hassine */ @SuppressWarnings("deprecation") @ExtendWith(MockitoExtension.class) @@ -51,7 +53,7 @@ class Neo4jItemWriterBuilderTests { void testBasicWriter() throws Exception { Neo4jItemWriter writer = new Neo4jItemWriterBuilder().sessionFactory(this.sessionFactory) .build(); - List items = new ArrayList<>(); + Chunk items = new Chunk<>(); items.add("foo"); items.add("bar"); @@ -68,7 +70,7 @@ class Neo4jItemWriterBuilderTests { void testBasicDelete() throws Exception { Neo4jItemWriter writer = new Neo4jItemWriterBuilder().delete(true) .sessionFactory(this.sessionFactory).build(); - List items = new ArrayList<>(); + Chunk items = new Chunk<>(); items.add("foo"); items.add("bar"); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/RepositoryItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/RepositoryItemWriterBuilderTests.java index 3c8c2ffe4..0a419e6fb 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/RepositoryItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/RepositoryItemWriterBuilderTests.java @@ -24,6 +24,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.data.RepositoryItemWriter; import org.springframework.data.repository.CrudRepository; @@ -60,7 +62,7 @@ class RepositoryItemWriterBuilderTests { RepositoryItemWriter writer = new RepositoryItemWriterBuilder().methodName("save") .repository(this.repository).build(); - List items = Collections.singletonList("foo"); + Chunk items = Chunk.of("foo"); writer.write(items); @@ -72,7 +74,7 @@ class RepositoryItemWriterBuilderTests { RepositoryItemWriter writer = new RepositoryItemWriterBuilder().methodName("foo") .repository(this.repository).build(); - List items = Collections.singletonList("foo"); + Chunk items = Chunk.of("foo"); writer.write(items); @@ -88,7 +90,7 @@ class RepositoryItemWriterBuilderTests { RepositoryItemWriter writer = new RepositoryItemWriterBuilder().methodName("foo") .repository(repositoryMethodReference).build(); - List items = Collections.singletonList("foo"); + Chunk items = Chunk.of("foo"); writer.write(items); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/HibernateItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/HibernateItemWriterTests.java index ef214c5ac..470f6b4f6 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/HibernateItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/HibernateItemWriterTests.java @@ -23,6 +23,8 @@ import org.hibernate.SessionFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -84,7 +86,7 @@ class HibernateItemWriterTests { this.currentSession.flush(); this.currentSession.clear(); - List items = Arrays.asList(new String[] { "foo", "bar" }); + Chunk items = Chunk.of("foo", "bar"); writer.write(items); } @@ -95,7 +97,7 @@ class HibernateItemWriterTests { final RuntimeException ex = new RuntimeException("ERROR"); when(this.currentSession.contains("foo")).thenThrow(ex); - Exception exception = assertThrows(RuntimeException.class, () -> writer.write(List.of("foo"))); + Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of("foo"))); assertEquals("ERROR", exception.getMessage()); } @@ -109,7 +111,7 @@ class HibernateItemWriterTests { currentSession.flush(); currentSession.clear(); - List items = Arrays.asList(new String[] { "foo", "bar" }); + Chunk items = Chunk.of("foo", "bar"); writer.write(items); } @@ -121,7 +123,7 @@ class HibernateItemWriterTests { when(factory.getCurrentSession()).thenReturn(currentSession); when(currentSession.contains("foo")).thenThrow(ex); - Exception exception = assertThrows(RuntimeException.class, () -> writer.write(List.of("foo"))); + Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of("foo"))); assertEquals("ERROR", exception.getMessage()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java index c2bb97dce..21e375a9c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterClassicTests.java @@ -27,6 +27,8 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.UncategorizedSQLException; @@ -38,6 +40,7 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; * @author Dave Syer * @author Thomas Risberg * @author Will Schipp + * @author Mahmoud Ben Hassine */ class JdbcBatchItemWriterClassicTests { @@ -105,7 +108,7 @@ class JdbcBatchItemWriterClassicTests { void testWriteAndFlush() throws Exception { ps.addBatch(); when(ps.executeBatch()).thenReturn(new int[] { 123 }); - writer.write(Collections.singletonList("bar")); + writer.write(Chunk.of("bar")); assertEquals(2, list.size()); assertTrue(list.contains("SQL")); } @@ -114,7 +117,7 @@ class JdbcBatchItemWriterClassicTests { void testWriteAndFlushWithEmptyUpdate() throws Exception { ps.addBatch(); when(ps.executeBatch()).thenReturn(new int[] { 0 }); - Exception exception = assertThrows(EmptyResultDataAccessException.class, () -> writer.write(List.of("bar"))); + Exception exception = assertThrows(EmptyResultDataAccessException.class, () -> writer.write(Chunk.of("bar"))); String message = exception.getMessage(); assertTrue(message.contains("did not update"), "Wrong message: " + message); assertEquals(2, list.size()); @@ -133,7 +136,7 @@ class JdbcBatchItemWriterClassicTests { }); ps.addBatch(); when(ps.executeBatch()).thenReturn(new int[] { 123 }); - Exception exception = assertThrows(RuntimeException.class, () -> writer.write(List.of("foo"))); + Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of("foo"))); assertEquals("bar", exception.getMessage()); assertEquals(2, list.size()); writer.setItemPreparedStatementSetter(new ItemPreparedStatementSetter() { @@ -142,7 +145,7 @@ class JdbcBatchItemWriterClassicTests { list.add(item); } }); - writer.write(Collections.singletonList("foo")); + writer.write(Chunk.of("foo")); assertEquals(4, list.size()); assertTrue(list.contains("SQL")); assertTrue(list.contains("foo")); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java index 7062a6fef..b117604c9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JdbcBatchItemWriterNamedParameterTests.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.batch.item.Chunk; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -43,6 +44,7 @@ import static org.mockito.hamcrest.MockitoHamcrest.argThat; * @author Thomas Risberg * @author Will Schipp * @author Michael Minella + * @author Mahmoud Ben Hassine */ public class JdbcBatchItemWriterNamedParameterTests { @@ -119,7 +121,7 @@ public class JdbcBatchItemWriterNamedParameterTests { eqSqlParameterSourceArray( new SqlParameterSource[] { new BeanPropertySqlParameterSource(new Foo("bar")) }))) .thenReturn(new int[] { 1 }); - writer.write(List.of(new Foo("bar"))); + writer.write(Chunk.of(new Foo("bar"))); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -134,7 +136,7 @@ public class JdbcBatchItemWriterNamedParameterTests { ArgumentCaptor captor = ArgumentCaptor.forClass(Map[].class); when(namedParameterJdbcOperations.batchUpdate(eq(sql), captor.capture())).thenReturn(new int[] { 1 }); - mapWriter.write(List.of(Map.of("foo", "bar"))); + mapWriter.write(Chunk.of(Map.of("foo", "bar"))); assertEquals(1, captor.getValue().length); Map results = captor.getValue()[0]; @@ -158,7 +160,7 @@ public class JdbcBatchItemWriterNamedParameterTests { ArgumentCaptor captor = ArgumentCaptor.forClass(SqlParameterSource[].class); when(namedParameterJdbcOperations.batchUpdate(any(String.class), captor.capture())).thenReturn(new int[] { 1 }); - mapWriter.write(List.of(Map.of("foo", "bar"))); + mapWriter.write(Chunk.of(Map.of("foo", "bar"))); assertEquals(1, captor.getValue().length); SqlParameterSource results = captor.getValue()[0]; @@ -172,7 +174,7 @@ public class JdbcBatchItemWriterNamedParameterTests { new SqlParameterSource[] { new BeanPropertySqlParameterSource(new Foo("bar")) }))) .thenReturn(new int[] { 0 }); Exception exception = assertThrows(EmptyResultDataAccessException.class, - () -> writer.write(List.of(new Foo("bar")))); + () -> writer.write(Chunk.of(new Foo("bar")))); String message = exception.getMessage(); assertTrue(message.contains("did not update"), "Wrong message: " + message); } @@ -184,7 +186,7 @@ public class JdbcBatchItemWriterNamedParameterTests { eqSqlParameterSourceArray( new SqlParameterSource[] { new BeanPropertySqlParameterSource(new Foo("bar")) }))) .thenThrow(ex); - Exception exception = assertThrows(RuntimeException.class, () -> writer.write(List.of(new Foo("bar")))); + Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of(new Foo("bar")))); assertEquals("ERROR", exception.getMessage()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterIntegrationTests.java index 86a0bb092..6f8dfcbe2 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterIntegrationTests.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.sample.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -71,7 +72,7 @@ class JpaItemWriterIntegrationTests { JpaItemWriter writer = new JpaItemWriter<>(); writer.setEntityManagerFactory(this.entityManagerFactory); writer.afterPropertiesSet(); - List items = Arrays.asList(new Person(1, "foo"), new Person(2, "bar")); + Chunk items = Chunk.of(new Person(1, "foo"), new Person(2, "bar")); // when writer.write(items); @@ -87,7 +88,7 @@ class JpaItemWriterIntegrationTests { writer.setEntityManagerFactory(this.entityManagerFactory); writer.setUsePersist(true); writer.afterPropertiesSet(); - List items = Arrays.asList(new Person(1, "foo"), new Person(2, "bar")); + Chunk items = Chunk.of(new Person(1, "foo"), new Person(2, "bar")); // when writer.write(items); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterTests.java index 216126ca2..4d523519f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaItemWriterTests.java @@ -31,6 +31,8 @@ import jakarta.persistence.EntityManagerFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -73,7 +75,7 @@ class JpaItemWriterTests { em.flush(); TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); - List items = Arrays.asList(new String[] { "foo", "bar" }); + Chunk items = Chunk.of("foo", "bar"); writer.write(items); @@ -85,10 +87,10 @@ class JpaItemWriterTests { writer.setUsePersist(true); EntityManager em = mock(EntityManager.class, "em"); TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); - List items = Arrays.asList("persist1", "persist2"); - writer.write(items); - verify(em).persist(items.get(0)); - verify(em).persist(items.get(1)); + Chunk chunk = Chunk.of("persist1", "persist2"); + writer.write(chunk); + verify(em).persist(chunk.getItems().get(0)); + verify(em).persist(chunk.getItems().get(1)); TransactionSynchronizationManager.unbindResource(emf); } @@ -102,7 +104,7 @@ class JpaItemWriterTests { when(em).thenThrow(ex); TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em)); - Exception exception = assertThrows(RuntimeException.class, () -> writer.write(List.of("foo", "bar"))); + Exception exception = assertThrows(RuntimeException.class, () -> writer.write(Chunk.of("foo", "bar"))); assertEquals("ERROR", exception.getMessage()); TransactionSynchronizationManager.unbindResource(emf); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/HibernateItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/HibernateItemWriterBuilderTests.java index 08c32e5f4..6d02d969c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/HibernateItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/HibernateItemWriterBuilderTests.java @@ -25,6 +25,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.database.HibernateItemWriter; import org.springframework.batch.item.sample.Foo; @@ -36,6 +38,7 @@ import static org.mockito.Mockito.when; /** * @author Michael Minella + * @author Mahmoud Ben Hassine */ @MockitoSettings(strictness = Strictness.LENIENT) class HibernateItemWriterBuilderTests { @@ -58,13 +61,13 @@ class HibernateItemWriterBuilderTests { itemWriter.afterPropertiesSet(); - List foos = getFoos(); + Chunk foos = getFoos(); itemWriter.write(foos); - verify(this.session).saveOrUpdate(foos.get(0)); - verify(this.session).saveOrUpdate(foos.get(1)); - verify(this.session).saveOrUpdate(foos.get(2)); + verify(this.session).saveOrUpdate(foos.getItems().get(0)); + verify(this.session).saveOrUpdate(foos.getItems().get(1)); + verify(this.session).saveOrUpdate(foos.getItems().get(2)); } @Test @@ -74,13 +77,13 @@ class HibernateItemWriterBuilderTests { itemWriter.afterPropertiesSet(); - List foos = getFoos(); + Chunk foos = getFoos(); itemWriter.write(foos); - verify(this.session).saveOrUpdate(foos.get(0)); - verify(this.session).saveOrUpdate(foos.get(1)); - verify(this.session).saveOrUpdate(foos.get(2)); + verify(this.session).saveOrUpdate(foos.getItems().get(0)); + verify(this.session).saveOrUpdate(foos.getItems().get(1)); + verify(this.session).saveOrUpdate(foos.getItems().get(2)); verify(this.session, never()).clear(); } @@ -91,8 +94,8 @@ class HibernateItemWriterBuilderTests { assertEquals("SessionFactory must be provided", exception.getMessage()); } - private List getFoos() { - List foos = new ArrayList<>(3); + private Chunk getFoos() { + Chunk foos = new Chunk<>(); for (int i = 1; i < 4; i++) { Foo foo = new Foo(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcBatchItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcBatchItemWriterBuilderTests.java index 88575ac33..ad80424ba 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcBatchItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JdbcBatchItemWriterBuilderTests.java @@ -25,6 +25,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -49,6 +50,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Michael Minella + * @author Mahmoud Ben Hassine */ class JdbcBatchItemWriterBuilderTests { @@ -77,8 +79,8 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List> items = buildMapItems(); - writer.write(items); + Chunk> chunk = buildMapItems(); + writer.write(chunk); verifyWrite(); } @@ -93,7 +95,7 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List> items = buildMapItems(); + Chunk> items = buildMapItems(); writer.write(items); verifyWrite(); @@ -109,7 +111,7 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List items = new ArrayList<>(3); + Chunk items = new Chunk<>(); items.add(new Foo(1, "two", "three")); items.add(new Foo(4, "five", "six")); @@ -128,7 +130,7 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List items = new ArrayList<>(1); + Chunk items = new Chunk<>(); items.add(new Foo(1, "two", "three")); @@ -147,7 +149,7 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List> items = buildMapItems(); + Chunk> items = buildMapItems(); writer.write(items); verifyWrite(); @@ -161,7 +163,7 @@ class JdbcBatchItemWriterBuilderTests { writer.afterPropertiesSet(); - List> items = buildMapItems(); + Chunk> items = buildMapItems(); writer.write(items); verifyWrite(); @@ -192,8 +194,8 @@ class JdbcBatchItemWriterBuilderTests { verifyRow(7, "eight", "nine"); } - private List> buildMapItems() { - List> items = new ArrayList<>(3); + private Chunk> buildMapItems() { + Chunk> items = new Chunk<>(); Map item = new HashMap<>(3); item.put("first", 1); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JpaItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JpaItemWriterBuilderTests.java index 3ef1c2ac2..a2404c2a4 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JpaItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/builder/JpaItemWriterBuilderTests.java @@ -26,6 +26,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.database.JpaItemWriter; import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -64,12 +66,12 @@ class JpaItemWriterBuilderTests { itemWriter.afterPropertiesSet(); - List items = Arrays.asList("foo", "bar"); + Chunk chunk = Chunk.of("foo", "bar"); - itemWriter.write(items); + itemWriter.write(chunk); - verify(this.entityManager).merge(items.get(0)); - verify(this.entityManager).merge(items.get(1)); + verify(this.entityManager).merge(chunk.getItems().get(0)); + verify(this.entityManager).merge(chunk.getItems().get(1)); } @Test @@ -86,12 +88,12 @@ class JpaItemWriterBuilderTests { itemWriter.afterPropertiesSet(); - List items = Arrays.asList("foo", "bar"); + Chunk chunk = Chunk.of("foo", "bar"); - itemWriter.write(items); + itemWriter.write(chunk); - verify(this.entityManager).persist(items.get(0)); - verify(this.entityManager).persist(items.get(1)); + verify(this.entityManager).persist(chunk.getItems().get(0)); + verify(this.entityManager).persist(chunk.getItems().get(1)); } } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java index f27b9f26a..e96440b7a 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/FlatFileItemWriterTests.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.UnexpectedInputException; @@ -60,6 +61,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * * @author Robert Kasanicky * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class FlatFileItemWriterTests { @@ -145,9 +147,9 @@ class FlatFileItemWriterTests { @Test void testWriteWithMultipleOpen() throws Exception { writer.open(executionContext); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("test1", readLine()); assertEquals("test2", readLine()); } @@ -155,13 +157,13 @@ class FlatFileItemWriterTests { @Test void testWriteWithDelete() throws Exception { writer.open(executionContext); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.close(); assertEquals("test1", readLine()); closeReader(); writer.setShouldDeleteIfExists(true); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("test2", readLine()); } @@ -169,12 +171,12 @@ class FlatFileItemWriterTests { void testWriteWithAppend() throws Exception { writer.setAppendAllowed(true); writer.open(executionContext); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.close(); assertEquals("test1", readLine()); closeReader(); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("test1", readLine()); assertEquals("test2", readLine()); } @@ -185,21 +187,21 @@ class FlatFileItemWriterTests { writer.setShouldDeleteIfExists(true); writer.setAppendAllowed(true); writer.open(executionContext); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.close(); assertEquals("test1", readLine()); closeReader(); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.update(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); assertEquals("test1", readLine()); assertEquals(TEST_STRING, readLine()); assertEquals(TEST_STRING, readLine()); assertNull(readLine()); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); closeReader(); assertEquals("test1", readLine()); @@ -222,7 +224,7 @@ class FlatFileItemWriterTests { @Test void testWriteString() throws Exception { writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); String lineFromFile = readLine(); @@ -233,7 +235,7 @@ class FlatFileItemWriterTests { void testForcedWriteString() throws Exception { writer.setForceSync(true); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); String lineFromFile = readLine(); @@ -254,7 +256,7 @@ class FlatFileItemWriterTests { }); String data = "string"; writer.open(executionContext); - writer.write(Collections.singletonList(data)); + writer.write(Chunk.of(data)); String lineFromFile = readLine(); // converter not used if input is String assertEquals("FOO:" + data, lineFromFile); @@ -273,7 +275,7 @@ class FlatFileItemWriterTests { } }); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); String lineFromFile = readLine(); assertEquals("FOO:" + TEST_STRING, lineFromFile); } @@ -285,7 +287,7 @@ class FlatFileItemWriterTests { @Test void testWriteRecord() throws Exception { writer.open(executionContext); - writer.write(Collections.singletonList("1")); + writer.write(Chunk.of("1")); String lineFromFile = readLine(); assertEquals("1", lineFromFile); } @@ -294,7 +296,7 @@ class FlatFileItemWriterTests { void testWriteRecordWithrecordSeparator() throws Exception { writer.setLineSeparator("|"); writer.open(executionContext); - writer.write(Arrays.asList(new String[] { "1", "2" })); + writer.write(Chunk.of(new String[] { "1", "2" })); String lineFromFile = readLine(); assertEquals("1|2|", lineFromFile); } @@ -313,9 +315,9 @@ class FlatFileItemWriterTests { writer.open(executionContext); // write some lines - writer.write(Arrays.asList(new String[] { "testLine1", "testLine2", "testLine3" })); + writer.write(Chunk.of(new String[] { "testLine1", "testLine2", "testLine3" })); // write more lines - writer.write(Arrays.asList(new String[] { "testLine4", "testLine5" })); + writer.write(Chunk.of(new String[] { "testLine4", "testLine5" })); // get restart data writer.update(executionContext); // close template @@ -324,7 +326,7 @@ class FlatFileItemWriterTests { // init with correct data writer.open(executionContext); // write more lines - writer.write(Arrays.asList(new String[] { "testLine6", "testLine7", "testLine8" })); + writer.write(Chunk.of(new String[] { "testLine6", "testLine7", "testLine8" })); // get statistics writer.update(executionContext); // close template @@ -362,7 +364,7 @@ class FlatFileItemWriterTests { @Override public Void doInTransaction(TransactionStatus status) { try { - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); assertEquals(expectedInTransaction, readLine()); } catch (Exception e) { @@ -396,9 +398,9 @@ class FlatFileItemWriterTests { public Void doInTransaction(TransactionStatus status) { try { // write some lines - writer.write(Arrays.asList(new String[] { "testLine1", "testLine2", "testLine3" })); + writer.write(Chunk.of(new String[] { "testLine1", "testLine2", "testLine3" })); // write more lines - writer.write(Arrays.asList(new String[] { "testLine4", "testLine5" })); + writer.write(Chunk.of(new String[] { "testLine4", "testLine5" })); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -419,7 +421,7 @@ class FlatFileItemWriterTests { public Void doInTransaction(TransactionStatus status) { try { // write more lines - writer.write(Arrays.asList(new String[] { "testLine6", "testLine7", "testLine8" })); + writer.write(Chunk.of(new String[] { "testLine6", "testLine7", "testLine8" })); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -476,9 +478,9 @@ class FlatFileItemWriterTests { public Void doInTransaction(TransactionStatus status) { try { // write some lines - writer.write(Arrays.asList(new String[] { "téstLine1", "téstLine2", "téstLine3" })); + writer.write(Chunk.of(new String[] { "téstLine1", "téstLine2", "téstLine3" })); // write more lines - writer.write(Arrays.asList(new String[] { "téstLine4", "téstLine5" })); + writer.write(Chunk.of(new String[] { "téstLine4", "téstLine5" })); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -499,7 +501,7 @@ class FlatFileItemWriterTests { public Void doInTransaction(TransactionStatus status) { try { // write more lines - writer.write(Arrays.asList(new String[] { "téstLine6", "téstLine7", "téstLine8" })); + writer.write(Chunk.of(new String[] { "téstLine6", "téstLine7", "téstLine8" })); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -571,17 +573,17 @@ class FlatFileItemWriterTests { // Try and write after the exception on open: writer.setEncoding("UTF-8"); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); } @Test void testWriteStringWithEncodingAfterClose() throws Exception { writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); writer.setEncoding("UTF-8"); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); String lineFromFile = readLine(); assertEquals(TEST_STRING, lineFromFile); @@ -598,7 +600,7 @@ class FlatFileItemWriterTests { }); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); assertEquals(TEST_STRING, readLine()); assertEquals("a", readLine()); @@ -616,7 +618,7 @@ class FlatFileItemWriterTests { }); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); String lineFromFile = readLine(); assertEquals("a", lineFromFile); @@ -637,14 +639,14 @@ class FlatFileItemWriterTests { }); writer.setAppendAllowed(true); writer.open(executionContext); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.close(); assertEquals("a", readLine()); assertEquals("b", readLine()); assertEquals("test1", readLine()); closeReader(); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("a", readLine()); assertEquals("b", readLine()); assertEquals("test1", readLine()); @@ -677,7 +679,7 @@ class FlatFileItemWriterTests { writer.close(); assertFalse(outputFile.exists()); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("test2", readLine()); } @@ -699,7 +701,7 @@ class FlatFileItemWriterTests { assertFalse(outputFile.exists()); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); assertEquals("a", readLine()); assertEquals("b", readLine()); assertEquals("test2", readLine()); @@ -709,7 +711,7 @@ class FlatFileItemWriterTests { void testDeleteOnExitNoRecordsWrittenAfterRestart() throws Exception { writer.setShouldDeleteIfEmpty(true); writer.open(executionContext); - writer.write(Collections.singletonList("test2")); + writer.write(Chunk.of("test2")); writer.update(executionContext); writer.close(); assertTrue(outputFile.exists()); @@ -729,10 +731,10 @@ class FlatFileItemWriterTests { }); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); String lineFromFile = readLine(); assertEquals("a", lineFromFile); @@ -755,9 +757,9 @@ class FlatFileItemWriterTests { }); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.update(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); String lineFromFile = readLine(); assertEquals("a", lineFromFile); @@ -766,7 +768,7 @@ class FlatFileItemWriterTests { lineFromFile = readLine(); assertEquals(TEST_STRING, lineFromFile); writer.open(executionContext); - writer.write(Collections.singletonList(TEST_STRING)); + writer.write(Chunk.of(TEST_STRING)); writer.close(); closeReader(); lineFromFile = readLine(); @@ -795,13 +797,7 @@ class FlatFileItemWriterTests { return item; } }); - List items = new ArrayList() { - { - add("1"); - add("2"); - add("3"); - } - }; + Chunk items = Chunk.of("1", "2", "3"); writer.open(executionContext); Exception expected = assertThrows(RuntimeException.class, () -> writer.write(items)); @@ -830,7 +826,7 @@ class FlatFileItemWriterTests { writer.open(executionContext); assertTrue(toBeCreated.exists(), "output file was created"); - writer.write(Collections.singletonList("test1")); + writer.write(Chunk.of("test1")); writer.close(); assertEquals("test1", readLine()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java index 81abdfe40..3098fbda8 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterFlatFileTests.java @@ -26,6 +26,8 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.file.transform.PassThroughLineAggregator; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.transaction.TransactionStatus; @@ -43,9 +45,9 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI */ private final class WriterCallback implements TransactionCallback { - private List list; + private Chunk list; - public WriterCallback(List list) { + public WriterCallback(Chunk list) { super(); this.list = list; } @@ -78,21 +80,21 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI super.setUp(delegate); tested.open(executionContext); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - tested.write(Arrays.asList("4")); + tested.write(Chunk.of("4")); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); - tested.write(Arrays.asList("5")); + tested.write(Chunk.of("5")); assertEquals("45", readFile(part2)); - tested.write(Arrays.asList("6", "7", "8", "9")); + tested.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(3)); assertTrue(part3.exists()); assertEquals("6789", readFile(part3)); @@ -107,7 +109,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI tested.update(executionContext); assertEquals(0, executionContext.getInt(tested.getExecutionContextKey("resource.item.count"))); assertEquals(1, executionContext.getInt(tested.getExecutionContextKey("resource.index"))); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); tested.update(executionContext); assertEquals(0, executionContext.getInt(tested.getExecutionContextKey("resource.item.count"))); assertEquals(2, executionContext.getInt(tested.getExecutionContextKey("resource.index"))); @@ -126,12 +128,12 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI super.setUp(delegate); tested.open(executionContext); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); - tested.write(Arrays.asList("4")); + tested.write(Chunk.of("4")); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); @@ -156,12 +158,12 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new WriterCallback(Arrays.asList("1", "2", "3"))); + new TransactionTemplate(transactionManager).execute(new WriterCallback(Chunk.of("1", "2", "3"))); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); - new TransactionTemplate(transactionManager).execute(new WriterCallback(Arrays.asList("4"))); + new TransactionTemplate(transactionManager).execute(new WriterCallback(Chunk.of("4"))); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); @@ -178,13 +180,13 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI super.setUp(delegate); tested.open(executionContext); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - tested.write(Arrays.asList("4")); + tested.write(Chunk.of("4")); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -194,10 +196,10 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI tested.open(executionContext); - tested.write(Arrays.asList("5")); + tested.write(Chunk.of("5")); assertEquals("45", readFile(part2)); - tested.write(Arrays.asList("6", "7", "8", "9")); + tested.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(3)); assertTrue(part3.exists()); assertEquals("6789", readFile(part3)); @@ -216,13 +218,13 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI super.setUp(delegate); tested.open(executionContext); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123f", readFile(part1)); - tested.write(Arrays.asList("4")); + tested.write(Chunk.of("4")); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -232,10 +234,10 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI tested.open(executionContext); - tested.write(Arrays.asList("5")); + tested.write(Chunk.of("5")); assertEquals("45f", readFile(part2)); - tested.write(Arrays.asList("6", "7", "8", "9")); + tested.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(3)); assertTrue(part3.exists()); assertEquals("6789f", readFile(part3)); @@ -255,13 +257,13 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager(); - new TransactionTemplate(transactionManager).execute(new WriterCallback(Arrays.asList("1", "2", "3"))); + new TransactionTemplate(transactionManager).execute(new WriterCallback(Chunk.of("1", "2", "3"))); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123f", readFile(part1)); - new TransactionTemplate(transactionManager).execute(new WriterCallback(Arrays.asList("4"))); + new TransactionTemplate(transactionManager).execute(new WriterCallback(Chunk.of("4"))); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -271,7 +273,7 @@ public class MultiResourceItemWriterFlatFileTests extends AbstractMultiResourceI tested.open(executionContext); - new TransactionTemplate(transactionManager).execute(new WriterCallback(Arrays.asList("5"))); + new TransactionTemplate(transactionManager).execute(new WriterCallback(Chunk.of("5"))); assertEquals("45f", readFile(part2)); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterXmlTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterXmlTests.java index ea0fc9640..deb68f2d0 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterXmlTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/MultiResourceItemWriterXmlTests.java @@ -28,6 +28,8 @@ import javax.xml.transform.Result; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.xml.StaxEventItemWriter; import org.springframework.batch.item.xml.StaxTestUtils; import org.springframework.oxm.Marshaller; @@ -95,12 +97,12 @@ class MultiResourceItemWriterXmlTests extends AbstractMultiResourceItemWriterTes super.setUp(delegate); tested.open(executionContext); - tested.write(Arrays.asList("1", "2", "3")); + tested.write(Chunk.of("1", "2", "3")); File part1 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(1)); assertTrue(part1.exists()); - tested.write(Arrays.asList("4")); + tested.write(Chunk.of("4")); File part2 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(2)); assertTrue(part2.exists()); @@ -112,9 +114,9 @@ class MultiResourceItemWriterXmlTests extends AbstractMultiResourceItemWriterTes tested.open(executionContext); - tested.write(Arrays.asList("5")); + tested.write(Chunk.of("5")); - tested.write(Arrays.asList("6", "7", "8", "9")); + tested.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(file.getAbsolutePath() + suffixCreator.getSuffix(3)); assertTrue(part3.exists()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java index 6a80f5bef..7e82cc6aa 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java @@ -24,6 +24,7 @@ import java.util.Arrays; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor; @@ -83,7 +84,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -105,7 +106,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -126,7 +127,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -147,7 +148,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -169,7 +170,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -190,7 +191,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); @@ -212,7 +213,7 @@ class FlatFileItemWriterBuilderTests { writer.open(executionContext); - writer.write(Arrays.asList(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); + writer.write(Chunk.of(new Foo(1, 2, "3"), new Foo(4, 5, "6"))); writer.close(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java index c06f1cf09..582e08a3f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/MultiResourceItemWriterBuilderTests.java @@ -25,6 +25,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.MultiResourceItemWriter; @@ -40,6 +41,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Glenn Renfro + * @author Mahmoud Ben Hassine */ class MultiResourceItemWriterBuilderTests { @@ -82,21 +84,21 @@ class MultiResourceItemWriterBuilderTests { this.writer.open(this.executionContext); - this.writer.write(Arrays.asList("1", "2", "3")); + this.writer.write(Chunk.of("1", "2", "3")); File part1 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - this.writer.write(Arrays.asList("4")); + this.writer.write(Chunk.of("4")); File part2 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); - this.writer.write(Arrays.asList("5")); + this.writer.write(Chunk.of("5")); assertEquals("45", readFile(part2)); - this.writer.write(Arrays.asList("6", "7", "8", "9")); + this.writer.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(3)); assertTrue(part3.exists()); assertEquals("6789", readFile(part3)); @@ -112,13 +114,13 @@ class MultiResourceItemWriterBuilderTests { this.writer.open(this.executionContext); - this.writer.write(Arrays.asList("1", "2", "3")); + this.writer.write(Chunk.of("1", "2", "3")); File part1 = new File(this.file.getAbsolutePath() + simpleResourceSuffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - this.writer.write(Arrays.asList("4")); + this.writer.write(Chunk.of("4")); File part2 = new File(this.file.getAbsolutePath() + simpleResourceSuffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -134,7 +136,7 @@ class MultiResourceItemWriterBuilderTests { this.writer.update(this.executionContext); assertEquals(0, this.executionContext.getInt(this.writer.getExecutionContextKey("resource.item.count"))); assertEquals(1, this.executionContext.getInt(this.writer.getExecutionContextKey("resource.index"))); - this.writer.write(Arrays.asList("1", "2", "3")); + this.writer.write(Chunk.of("1", "2", "3")); this.writer.update(this.executionContext); assertEquals(0, this.executionContext.getInt(this.writer.getExecutionContextKey("resource.item.count"))); assertEquals(2, this.executionContext.getInt(this.writer.getExecutionContextKey("resource.index"))); @@ -147,13 +149,13 @@ class MultiResourceItemWriterBuilderTests { .resource(new FileSystemResource(this.file)).resourceSuffixCreator(this.suffixCreator) .itemCountLimitPerResource(2).saveState(true).name("foo").build(); - this.writer.write(Arrays.asList("1", "2", "3")); + this.writer.write(Chunk.of("1", "2", "3")); File part1 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - this.writer.write(Arrays.asList("4")); + this.writer.write(Chunk.of("4")); File part2 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -162,10 +164,10 @@ class MultiResourceItemWriterBuilderTests { this.writer.close(); this.writer.open(this.executionContext); - this.writer.write(Arrays.asList("5")); + this.writer.write(Chunk.of("5")); assertEquals("45", readFile(part2)); - this.writer.write(Arrays.asList("6", "7", "8", "9")); + this.writer.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(3)); assertTrue(part3.exists()); assertEquals("6789", readFile(part3)); @@ -178,13 +180,13 @@ class MultiResourceItemWriterBuilderTests { .resource(new FileSystemResource(this.file)).resourceSuffixCreator(this.suffixCreator) .itemCountLimitPerResource(2).saveState(false).name("foo").build(); - this.writer.write(Arrays.asList("1", "2", "3")); + this.writer.write(Chunk.of("1", "2", "3")); File part1 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(1)); assertTrue(part1.exists()); assertEquals("123", readFile(part1)); - this.writer.write(Arrays.asList("4")); + this.writer.write(Chunk.of("4")); File part2 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(2)); assertTrue(part2.exists()); assertEquals("4", readFile(part2)); @@ -193,10 +195,10 @@ class MultiResourceItemWriterBuilderTests { this.writer.close(); this.writer.open(this.executionContext); - this.writer.write(Arrays.asList("5")); + this.writer.write(Chunk.of("5")); assertEquals("4", readFile(part2)); - this.writer.write(Arrays.asList("6", "7", "8", "9")); + this.writer.write(Chunk.of("6", "7", "8", "9")); File part3 = new File(this.file.getAbsolutePath() + this.suffixCreator.getSuffix(1)); assertTrue(part3.exists()); assertEquals("56789", readFile(part3)); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/JmsItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/JmsItemWriterTests.java index 59cbd7a85..5cf6c60eb 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/JmsItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/JmsItemWriterTests.java @@ -22,6 +22,8 @@ import static org.mockito.Mockito.mock; import java.util.Arrays; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.jms.core.JmsOperations; import org.springframework.jms.core.JmsTemplate; @@ -36,7 +38,7 @@ class JmsItemWriterTests { jmsTemplate.convertAndSend("bar"); itemWriter.setJmsTemplate(jmsTemplate); - itemWriter.write(Arrays.asList("foo", "bar")); + itemWriter.write(Chunk.of("foo", "bar")); } @Test diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/builder/JmsItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/builder/JmsItemWriterBuilderTests.java index b0e310a94..9c12c4c3c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/builder/JmsItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/jms/builder/JmsItemWriterBuilderTests.java @@ -21,6 +21,7 @@ import java.util.Arrays; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.jms.JmsItemWriter; import org.springframework.jms.core.JmsOperations; @@ -41,7 +42,7 @@ class JmsItemWriterBuilderTests { JmsOperations jmsTemplate = mock(JmsOperations.class); JmsItemWriter itemWriter = new JmsItemWriterBuilder().jmsTemplate(jmsTemplate).build(); ArgumentCaptor argCaptor = ArgumentCaptor.forClass(String.class); - itemWriter.write(Arrays.asList("foo", "bar")); + itemWriter.write(Chunk.of("foo", "bar")); verify(jmsTemplate, times(2)).convertAndSend(argCaptor.capture()); assertEquals("foo", argCaptor.getAllValues().get(0), "Expected foo"); assertEquals("bar", argCaptor.getAllValues().get(1), "Expected bar"); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterFunctionalTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterFunctionalTests.java index 38fb618e4..60d03a3e8 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterFunctionalTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterFunctionalTests.java @@ -30,6 +30,7 @@ import java.util.List; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.batch.item.json.builder.JsonFileItemWriterBuilder; @@ -76,7 +77,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(new ExecutionContext()); - writer.write(Arrays.asList(this.trade1, this.trade2)); + writer.write(Chunk.of(this.trade1, this.trade2)); writer.close(); // then @@ -93,8 +94,8 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(new ExecutionContext()); - writer.write(Arrays.asList(this.trade1, this.trade2)); - writer.write(Arrays.asList(this.trade3, this.trade4)); + writer.write(Chunk.of(this.trade1, this.trade2)); + writer.write(Chunk.of(this.trade3, this.trade4)); writer.close(); // then @@ -112,7 +113,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(new ExecutionContext()); - writer.write(Arrays.asList(this.trade1, this.trade2)); + writer.write(Chunk.of(this.trade1, this.trade2)); writer.close(); // when @@ -133,7 +134,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(new ExecutionContext()); - writer.write(Arrays.asList(this.trade1, this.trade2)); + writer.write(Chunk.of(this.trade1, this.trade2)); writer.close(); // then @@ -151,7 +152,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(new ExecutionContext()); - writer.write(Collections.singletonList(this.trade1)); + writer.write(Chunk.of(this.trade1)); writer.close(); // then @@ -169,10 +170,10 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(executionContext); - writer.write(Collections.singletonList(this.trade1)); + writer.write(Chunk.of(this.trade1)); writer.close(); writer.open(executionContext); - writer.write(Collections.singletonList(this.trade2)); + writer.write(Chunk.of(this.trade2)); writer.close(); // then @@ -191,7 +192,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(executionContext); // write some lines - writer.write(Collections.singletonList(this.trade1)); + writer.write(Chunk.of(this.trade1)); // get restart data writer.update(executionContext); // close template @@ -200,7 +201,7 @@ abstract class JsonFileItemWriterFunctionalTests { // init with correct data writer.open(executionContext); // write more lines - writer.write(Collections.singletonList(this.trade2)); + writer.write(Chunk.of(this.trade2)); // get statistics writer.update(executionContext); // close template @@ -229,7 +230,7 @@ abstract class JsonFileItemWriterFunctionalTests { new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { try { // write some lines - writer.write(Collections.singletonList(this.trade1)); + writer.write(Chunk.of(this.trade1)); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -247,7 +248,7 @@ abstract class JsonFileItemWriterFunctionalTests { new TransactionTemplate(transactionManager).execute((TransactionCallback) status -> { try { // write more lines - writer.write(Collections.singletonList(this.trade2)); + writer.write(Chunk.of(this.trade2)); } catch (Exception e) { throw new UnexpectedInputException("Could not write data", e); @@ -279,7 +280,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(executionContext); - Exception exception = assertThrows(IllegalArgumentException.class, () -> writer.write(List.of(this.trade1))); + Exception exception = assertThrows(IllegalArgumentException.class, () -> writer.write(Chunk.of(this.trade1))); assertEquals("Bad item", exception.getMessage()); writer.close(); @@ -303,7 +304,7 @@ abstract class JsonFileItemWriterFunctionalTests { // when writer.open(executionContext); - writer.write(Collections.singletonList(this.trade1)); + writer.write(Chunk.of(this.trade1)); writer.close(); // then diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterTests.java index f977ffe0f..e085213b9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/json/JsonFileItemWriterTests.java @@ -27,6 +27,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.WritableResource; @@ -67,7 +68,7 @@ class JsonFileItemWriterTests { // when writer.open(new ExecutionContext()); - writer.write(Arrays.asList("foo", "bar")); + writer.write(Chunk.of("foo", "bar")); writer.close(); // then diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/kafka/KafkaItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/kafka/KafkaItemWriterTests.java index 8737f42c0..069376803 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/kafka/KafkaItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/kafka/KafkaItemWriterTests.java @@ -25,6 +25,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; + +import org.springframework.batch.item.Chunk; import org.springframework.core.convert.converter.Converter; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; @@ -80,10 +82,11 @@ class KafkaItemWriterTests { @Test void testBasicWrite() throws Exception { - List items = Arrays.asList("val1", "val2"); + Chunk chunk = Chunk.of("val1", "val2"); - this.writer.write(items); + this.writer.write(chunk); + List items = chunk.getItems(); verify(this.kafkaTemplate).sendDefault(items.get(0), items.get(0)); verify(this.kafkaTemplate).sendDefault(items.get(1), items.get(1)); verify(this.kafkaTemplate).flush(); @@ -92,11 +95,12 @@ class KafkaItemWriterTests { @Test void testBasicDelete() throws Exception { - List items = Arrays.asList("val1", "val2"); + Chunk chunk = Chunk.of("val1", "val2"); this.writer.setDelete(true); - this.writer.write(items); + this.writer.write(chunk); + List items = chunk.getItems(); verify(this.kafkaTemplate).sendDefault(items.get(0), null); verify(this.kafkaTemplate).sendDefault(items.get(1), null); verify(this.kafkaTemplate).flush(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java index 49ee5431c..4485d4031 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/SimpleMailMessageItemWriterTests.java @@ -32,6 +32,7 @@ import jakarta.mail.MessagingException; 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; @@ -64,7 +65,7 @@ class SimpleMailMessageItemWriterTests { SimpleMailMessage bar = new SimpleMailMessage(); SimpleMailMessage[] items = new SimpleMailMessage[] { foo, bar }; - writer.write(Arrays.asList(items)); + writer.write(Chunk.of(items)); // Spring 4.1 changed the send method to be vargs instead of an array if (ReflectionUtils.findMethod(SimpleMailMessage.class, "send", SimpleMailMessage[].class) != null) { @@ -93,7 +94,7 @@ class SimpleMailMessageItemWriterTests { when(mailSender).thenThrow(new MailSendException( Collections.singletonMap((Object) foo, (Exception) new MessagingException("FOO")))); - assertThrows(MailSendException.class, () -> writer.write(List.of(items))); + assertThrows(MailSendException.class, () -> writer.write(Chunk.of(items))); } @Test @@ -122,7 +123,7 @@ class SimpleMailMessageItemWriterTests { when(mailSender).thenThrow(new MailSendException( Collections.singletonMap((Object) foo, (Exception) new MessagingException("FOO")))); - writer.write(Arrays.asList(items)); + writer.write(Chunk.of(items)); assertEquals("FOO", content.get()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java index 596cb89d7..7a0838180 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/builder/SimpleMailMessageItemWriterBuilderTests.java @@ -26,6 +26,7 @@ import jakarta.mail.MessagingException; 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; @@ -67,7 +68,7 @@ class SimpleMailMessageItemWriterBuilderTests { SimpleMailMessageItemWriter writer = new SimpleMailMessageItemWriterBuilder().mailSender(this.mailSender) .build(); - writer.write(Arrays.asList(this.items)); + writer.write(Chunk.of(this.items)); verify(this.mailSender).send(this.foo, this.bar); } @@ -86,7 +87,7 @@ class SimpleMailMessageItemWriterBuilderTests { this.mailSender.send(this.foo, this.bar); when(this.mailSender) .thenThrow(new MailSendException(Collections.singletonMap(this.foo, new MessagingException("FOO")))); - assertThrows(MailSendException.class, () -> writer.write(List.of(this.items))); + assertThrows(MailSendException.class, () -> writer.write(Chunk.of(this.items))); } @Test @@ -103,7 +104,7 @@ class SimpleMailMessageItemWriterBuilderTests { this.mailSender.send(this.foo, this.bar); when(this.mailSender) .thenThrow(new MailSendException(Collections.singletonMap(this.foo, new MessagingException("FOO")))); - writer.write(Arrays.asList(this.items)); + writer.write(Chunk.of(this.items)); assertEquals("FOO", content.get()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java index ee9811451..51b7625d7 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/mail/javamail/MimeMessageItemWriterTests.java @@ -33,6 +33,8 @@ import jakarta.mail.internet.MimeMessage; 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; @@ -70,7 +72,7 @@ class MimeMessageItemWriterTests { mailSender.send(aryEq(items)); - writer.write(Arrays.asList(items)); + writer.write(Chunk.of(items)); } @@ -92,7 +94,7 @@ class MimeMessageItemWriterTests { when(mailSender).thenThrow(new MailSendException( Collections.singletonMap((Object) foo, (Exception) new MessagingException("FOO")))); - assertThrows(MailSendException.class, () -> writer.write(List.of(items))); + assertThrows(MailSendException.class, () -> writer.write(Chunk.of(items))); } @Test @@ -121,7 +123,7 @@ class MimeMessageItemWriterTests { when(mailSender).thenThrow(new MailSendException( Collections.singletonMap((Object) foo, (Exception) new MessagingException("FOO")))); - writer.write(Arrays.asList(items)); + writer.write(Chunk.of(items)); assertEquals("FOO", content.get()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/AbstractSynchronizedItemStreamWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/AbstractSynchronizedItemStreamWriterTests.java index e6e0b5bac..ae6bf5bec 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/AbstractSynchronizedItemStreamWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/AbstractSynchronizedItemStreamWriterTests.java @@ -26,6 +26,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamWriter; @@ -34,6 +36,7 @@ import org.springframework.batch.item.ItemStreamWriter; * {@link org.springframework.batch.item.support.builder.SynchronizedItemStreamWriterBuilderTests} * * @author Dimitrios Liapis + * @author Mahmoud Ben Hassine * */ @ExtendWith(MockitoExtension.class) @@ -44,7 +47,7 @@ public abstract class AbstractSynchronizedItemStreamWriterTests { private SynchronizedItemStreamWriter synchronizedItemStreamWriter; - private final List testList = Collections.unmodifiableList(new ArrayList<>()); + private final Chunk testList = new Chunk(); private final ExecutionContext testExecutionContext = new ExecutionContext(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java index bcb48945c..3ee4a712b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/ClassifierCompositeItemWriterTests.java @@ -21,48 +21,52 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.classify.PatternMatchingClassifier; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Dave Syer * @author Glenn Renfro + * @author Mahmoud Ben Hassine * */ class ClassifierCompositeItemWriterTests { private final ClassifierCompositeItemWriter writer = new ClassifierCompositeItemWriter<>(); - private final List defaults = new ArrayList<>(); + private final Chunk defaults = new Chunk<>(); - private final List foos = new ArrayList<>(); + private final Chunk foos = new Chunk<>(); @Test void testWrite() throws Exception { - Map> map = new HashMap<>(); + Map> map = new HashMap<>(); ItemWriter fooWriter = new ItemWriter() { @Override - public void write(List items) throws Exception { - foos.addAll(items); + public void write(Chunk chunk) throws Exception { + foos.addAll(chunk.getItems()); } }; ItemWriter defaultWriter = new ItemWriter() { @Override - public void write(List items) throws Exception { - defaults.addAll(items); + public void write(Chunk chunk) throws Exception { + defaults.addAll(chunk.getItems()); } }; map.put("foo", fooWriter); map.put("*", defaultWriter); - writer.setClassifier(new PatternMatchingClassifier<>(map)); - writer.write(Arrays.asList("foo", "foo", "one", "two", "three")); - assertEquals("[foo, foo]", foos.toString()); - assertEquals("[one, two, three]", defaults.toString()); + writer.setClassifier(new PatternMatchingClassifier(map)); + writer.write(Chunk.of("foo", "foo", "one", "two", "three")); + assertIterableEquals(Chunk.of("foo", "foo"), foos); + assertIterableEquals(Chunk.of("one", "two", "three"), defaults); } @Test diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java index 10c312dd5..54221d280 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java @@ -21,6 +21,8 @@ import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamWriter; import org.springframework.batch.item.ItemWriter; @@ -30,6 +32,7 @@ import org.springframework.batch.item.ItemWriter; * * @author Robert Kasanicky * @author Will Schipp + * @author Mahmoud Ben Hassine */ class CompositeItemWriterTests { @@ -43,7 +46,7 @@ class CompositeItemWriterTests { void testProcess() throws Exception { final int NUMBER_OF_WRITERS = 10; - List data = Collections.singletonList(new Object()); + Chunk data = Chunk.of(new Object()); List> writers = new ArrayList<>(); @@ -74,7 +77,7 @@ class CompositeItemWriterTests { private void doTestItemStream(boolean expectOpen) throws Exception { @SuppressWarnings("unchecked") ItemStreamWriter writer = mock(ItemStreamWriter.class); - List data = Collections.singletonList(new Object()); + Chunk data = Chunk.of(new Object()); ExecutionContext executionContext = new ExecutionContext(); if (expectOpen) { writer.open(executionContext); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java index d35a8452f..d144a4f65 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/ClassifierCompositeItemWriterBuilderTests.java @@ -24,35 +24,48 @@ import java.util.Map; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.support.ClassifierCompositeItemWriter; import org.springframework.classify.PatternMatchingClassifier; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Glenn Renfro + * @author Mahmoud Ben Hassine */ class ClassifierCompositeItemWriterBuilderTests { - private final List defaults = new ArrayList<>(); + private final Chunk defaults = new Chunk(); - private final List foos = new ArrayList<>(); + private final Chunk foos = new Chunk(); @Test void testWrite() throws Exception { Map> map = new HashMap<>(); - ItemWriter fooWriter = items -> foos.addAll(items); - ItemWriter defaultWriter = items -> defaults.addAll(items); + ItemWriter fooWriter = new ItemWriter() { + @Override + public void write(Chunk chunk) throws Exception { + foos.addAll(chunk.getItems()); + } + }; + ItemWriter defaultWriter = new ItemWriter() { + @Override + public void write(Chunk chunk) throws Exception { + defaults.addAll(chunk.getItems()); + } + }; map.put("foo", fooWriter); map.put("*", defaultWriter); ClassifierCompositeItemWriter writer = new ClassifierCompositeItemWriterBuilder() .classifier(new PatternMatchingClassifier<>(map)).build(); - writer.write(Arrays.asList("foo", "foo", "one", "two", "three")); - assertEquals("[foo, foo]", foos.toString()); - assertEquals("[one, two, three]", defaults.toString()); + writer.write(Chunk.of("foo", "foo", "one", "two", "three")); + assertIterableEquals(Chunk.of("foo", "foo"), foos); + assertIterableEquals(Chunk.of("one", "two", "three"), defaults); } @Test diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/CompositeItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/CompositeItemWriterBuilderTests.java index cb4987b99..7130f4e3c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/CompositeItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/builder/CompositeItemWriterBuilderTests.java @@ -22,6 +22,7 @@ import java.util.List; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamWriter; import org.springframework.batch.item.ItemWriter; @@ -34,6 +35,7 @@ import static org.mockito.Mockito.verify; /** * @author Glenn Renfro * @author Drummond Dawson + * @author Mahmoud Ben Hassine */ class CompositeItemWriterBuilderTests { @@ -42,7 +44,7 @@ class CompositeItemWriterBuilderTests { void testProcess() throws Exception { final int NUMBER_OF_WRITERS = 10; - List data = Collections.singletonList(new Object()); + Chunk data = Chunk.of(new Object()); List> writers = new ArrayList<>(); @@ -63,7 +65,7 @@ class CompositeItemWriterBuilderTests { @SuppressWarnings("unchecked") void testProcessVarargs() throws Exception { - List data = Collections.singletonList(new Object()); + Chunk data = Chunk.of(new Object()); List> writers = new ArrayList<>(); @@ -90,7 +92,7 @@ class CompositeItemWriterBuilderTests { @SuppressWarnings("unchecked") private void ignoreItemStream(boolean ignoreItemStream) throws Exception { ItemStreamWriter writer = mock(ItemStreamWriter.class); - List data = Collections.singletonList(new Object()); + Chunk data = Chunk.of(new Object()); ExecutionContext executionContext = new ExecutionContext(); List> writers = new ArrayList<>(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java index fb64db327..b3002be6a 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/AbstractStaxEventWriterItemWriterTests.java @@ -30,6 +30,7 @@ import org.xmlunit.diff.DefaultNodeMatcher; import org.xmlunit.diff.ElementSelectors; import org.xmlunit.matchers.CompareMatcher; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.xml.domain.Trade; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; @@ -60,13 +61,9 @@ abstract class AbstractStaxEventWriterItemWriterTests { protected Resource expected = new ClassPathResource("expected-output.xml", getClass()); - protected List objects = new ArrayList() { - { - add(new Trade("isin1", 1, new BigDecimal(1.0), "customer1")); - add(new Trade("isin2", 2, new BigDecimal(2.0), "customer2")); - add(new Trade("isin3", 3, new BigDecimal(3.0), "customer3")); - } - }; + protected Chunk objects = Chunk.of(new Trade("isin1", 1, new BigDecimal(1.0), "customer1"), + new Trade("isin2", 2, new BigDecimal(2.0), "customer2"), + new Trade("isin3", 3, new BigDecimal(3.0), "customer3")); /** * Write list of domain objects and check the output file. diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java index 22415ba38..c4efe88d3 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/Jaxb2NamespaceMarshallingTests.java @@ -30,6 +30,7 @@ import org.junit.jupiter.api.Test; import org.xmlunit.builder.Input; import org.xmlunit.matchers.CompareMatcher; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.xml.domain.QualifiedTrade; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; @@ -62,7 +63,7 @@ class Jaxb2NamespaceMarshallingTests { private final Resource expected = new ClassPathResource("expected-qualified-output.xml", getClass()); - private final List objects = List.of( + private final Chunk objects = Chunk.of( new QualifiedTrade("isin1", 1, new BigDecimal(1.0), "customer1"), new QualifiedTrade("isin2", 2, new BigDecimal(2.0), "customer2"), new QualifiedTrade("isin3", 3, new BigDecimal(3.0), "customer3")); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java index a45629aa5..f90f166bd 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java @@ -29,6 +29,7 @@ import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.UnexpectedInputException; import org.springframework.batch.item.WriterNotOpenException; @@ -87,11 +88,11 @@ class StaxEventItemWriterTests { } }; - private final List items = List.of(item); + private final Chunk items = Chunk.of(item); - private final List itemsMultiByte = List.of(itemMultiByte); + private final Chunk itemsMultiByte = Chunk.of(itemMultiByte); - private final List jaxbItems = List.of(jaxbItem); + private final Chunk jaxbItems = Chunk.of(jaxbItem); private static final String TEST_STRING = "<" + ClassUtils.getShortName(StaxEventItemWriter.class) + "-testString/>"; @@ -138,7 +139,7 @@ class StaxEventItemWriterTests { void testAssertWriterIsInitialized() { StaxEventItemWriter writer = new StaxEventItemWriter<>(); - assertThrows(WriterNotOpenException.class, () -> writer.write(List.of("foo"))); + assertThrows(WriterNotOpenException.class, () -> writer.write(Chunk.of("foo"))); } @Test diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java index 15e0d169a..ed09bf52e 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/TransactionalStaxEventItemWriterTests.java @@ -31,6 +31,8 @@ import javax.xml.transform.Result; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.support.transaction.ResourcelessTransactionManager; import org.springframework.core.io.FileSystemResource; @@ -67,7 +69,7 @@ class TransactionalStaxEventItemWriterTests { } }; - private final List items = List.of(item); + private final Chunk items = Chunk.of(item); private static final String TEST_STRING = ""; diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/builder/StaxEventItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/builder/StaxEventItemWriterBuilderTests.java index b2ddbc344..9795a76e2 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/builder/StaxEventItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/builder/StaxEventItemWriterBuilderTests.java @@ -30,6 +30,7 @@ import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.xml.StaxEventItemWriter; @@ -54,7 +55,7 @@ class StaxEventItemWriterBuilderTests { private WritableResource resource; - private List items; + private Chunk items; private Marshaller marshaller; @@ -73,7 +74,7 @@ class StaxEventItemWriterBuilderTests { this.resource = new FileSystemResource( File.createTempFile("StaxEventItemWriterBuilderTests", ".xml", directory)); - this.items = new ArrayList<>(3); + this.items = new Chunk<>(); this.items.add(new Foo(1, "two", "three")); this.items.add(new Foo(4, "five", "six")); this.items.add(new Foo(7, "eight", "nine")); @@ -99,7 +100,7 @@ class StaxEventItemWriterBuilderTests { staxEventItemWriter.afterPropertiesSet(); staxEventItemWriter.open(executionContext); - staxEventItemWriter.write(Collections.emptyList()); + staxEventItemWriter.write(new Chunk()); staxEventItemWriter.update(executionContext); staxEventItemWriter.close(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/AbstractTradeBatchTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/AbstractTradeBatchTests.java index 222c69dde..b447fc8f3 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/AbstractTradeBatchTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/AbstractTradeBatchTests.java @@ -19,6 +19,8 @@ package org.springframework.batch.repeat.support; import java.util.List; import org.junit.jupiter.api.BeforeEach; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; @@ -33,6 +35,7 @@ import org.springframework.core.io.Resource; * Base class for simple tests with small trade data set. * * @author Dave Syer + * @author Mahmoud Ben Hassine * */ abstract class AbstractTradeBatchTests { @@ -81,7 +84,7 @@ abstract class AbstractTradeBatchTests { // This has to be synchronized because we are going to test the state // (count) at the end of a concurrent batch run. @Override - public synchronized void write(List data) { + public synchronized void write(Chunk data) { count++; System.out.println("Executing trade '" + data + "'"); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ItemReaderRepeatCallback.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ItemReaderRepeatCallback.java index 99c709fac..86f56b90c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ItemReaderRepeatCallback.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ItemReaderRepeatCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.batch.repeat.support; import java.util.Collections; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.repeat.RepeatStatus; @@ -25,6 +26,7 @@ import org.springframework.batch.repeat.RepeatContext; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ public class ItemReaderRepeatCallback implements RepeatCallback { @@ -55,7 +57,7 @@ public class ItemReaderRepeatCallback implements RepeatCallback { if (item == null) { return RepeatStatus.FINISHED; } - writer.write(Collections.singletonList(item)); + writer.write(Chunk.of(item)); return RepeatStatus.CONTINUABLE; } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java index cf81a21eb..124b3081e 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplateAsynchronousTests.java @@ -30,6 +30,8 @@ import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.repeat.RepeatCallback; import org.springframework.batch.repeat.RepeatContext; @@ -148,7 +150,7 @@ class TaskExecutorRepeatTemplateAsynchronousTests extends AbstractTradeBatchTest Thread.sleep(100); Trade item = provider.read(); if (item != null) { - processor.write(Collections.singletonList(item)); + processor.write(Chunk.of(item)); } return RepeatStatus.continueIf(item != null); } @@ -184,7 +186,7 @@ class TaskExecutorRepeatTemplateAsynchronousTests extends AbstractTradeBatchTest threadNames.add(Thread.currentThread().getName() + " : " + item); items.add("" + item); if (item != null) { - processor.write(Collections.singletonList(item)); + processor.write(Chunk.of(item)); // Do some more I/O for (int i = 0; i < 10; i++) { TradeItemReader provider = new TradeItemReader(resource); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java index 43299ab1a..5e0dda7fc 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java @@ -18,6 +18,8 @@ package org.springframework.batch.retry.jms; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; @@ -96,7 +98,7 @@ class ExternalRetryTests { final ItemWriter writer = new ItemWriter() { @Override - public void write(final List texts) { + public void write(final Chunk texts) { for (Object text : texts) { @@ -115,7 +117,7 @@ class ExternalRetryTests { try { final Object item = provider.read(); RetryCallback callback = context -> { - writer.write(Collections.singletonList(item)); + writer.write(Chunk.of(item)); return null; }; return retryTemplate.execute(callback, new DefaultRetryState(item)); @@ -137,7 +139,7 @@ class ExternalRetryTests { RetryCallback callback = new RetryCallback() { @Override public Object doWithRetry(RetryContext context) throws Exception { - writer.write(Collections.singletonList(item)); + writer.write(Chunk.of(item)); return null; } }; diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java index f5d4bcd60..65c4932fe 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2018 the original author or authors. + * Copyright 2006-2022 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. @@ -23,6 +23,7 @@ import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; @@ -59,7 +60,7 @@ public class AsyncItemWriter implements ItemStreamWriter>, Initiali * delegate * @throws Exception The exception returned by the Future if one was thrown */ - public void write(List> items) throws Exception { + public void write(Chunk> items) throws Exception { List list = new ArrayList<>(); for (Future future : items) { try { @@ -83,7 +84,7 @@ public class AsyncItemWriter implements ItemStreamWriter>, Initiali } } - delegate.write(list); + delegate.write(new Chunk<>(list)); } @Override diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java index 0141cbff8..a51a4d3f4 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,6 +30,7 @@ import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; @@ -92,7 +93,7 @@ public class ChunkMessageChannelItemWriter this.replyChannel = replyChannel; } - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { // Block until expecting <= throttle limit while (localState.getExpecting() > throttleLimit) { @@ -283,7 +284,7 @@ public class ChunkMessageChannelItemWriter return expected.get() - actual.get(); } - public ChunkRequest getRequest(List items) { + public ChunkRequest getRequest(Chunk items) { return new ChunkRequest<>(current.incrementAndGet(), items, getJobId(), createStepContribution()); } diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandler.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandler.java index 7ff9115bd..2ff1c65a2 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandler.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 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,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.JobInterruptedException; import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.step.item.Chunk; +import org.springframework.batch.item.Chunk; import org.springframework.batch.core.step.item.ChunkProcessor; import org.springframework.batch.core.step.item.FaultTolerantChunkProcessor; import org.springframework.batch.core.step.skip.NonSkippableReadException; @@ -40,6 +40,7 @@ import org.springframework.util.Assert; * * @author Dave Syer * @author Michael Minella + * @author Mahmoud Ben Hassine * @param the type of the items in the chunk to be handled */ @MessageEndpoint @@ -100,7 +101,7 @@ public class ChunkProcessorChunkHandler implements ChunkHandler, Initializ */ private Throwable process(ChunkRequest chunkRequest, StepContribution stepContribution) throws Exception { - Chunk chunk = new Chunk<>(chunkRequest.getItems()); + Chunk chunk = chunkRequest.getItems(); Throwable failure = null; try { chunkProcessor.process(stepContribution, chunk); diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java index 3ae79c6e2..eaa6f5b38 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,11 +20,13 @@ import java.io.Serializable; import java.util.Collection; import org.springframework.batch.core.StepContribution; +import org.springframework.batch.item.Chunk; /** * Encapsulation of a chunk of items to be processed remotely as part of a step execution. * * @author Dave Syer + * @author Mahmoud Ben Hassine * @param the type of the items to process */ public class ChunkRequest implements Serializable { @@ -33,13 +35,13 @@ public class ChunkRequest implements Serializable { private final long jobId; - private final Collection items; + private final Chunk items; private final StepContribution stepContribution; private final int sequence; - public ChunkRequest(int sequence, Collection items, long jobId, StepContribution stepContribution) { + public ChunkRequest(int sequence, Chunk items, long jobId, StepContribution stepContribution) { this.sequence = sequence; this.items = items; this.jobId = jobId; @@ -50,7 +52,7 @@ public class ChunkRequest implements Serializable { return jobId; } - public Collection getItems() { + public Chunk getItems() { return items; } diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java index d6ccd4325..538e9a60c 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -22,7 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.step.item.Chunk; +import org.springframework.batch.item.Chunk; import org.springframework.batch.core.step.item.ChunkOrientedTasklet; import org.springframework.batch.core.step.item.ChunkProcessor; import org.springframework.batch.core.step.item.FaultTolerantChunkProcessor; @@ -176,7 +176,7 @@ public class RemoteChunkHandlerFactoryBean implements FactoryBean inputs, Chunk outputs) throws Exception { - doWrite(outputs.getItems()); + doWrite(outputs); // Do not update the step contribution until the chunks are // actually processed updateStepContribution(contribution, stepContributionSource); diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java index 183b04f87..26d47af67 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/async/AsyncItemWriterTests.java @@ -27,6 +27,7 @@ import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamException; import org.springframework.batch.item.ItemStreamWriter; @@ -41,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author mminella + * @author Mahmoud Ben Hassine */ class AsyncItemWriterTests { @@ -60,7 +62,7 @@ class AsyncItemWriterTests { @Test void testRoseyScenario() throws Exception { writer.setDelegate(new ListItemWriter(writtenItems)); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); processedItems.add(new FutureTask<>(new Callable() { @Override @@ -90,7 +92,7 @@ class AsyncItemWriterTests { @Test void testFilteredItem() throws Exception { writer.setDelegate(new ListItemWriter(writtenItems)); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); processedItems.add(new FutureTask<>(new Callable() { @Override @@ -119,7 +121,7 @@ class AsyncItemWriterTests { @Test void testException() { writer.setDelegate(new ListItemWriter(writtenItems)); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); processedItems.add(new FutureTask<>(new Callable() { @Override @@ -147,7 +149,7 @@ class AsyncItemWriterTests { void testExecutionException() { ListItemWriter delegate = new ListItemWriter(writtenItems); writer.setDelegate(delegate); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); processedItems.add(new Future() { @@ -189,7 +191,7 @@ class AsyncItemWriterTests { ListItemStreamWriter itemWriter = new ListItemStreamWriter(writtenItems); writer.setDelegate(itemWriter); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); ExecutionContext executionContext = new ExecutionContext(); writer.open(executionContext); @@ -207,7 +209,7 @@ class AsyncItemWriterTests { ListItemWriter itemWriter = new ListItemWriter(writtenItems); writer.setDelegate(itemWriter); - List> processedItems = new ArrayList<>(); + Chunk> processedItems = new Chunk<>(); ExecutionContext executionContext = new ExecutionContext(); writer.open(executionContext); @@ -235,8 +237,8 @@ class AsyncItemWriterTests { } @Override - public void write(List items) throws Exception { - this.items.addAll(items); + public void write(Chunk chunk) throws Exception { + this.items.addAll(chunk.getItems()); } } @@ -256,8 +258,8 @@ class AsyncItemWriterTests { } @Override - public void write(List items) throws Exception { - this.items.addAll(items); + public void write(Chunk chunk) throws Exception { + this.items.addAll(chunk.getItems()); } @Override diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkMessageItemWriterIntegrationTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkMessageItemWriterIntegrationTests.java index 0234c9c55..7c6c2537d 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkMessageItemWriterIntegrationTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkMessageItemWriterIntegrationTests.java @@ -37,6 +37,7 @@ 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.core.step.factory.SimpleStepFactoryBean; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.support.ListItemReader; import org.springframework.beans.factory.annotation.Autowired; @@ -161,8 +162,8 @@ class ChunkMessageItemWriterIntegrationTests { stepExecution.getExecutionContext().putInt(ChunkMessageChannelItemWriter.EXPECTED, 6); stepExecution.getExecutionContext().putInt(ChunkMessageChannelItemWriter.ACTUAL, 4); // And make the back log real - requests.send(getSimpleMessage("foo", stepExecution.getJobExecution().getJobId())); - requests.send(getSimpleMessage("bar", stepExecution.getJobExecution().getJobId())); + requests.send(getSimpleMessage(stepExecution.getJobExecution().getJobId(), "foo")); + requests.send(getSimpleMessage(stepExecution.getJobExecution().getJobId(), "bar")); step.execute(stepExecution); waitForResults(8, 10); @@ -190,7 +191,7 @@ class ChunkMessageItemWriterIntegrationTests { writer.setMaxWaitTimeouts(2); // And make the back log real - requests.send(getSimpleMessage("foo", 4321L)); + requests.send(getSimpleMessage(4321L, "foo")); step.execute(stepExecution); assertEquals(BatchStatus.FAILED, stepExecution.getStatus()); assertEquals(ExitStatus.FAILED.getExitCode(), stepExecution.getExitStatus().getExitCode()); @@ -205,10 +206,10 @@ class ChunkMessageItemWriterIntegrationTests { } @SuppressWarnings({ "unchecked", "rawtypes" }) - private GenericMessage getSimpleMessage(String string, Long jobId) { + private GenericMessage getSimpleMessage(Long jobId, String... items) { StepContribution stepContribution = new JobExecution(new JobInstance(0L, "job"), new JobParameters()) .createStepExecution("step").createStepContribution(); - ChunkRequest chunk = new ChunkRequest(0, StringUtils.commaDelimitedListToSet(string), jobId, stepContribution); + ChunkRequest chunk = new ChunkRequest(0, Chunk.of(items), jobId, stepContribution); GenericMessage message = new GenericMessage<>(chunk); return message; } diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java index 9b66e0df7..b7be87965 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkProcessorChunkHandlerTests.java @@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.step.item.Chunk; +import org.springframework.batch.item.Chunk; import org.springframework.batch.core.step.item.ChunkProcessor; import org.springframework.batch.test.MetaDataInstanceFactory; import org.springframework.util.StringUtils; @@ -33,14 +33,20 @@ class ChunkProcessorChunkHandlerTests { @Test void testVanillaHandleChunk() throws Exception { + // given handler.setChunkProcessor(new ChunkProcessor() { public void process(StepContribution contribution, Chunk chunk) throws Exception { count += chunk.size(); } }); StepContribution stepContribution = MetaDataInstanceFactory.createStepExecution().createStepContribution(); - ChunkResponse response = handler.handleChunk( - new ChunkRequest<>(0, StringUtils.commaDelimitedListToSet("foo,bar"), 12L, stepContribution)); + Chunk items = Chunk.of("foo", "bar"); + ChunkRequest chunkRequest = new ChunkRequest<>(0, items, 12L, stepContribution); + + // when + ChunkResponse response = handler.handleChunk(chunkRequest); + + // then assertEquals(stepContribution, response.getStepContribution()); assertEquals(12, response.getJobId().longValue()); assertTrue(response.isSuccessful()); diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkRequestTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkRequestTests.java index b8c2c2cef..aab46d4f2 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkRequestTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/ChunkRequestTests.java @@ -21,16 +21,19 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Arrays; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.test.MetaDataInstanceFactory; import org.springframework.util.SerializationUtils; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class ChunkRequestTests { - private final ChunkRequest request = new ChunkRequest<>(0, Arrays.asList("foo", "bar"), 111L, + private final ChunkRequest request = new ChunkRequest<>(0, Chunk.of("foo", "bar"), 111L, MetaDataInstanceFactory.createStepExecution().createStepContribution()); @Test diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/TestItemWriter.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/TestItemWriter.java index 1dcec0903..b14dab188 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/TestItemWriter.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/chunk/TestItemWriter.java @@ -1,9 +1,26 @@ +/* + * Copyright 2022 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.batch.integration.chunk; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.stereotype.Component; @@ -37,7 +54,7 @@ public class TestItemWriter implements ItemWriter { */ public static final String WAIT_ON = "wait"; - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (T item : items) { diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/config/xml/RemoteChunkingParserTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/config/xml/RemoteChunkingParserTests.java index 9aa5b2ec1..c7c94d862 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/config/xml/RemoteChunkingParserTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/config/xml/RemoteChunkingParserTests.java @@ -25,6 +25,7 @@ import org.springframework.batch.integration.chunk.ChunkHandler; import org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter; import org.springframework.batch.integration.chunk.ChunkProcessorChunkHandler; import org.springframework.batch.integration.chunk.RemoteChunkHandlerFactoryBean; +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; @@ -251,7 +252,7 @@ class RemoteChunkingParserTests { private static class Writer implements ItemWriter { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { // } diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java index 31faecc5c..4f6c70d7b 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java @@ -22,6 +22,8 @@ import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; @@ -69,7 +71,7 @@ class MessagingGatewayIntegrationTests { @Test void testWriter() throws Exception { - writer.write(Arrays.asList("foo", "bar", "spam")); + writer.write(Chunk.of("foo", "bar", "spam")); assertEquals(3, splitter.count); assertEquals(3, service.count); } @@ -104,6 +106,7 @@ class MessagingGatewayIntegrationTests { * More complex splitters might filter or enhance the items before passing them on. * * @author Dave Syer + * @author Mahmoud Ben Hassine * */ @MessageEndpoint @@ -113,7 +116,7 @@ class MessagingGatewayIntegrationTests { private int count; @Splitter - public List split(List input) { + public Chunk split(Chunk input) { count += input.size(); return input; } diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/partition/ExampleItemWriter.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/partition/ExampleItemWriter.java index 59a9fb7e4..0818a3a4a 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/partition/ExampleItemWriter.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/partition/ExampleItemWriter.java @@ -1,9 +1,26 @@ +/* + * Copyright 2022 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. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.batch.integration.partition; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** @@ -14,9 +31,9 @@ public class ExampleItemWriter implements ItemWriter { private static final Log log = LogFactory.getLog(ExampleItemWriter.class); /** - * @see ItemWriter#write(List) + * @see ItemWriter#write(Chunk) */ - public void write(List data) throws Exception { + public void write(Chunk data) throws Exception { log.info(data); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/InfiniteLoopWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/InfiniteLoopWriter.java index fa55d3925..143d372ce 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/InfiniteLoopWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/InfiniteLoopWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** @@ -53,7 +54,7 @@ public class InfiniteLoopWriter implements StepExecutionListener, ItemWriter items) throws Exception { + public void write(Chunk items) throws Exception { try { Thread.sleep(500); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemWriter.java index 7c052710f..9a989ae74 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/common/StagingItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2019 the original author or authors. + * Copyright 2006-2022 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,6 +24,7 @@ import java.util.ListIterator; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.support.JdbcDaoSupport; @@ -72,14 +73,14 @@ public class StagingItemWriter extends JdbcDaoSupport implements StepExecutio * @see ItemWriter#write(java.util.List) */ @Override - public void write(final List items) { - final ListIterator itemIterator = items.listIterator(); + public void write(final Chunk chunk) { + final ListIterator itemIterator = chunk.getItems().listIterator(); getJdbcTemplate().batchUpdate("INSERT into BATCH_STAGING (ID, JOB_ID, VALUE, PROCESSED) values (?,?,?,?)", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { - return items.size(); + return chunk.size(); } @Override diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDao.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDao.java index 5eac26b36..a8d459a38 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDao.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.football.internal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.football.Game; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -38,7 +39,7 @@ public class JdbcGameDao extends JdbcDaoSupport implements ItemWriter { } @Override - public void write(List games) { + public void write(Chunk games) { for (Game game : games) { diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDao.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDao.java index 3ebf7707e..2b51bee73 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDao.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2012 the original author or authors. + * Copyright 2006-2022 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,6 +20,7 @@ import java.util.List; import javax.sql.DataSource; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.football.PlayerSummary; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -36,7 +37,7 @@ public class JdbcPlayerSummaryDao implements ItemWriter { private NamedParameterJdbcOperations namedParameterJdbcTemplate; @Override - public void write(List summaries) { + public void write(Chunk summaries) { for (PlayerSummary summary : summaries) { diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/PlayerItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/PlayerItemWriter.java index 7ed7575ac..ef3f9d3f1 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/PlayerItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/football/internal/PlayerItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.football.internal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.football.Player; import org.springframework.batch.sample.domain.football.PlayerDao; @@ -27,7 +28,7 @@ public class PlayerItemWriter implements ItemWriter { private PlayerDao playerDao; @Override - public void write(List players) throws Exception { + public void write(Chunk players) throws Exception { for (Player player : players) { playerDao.savePlayer(player); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/person/internal/PersonWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/person/internal/PersonWriter.java index 4e402fae1..0d6b2cba5 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/person/internal/PersonWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/person/internal/PersonWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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,6 +20,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.person.Person; @@ -28,7 +30,7 @@ public class PersonWriter implements ItemWriter { private static Log log = LogFactory.getLog(PersonWriter.class); @Override - public void write(List data) { + public void write(Chunk data) { if (log.isDebugEnabled()) { log.debug("Processing: " + data); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/CustomerUpdateWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/CustomerUpdateWriter.java index 03b0fc078..9947f069f 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/CustomerUpdateWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/CustomerUpdateWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,10 +18,12 @@ package org.springframework.batch.sample.domain.trade; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** * @author Lucas Ward + * @author Mahmoud Ben Hassine * */ public class CustomerUpdateWriter implements ItemWriter { @@ -29,7 +31,7 @@ public class CustomerUpdateWriter implements ItemWriter { private CustomerDao customerDao; @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (CustomerUpdate customerUpdate : items) { if (customerUpdate.getOperation() == CustomerOperation.ADD) { customerDao.insertCustomer(customerUpdate.getCustomerName(), customerUpdate.getCredit()); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditItemWriter.java index c376292ff..e19dc233a 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.trade.internal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.sample.domain.trade.CustomerCreditDao; @@ -26,6 +27,7 @@ import org.springframework.batch.sample.domain.trade.CustomerCreditDao; * Delegates actual writing to a custom DAO. * * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class CustomerCreditItemWriter implements ItemWriter { @@ -40,7 +42,7 @@ public class CustomerCreditItemWriter implements ItemWriter { } @Override - public void write(List customerCredits) throws Exception { + public void write(Chunk customerCredits) throws Exception { for (CustomerCredit customerCredit : customerCredits) { customerCreditDao.writeCredit(customerCredit); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateWriter.java index 0058afeec..c98a10c37 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2014 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.trade.internal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.sample.domain.trade.CustomerCreditDao; @@ -29,7 +30,7 @@ public class CustomerCreditUpdateWriter implements ItemWriter { private CustomerCreditDao dao; @Override - public void write(List customerCredits) throws Exception { + public void write(Chunk customerCredits) throws Exception { for (CustomerCredit customerCredit : customerCredits) { if (customerCredit.getCredit().doubleValue() > creditFilter) { dao.writeCredit(customerCredit); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateWriter.java index bb7c827a8..1021244a3 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.trade.internal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.CustomerDebit; import org.springframework.batch.sample.domain.trade.CustomerDebitDao; @@ -27,13 +28,14 @@ import org.springframework.batch.sample.domain.trade.Trade; * Transforms Trade to a CustomerDebit and asks DAO delegate to write the result. * * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class CustomerUpdateWriter implements ItemWriter { private CustomerDebitDao dao; @Override - public void write(List trades) { + public void write(Chunk trades) { for (Trade trade : trades) { CustomerDebit customerDebit = new CustomerDebit(); customerDebit.setName(trade.getCustomer()); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDao.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDao.java index 6ee22cc50..741da999e 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDao.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDao.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 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,6 +18,7 @@ package org.springframework.batch.sample.domain.trade.internal; import java.util.Collections; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemWriter; @@ -30,6 +31,7 @@ import org.springframework.beans.factory.DisposableBean; * * @see CustomerCreditDao * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class FlatFileCustomerCreditDao implements CustomerCreditDao, DisposableBean { @@ -48,7 +50,7 @@ public class FlatFileCustomerCreditDao implements CustomerCreditDao, DisposableB String line = "" + customerCredit.getName() + separator + customerCredit.getCredit(); - itemWriter.write(Collections.singletonList(line)); + itemWriter.write(Chunk.of(line)); } public void setSeparator(String separator) { diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/HibernateAwareCustomerCreditItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/HibernateAwareCustomerCreditItemWriter.java index 2746f2c85..51848ef14 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/HibernateAwareCustomerCreditItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/HibernateAwareCustomerCreditItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2013 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ package org.springframework.batch.sample.domain.trade.internal; import java.util.List; import org.hibernate.SessionFactory; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.sample.domain.trade.CustomerCreditDao; @@ -31,6 +33,7 @@ import org.springframework.util.Assert; * * @author Robert Kasanicky * @author Michael Minella + * @author Mahmoud Ben Hassine */ public class HibernateAwareCustomerCreditItemWriter implements ItemWriter, InitializingBean { @@ -39,7 +42,7 @@ public class HibernateAwareCustomerCreditItemWriter implements ItemWriter items) throws Exception { + public void write(Chunk items) throws Exception { for (CustomerCredit credit : items) { dao.writeCredit(credit); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/TradeWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/TradeWriter.java index eed0b305e..8692761d4 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/TradeWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/trade/internal/TradeWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2021 the original author or authors. + * Copyright 2006-2022 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. @@ -23,6 +23,7 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.batch.core.annotation.AfterWrite; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStreamSupport; import org.springframework.batch.item.ItemWriter; @@ -48,7 +49,7 @@ public class TradeWriter extends ItemStreamSupport implements ItemWriter private BigDecimal totalPrice = BigDecimal.ZERO; @Override - public void write(List trades) { + public void write(Chunk trades) { for (Trade trade : trades) { @@ -67,7 +68,7 @@ public class TradeWriter extends ItemStreamSupport implements ItemWriter } @AfterWrite - public void updateTotalPrice(List trades) { + public void updateTotalPrice(Chunk trades) { for (Trade trade : trades) { this.totalPrice = this.totalPrice.add(trade.getPrice()); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/DummyItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/DummyItemWriter.java index de2f5588e..09e5509cf 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/DummyItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/DummyItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,16 +17,18 @@ package org.springframework.batch.sample.support; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ public class DummyItemWriter implements ItemWriter { @Override - public void write(List item) throws Exception { + public void write(Chunk item) throws Exception { // NO-OP Thread.sleep(500); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/RetrySampleItemWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/RetrySampleItemWriter.java index 22de74c95..d1dedddb4 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/RetrySampleItemWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/support/RetrySampleItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2014 the original author or authors. + * Copyright 2006-2022 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,19 +18,21 @@ package org.springframework.batch.sample.support; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; /** * Simulates temporary output trouble - requires to retry 3 times to pass successfully. * * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ public class RetrySampleItemWriter implements ItemWriter { private int counter = 0; @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { int current = counter; counter += items.size(); if (current < 3 && (counter >= 2 || counter >= 3)) { @@ -39,7 +41,7 @@ public class RetrySampleItemWriter implements ItemWriter { } /** - * @return number of times {@link #write(List)} method was called. + * @return number of times {@link #write(Chunk)} method was called. */ public int getCounter() { return counter; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFileSampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFileSampleFunctionalTests.java index 494f846fd..70518dd4d 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFileSampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFileSampleFunctionalTests.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.test.AssertFile; @@ -34,6 +35,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Dan Garrette + * @author Mahmoud Ben Hassine * @since 2.0 */ @SpringJUnitConfig( @@ -64,7 +66,7 @@ class RestartFileSampleFunctionalTests { private boolean failed = false; @Override - public void write(List arg0) throws Exception { + public void write(Chunk arg0) throws Exception { for (CustomerCredit cc : arg0) { if (!failed && cc.getName().equals("customer13")) { failed = true; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/CustomItemWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/CustomItemWriterTests.java index 52ff595ff..378517fe8 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/CustomItemWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/CustomItemWriterTests.java @@ -22,6 +22,8 @@ import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.support.transaction.TransactionAwareProxyFactory; @@ -31,6 +33,7 @@ import org.springframework.batch.support.transaction.TransactionAwareProxyFactor * code base shifts. * * @author Lucas Ward + * @author Mahmoud Ben Hassine * */ class CustomItemWriterTests { @@ -38,9 +41,9 @@ class CustomItemWriterTests { @Test void testFlush() throws Exception { CustomItemWriter itemWriter = new CustomItemWriter<>(); - itemWriter.write(Collections.singletonList("1")); + itemWriter.write(Chunk.of("1")); assertEquals(1, itemWriter.getOutput().size()); - itemWriter.write(Arrays.asList("2", "3")); + itemWriter.write(Chunk.of("2", "3")); assertEquals(3, itemWriter.getOutput().size()); } @@ -49,8 +52,8 @@ class CustomItemWriterTests { private List output = TransactionAwareProxyFactory.createTransactionalList(); @Override - public void write(List items) throws Exception { - output.addAll(items); + public void write(Chunk chunk) throws Exception { + output.addAll(chunk.getItems()); } public List getOutput() { diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java index 98d50fcfc..ae78916f7 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemReaderTests.java @@ -27,6 +27,7 @@ import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; +import org.springframework.batch.item.Chunk; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -66,7 +67,7 @@ class StagingItemReaderTests { StepExecution stepExecution = new StepExecution("stepName", new JobExecution(new JobInstance(jobId, "testJob"), new JobParameters())); writer.beforeStep(stepExecution); - writer.write(Arrays.asList("FOO", "BAR", "SPAM", "BUCKET")); + writer.write(Chunk.of("FOO", "BAR", "SPAM", "BUCKET")); reader.beforeStep(stepExecution); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemWriterTests.java index 763f560d0..a4fe5f3f0 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/common/StagingItemWriterTests.java @@ -27,6 +27,7 @@ import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobInstance; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; +import org.springframework.batch.item.Chunk; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @@ -57,7 +58,7 @@ class StagingItemWriterTests { @Test void testProcessInsertsNewItem() { int before = JdbcTestUtils.countRowsInTable(jdbcTemplate, "BATCH_STAGING"); - writer.write(Collections.singletonList("FOO")); + writer.write(Chunk.of("FOO")); int after = JdbcTestUtils.countRowsInTable(jdbcTemplate, "BATCH_STAGING"); assertEquals(before + 1, after); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDaoIntegrationTests.java index f08c2423d..ed0c68e92 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcGameDaoIntegrationTests.java @@ -26,6 +26,7 @@ import javax.sql.DataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.football.Game; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcOperations; @@ -36,6 +37,7 @@ import org.springframework.transaction.annotation.Transactional; /** * @author Lucas Ward + * @author Mahmoud Ben Hassine * */ @SpringJUnitConfig(locations = { "/data-source-context.xml" }) @@ -77,7 +79,7 @@ class JdbcGameDaoIntegrationTests { @Transactional @Test void testWrite() { - gameDao.write(Collections.singletonList(game)); + gameDao.write(Chunk.of(game)); Game tempGame = jdbcTemplate.queryForObject("SELECT * FROM GAMES where PLAYER_ID=? AND YEAR_NO=?", new GameRowMapper(), "XXXXX00 ", game.getYear()); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDaoIntegrationTests.java index f156f057f..d674cc843 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/football/internal/JdbcPlayerSummaryDaoIntegrationTests.java @@ -23,6 +23,8 @@ import javax.sql.DataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.football.PlayerSummary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @@ -73,7 +75,7 @@ class JdbcPlayerSummaryDaoIntegrationTests { @Test @Transactional void testWrite() { - playerSummaryDao.write(Collections.singletonList(summary)); + playerSummaryDao.write(Chunk.of(summary)); PlayerSummary testSummary = jdbcTemplate.queryForObject("SELECT * FROM PLAYER_SUMMARY", new PlayerSummaryMapper()); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateProcessorTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateProcessorTests.java index 87b0b0051..824d5c7cb 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateProcessorTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerCreditUpdateProcessorTests.java @@ -22,6 +22,8 @@ import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.sample.domain.trade.CustomerCreditDao; @@ -47,13 +49,13 @@ class CustomerCreditUpdateProcessorTests { CustomerCredit credit = new CustomerCredit(); credit.setCredit(new BigDecimal(CREDIT_FILTER)); - writer.write(Collections.singletonList(credit)); + writer.write(Chunk.of(credit)); credit.setCredit(new BigDecimal(CREDIT_FILTER + 1)); dao.writeCredit(credit); - writer.write(Collections.singletonList(credit)); + writer.write(Chunk.of(credit)); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java index 9496a6e39..7c13a6368 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/CustomerUpdateProcessorTests.java @@ -21,6 +21,8 @@ import java.math.BigDecimal; import java.util.Collections; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.trade.CustomerDebit; import org.springframework.batch.sample.domain.trade.CustomerDebitDao; import org.springframework.batch.sample.domain.trade.Trade; @@ -44,7 +46,7 @@ class CustomerUpdateProcessorTests { CustomerUpdateWriter processor = new CustomerUpdateWriter(); processor.setDao(dao); - processor.write(Collections.singletonList(trade)); + processor.write(Chunk.of(trade)); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDaoTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDaoTests.java index 1de1d2545..e63616766 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDaoTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/FlatFileCustomerCreditDaoTests.java @@ -22,6 +22,8 @@ import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemWriter; @@ -65,7 +67,7 @@ class FlatFileCustomerCreditDaoTests { writer.setSeparator(";"); - output.write(Collections.singletonList("testName;1")); + output.write(Chunk.of("testName;1")); output.open(new ExecutionContext()); writer.writeCredit(credit); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/ItemTrackingTradeItemWriter.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/ItemTrackingTradeItemWriter.java index 2cfd8f486..ef0a3f4f4 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/ItemTrackingTradeItemWriter.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/ItemTrackingTradeItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2008-2014 the original author or authors. + * Copyright 2008-2022 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,6 +21,7 @@ import java.util.List; import javax.sql.DataSource; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.Trade; import org.springframework.jdbc.core.JdbcOperations; @@ -47,7 +48,7 @@ public class ItemTrackingTradeItemWriter implements ItemWriter { } @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { List newItems = new ArrayList<>(); for (Trade t : items) { diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/TradeProcessorTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/TradeProcessorTests.java index 9e80746b6..b167b2d95 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/TradeProcessorTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/domain/trade/internal/TradeProcessorTests.java @@ -21,6 +21,8 @@ import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.trade.Trade; import org.springframework.batch.sample.domain.trade.TradeDao; @@ -44,7 +46,7 @@ class TradeProcessorTests { writer.writeTrade(trade); - processor.write(Collections.singletonList(trade)); + processor.write(Chunk.of(trade)); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/MultiLineTradeItemWriter.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/MultiLineTradeItemWriter.java index f60ff4286..1e396d412 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/MultiLineTradeItemWriter.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/MultiLineTradeItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2014 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.sample.iosample.internal; import java.util.ArrayList; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemStreamException; @@ -28,6 +29,7 @@ import org.springframework.batch.sample.domain.trade.Trade; /** * @author Dan Garrette + * @author Mahmoud Ben Hassine * @since 2.0 */ public class MultiLineTradeItemWriter implements ItemWriter, ItemStream { @@ -35,8 +37,8 @@ public class MultiLineTradeItemWriter implements ItemWriter, ItemStream { private FlatFileItemWriter delegate; @Override - public void write(List items) throws Exception { - List lines = new ArrayList<>(); + public void write(Chunk items) throws Exception { + Chunk lines = new Chunk<>(); for (Trade t : items) { lines.add("BEGIN"); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/TradeCustomerItemWriter.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/TradeCustomerItemWriter.java index 3815a5a73..4543b324c 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/TradeCustomerItemWriter.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/iosample/internal/TradeCustomerItemWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.batch.sample.iosample.internal; import java.math.BigDecimal; import java.util.List; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.trade.CustomerCredit; import org.springframework.batch.sample.domain.trade.Trade; @@ -26,6 +27,7 @@ import org.springframework.batch.sample.domain.trade.TradeDao; /** * @author Dan Garrette + * @author Mahmoud Ben Hassine * @since 2.0 */ public class TradeCustomerItemWriter implements ItemWriter { @@ -35,7 +37,7 @@ public class TradeCustomerItemWriter implements ItemWriter { private int count; @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { for (CustomerCredit c : items) { Trade t = new Trade("ISIN" + count++, 100, new BigDecimal("1.50"), c.getName()); this.dao.writeTrade(t); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/ItemTrackingItemWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/ItemTrackingItemWriterTests.java index 3fec20d2a..23f223dbc 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/ItemTrackingItemWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/ItemTrackingItemWriterTests.java @@ -22,11 +22,14 @@ import java.io.IOException; import java.util.Arrays; import org.junit.jupiter.api.Test; + +import org.springframework.batch.item.Chunk; import org.springframework.batch.sample.domain.trade.Trade; import org.springframework.batch.sample.domain.trade.internal.ItemTrackingTradeItemWriter; /** * @author Dave Syer + * @author Mahmoud Ben Hassine * */ class ItemTrackingItemWriterTests { @@ -39,7 +42,7 @@ class ItemTrackingItemWriterTests { Trade a = new Trade("a", 0, null, null); Trade b = new Trade("b", 0, null, null); Trade c = new Trade("c", 0, null, null); - writer.write(Arrays.asList(a, b, c)); + writer.write(Chunk.of(a, b, c)); assertEquals(3, writer.getItems().size()); } @@ -49,13 +52,13 @@ class ItemTrackingItemWriterTests { Trade a = new Trade("a", 0, null, null); Trade b = new Trade("b", 0, null, null); Trade c = new Trade("c", 0, null, null); - assertThrows(IOException.class, () -> writer.write(Arrays.asList(a, b, c))); + assertThrows(IOException.class, () -> writer.write(Chunk.of(a, b, c))); assertEquals(0, writer.getItems().size()); Trade e = new Trade("e", 0, null, null); Trade f = new Trade("f", 0, null, null); Trade g = new Trade("g", 0, null, null); - writer.write(Arrays.asList(e, f, g)); + writer.write(Chunk.of(e, f, g)); assertEquals(3, writer.getItems().size()); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/RetrySampleItemWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/RetrySampleItemWriterTests.java index 539ae4b62..d3ea9e62c 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/RetrySampleItemWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/support/RetrySampleItemWriterTests.java @@ -23,10 +23,13 @@ import java.util.Collections; import org.junit.jupiter.api.Test; +import org.springframework.batch.item.Chunk; + /** * Tests for {@link RetrySampleItemWriter}. * * @author Robert Kasanicky + * @author Mahmoud Ben Hassine */ class RetrySampleItemWriterTests { @@ -38,11 +41,11 @@ class RetrySampleItemWriterTests { @Test void testProcess() throws Exception { Object item = null; - processor.write(Collections.singletonList(item)); + processor.write(Chunk.of(item)); - assertThrows(RuntimeException.class, () -> processor.write(Arrays.asList(item, item, item))); + assertThrows(RuntimeException.class, () -> processor.write(Chunk.of(item, item, item))); - processor.write(Collections.singletonList(item)); + processor.write(Chunk.of(item)); assertEquals(5, processor.getCounter()); } diff --git a/spring-batch-test/src/test/java/org/springframework/batch/test/StepScopeAnnotatedListenerIntegrationTests.java b/spring-batch-test/src/test/java/org/springframework/batch/test/StepScopeAnnotatedListenerIntegrationTests.java index e4c239600..f2b6f14bd 100644 --- a/spring-batch-test/src/test/java/org/springframework/batch/test/StepScopeAnnotatedListenerIntegrationTests.java +++ b/spring-batch-test/src/test/java/org/springframework/batch/test/StepScopeAnnotatedListenerIntegrationTests.java @@ -34,6 +34,7 @@ import org.springframework.batch.core.configuration.annotation.EnableBatchProces import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepScope; +import org.springframework.batch.item.Chunk; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; @@ -144,7 +145,7 @@ class StepScopeAnnotatedListenerIntegrationTests { return new ItemWriter() { @Override - public void write(List items) throws Exception { + public void write(Chunk items) throws Exception { } }; }