Use the Chunk API consistently

This commit replaces the usage of List with Chunk
where appropriate. Summary of changes:

- The Chunk class was moved from the `org.springframework.batch.core.step.item` package to the `org.springframework.batch.item` package
- The signature of the method `ItemWriter#write(List)` was changed to `ItemWriter#write(Chunk)`
- All implementations of `ItemWriter` were updated to use the Chunk API instead of List
- All methods in the `ItemWriteListener` interface were updated to use the Chunk API instead of List
- All implementations of `ItemWriteListener` were updated to use the Chunk API instead of List
- The constructor of `ChunkRequest` was changed to accept a Chunk instead of a Collection of items
- The return type of `ChunkRequest#getItems()` was changed from List to Chunk

Resolves #3954
This commit is contained in:
Mahmoud Ben Hassine
2022-08-17 21:06:09 +02:00
parent bf2e6ab0e5
commit e67c0069f1
175 changed files with 1077 additions and 763 deletions

View File

@@ -0,0 +1,264 @@
/*
* 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.
* 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.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;
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 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<W> implements Iterable<W>, Serializable {
private List<W> items = new ArrayList<>();
private List<SkipWrapper<W>> skips = new ArrayList<>();
private List<Exception> errors = new ArrayList<>();
private Object userData;
private boolean end;
private boolean busy;
public Chunk(W... items) {
this(Arrays.stream(items).toList());
}
public static <W> Chunk<W> of(W... items) {
return new Chunk<>(items);
}
public Chunk(List<? extends W> items) {
this(items, null);
}
public Chunk(List<? extends W> items, List<SkipWrapper<W>> skips) {
super();
if (items != null) {
this.items = new ArrayList<>(items);
}
if (skips != null) {
this.skips = new ArrayList<>(skips);
}
}
/**
* Add the item to the chunk.
* @param item the item to add
*/
public void add(W item) {
items.add(item);
}
/**
* Add all items to the chunk.
* @param items the items to add
*/
public void addAll(List<W> items) {
this.items.addAll(items);
}
/**
* Clear the items down to signal that we are done.
*/
public void clear() {
items.clear();
skips.clear();
userData = null;
}
/**
* @return a copy of the items to be processed as an unmodifiable list
*/
public List<W> getItems() {
return Collections.unmodifiableList(new ArrayList<>(items));
}
/**
* @return a copy of the skips as an unmodifiable list
*/
public List<SkipWrapper<W>> getSkips() {
return Collections.unmodifiableList(skips);
}
/**
* @return a copy of the anonymous errors as an unmodifiable list
*/
public List<Exception> getErrors() {
return Collections.unmodifiableList(errors);
}
/**
* Register an anonymous skip. To skip an individual item, use
* {@link ChunkIterator#remove()}.
* @param e the exception that caused the skip
*/
public void skip(Exception e) {
errors.add(e);
}
/**
* @return true if there are no items in the chunk
*/
public boolean isEmpty() {
return items.isEmpty();
}
/**
* Get an unmodifiable iterator for the underlying items.
* @see java.lang.Iterable#iterator()
*/
@Override
public ChunkIterator iterator() {
return new ChunkIterator(items);
}
/**
* @return the number of items (excluding skips)
*/
public int size() {
return items.size();
}
/**
* Flag to indicate if the source data is exhausted.
* @return true if there is no more data to process
*/
public boolean isEnd() {
return end;
}
/**
* Set the flag to say that this chunk represents an end of stream (there is no more
* data to process).
*/
public void setEnd() {
this.end = true;
}
/**
* Query the chunk to see if anyone has registered an interest in keeping a reference
* to it.
* @return the busy flag
*/
public boolean isBusy() {
return busy;
}
/**
* Register an interest in the chunk to prevent it from being cleaned up before the
* flag is reset to false.
* @param busy the flag to set
*/
public void setBusy(boolean busy) {
this.busy = busy;
}
/**
* Clear only the skips list.
*/
public void clearSkips() {
skips.clear();
}
public Object getUserData() {
return userData;
}
public void setUserData(Object userData) {
this.userData = userData;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("[items=%s, skips=%s]", items, skips);
}
/**
* Special iterator for a chunk providing the {@link #remove(Throwable)} method for
* dynamically removing an item and adding it to the skips.
*
* @author Dave Syer
*
*/
public class ChunkIterator implements Iterator<W> {
final private Iterator<W> iterator;
private W next;
public ChunkIterator(List<W> items) {
iterator = items.iterator();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public W next() {
next = iterator.next();
return next;
}
public void remove(Throwable e) {
remove();
skips.add(new SkipWrapper<>(next, e));
}
@Override
public void remove() {
if (next == null) {
if (iterator.hasNext()) {
next = iterator.next();
}
else {
return;
}
}
iterator.remove();
}
@Override
public String toString() {
return String.format("[items=%s, skips=%s]", items, skips);
}
}
}

View File

@@ -18,6 +18,8 @@ package org.springframework.batch.item;
import java.util.List;
import org.springframework.lang.NonNull;
/**
* <p>
* 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<T> {
@@ -43,10 +46,10 @@ public interface ItemWriter<T> {
/**
* 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<? extends T> items) throws Exception;
void write(@NonNull Chunk<? extends T> chunk) throws Exception;
}

View File

@@ -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<K, V> implements ItemWriter<V>, Initial
* @see org.springframework.batch.item.ItemWriter#write(java.util.List)
*/
@Override
public void write(List<? extends V> items) throws Exception {
public void write(Chunk<? extends V> items) throws Exception {
if (items == null) {
return;
}

View File

@@ -0,0 +1,75 @@
/*
* 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.
* 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.item;
import org.springframework.lang.Nullable;
/**
* Wrapper for an item and its exception if it failed processing.
*
* @author Dave Syer
* @author Mahmoud Ben Hassine
*
*/
public class SkipWrapper<T> {
final private Throwable exception;
final private T item;
/**
* @param item the item being wrapped.
*/
public SkipWrapper(T item) {
this(item, null);
}
/**
* @param e instance of {@link Throwable} that being wrapped.
*/
public SkipWrapper(Throwable e) {
this(null, e);
}
public SkipWrapper(T item, @Nullable Throwable e) {
this.item = item;
this.exception = e;
}
/**
* Public getter for the exception.
* @return the exception
*/
@Nullable
public Throwable getException() {
return exception;
}
/**
* Public getter for the item.
* @return the item
*/
public T getItem() {
return item;
}
@Override
public String toString() {
return String.format("[exception=%s, item=%s]", exception, item);
}
}

View File

@@ -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<T> extends AbstractMethodInvokingDelegator<T> implements ItemWriter<T> {
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
for (T item : items) {
invokeDelegateMethodWithArgument(item);
}

View File

@@ -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<T> extends AbstractMethodInvokingDelegator<T>
implements ItemWriter<T> {
@@ -41,7 +43,7 @@ public class PropertyExtractingDelegatingItemWriter<T> extends AbstractMethodInv
* passes them as arguments to the delegate method.
*/
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
for (T item : items) {
// helper for extracting property values from a bean

View File

@@ -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<T> implements ItemWriter<T> {
}
@Override
public void write(final List<? extends T> items) throws Exception {
public void write(final Chunk<? extends T> items) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Writing to AMQP with " + items.size() + " items.");
}

View File

@@ -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<T> extends AbstractItemStreamItemWriter<T> {
}
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
items.forEach(item -> {
try {
if (this.dataFileWriter != null) {

View File

@@ -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<T> implements ItemWriter<T>, 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<? extends T> items) throws Exception {
public void write(Chunk<? extends T> chunk) throws Exception {
if (!transactionActive()) {
doWrite(items);
doWrite(chunk);
return;
}
List<T> 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<? extends T> items) {
if (!CollectionUtils.isEmpty(items)) {
protected void doWrite(Chunk<? extends T> chunk) {
if (!CollectionUtils.isEmpty(chunk.getItems())) {
if (this.delete) {
delete(items);
delete(chunk);
}
else {
saveOrUpdate(items);
saveOrUpdate(chunk);
}
}
}
private void delete(List<? extends T> items) {
BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, items.get(0));
private void delete(Chunk<? extends T> 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<T> implements ItemWriter<T>, InitializingBean {
bulkOperations.execute();
}
private void saveOrUpdate(List<? extends T> items) {
BulkOperations bulkOperations = initBulkOperations(BulkMode.ORDERED, items.get(0));
private void saveOrUpdate(Chunk<? extends T> 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<T> implements ItemWriter<T>, InitializingBean {
return TransactionSynchronizationManager.isActualTransactionActive();
}
@SuppressWarnings("unchecked")
private List<T> getCurrentBuffer() {
private Chunk<T> getCurrentBuffer() {
if (!TransactionSynchronizationManager.hasResource(bufferKey)) {
TransactionSynchronizationManager.bindResource(bufferKey, new ArrayList<T>());
TransactionSynchronizationManager.bindResource(bufferKey, new Chunk<T>());
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void beforeCommit(boolean readOnly) {
List<T> items = (List<T>) TransactionSynchronizationManager.getResource(bufferKey);
Chunk<T> chunk = (Chunk<T>) 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<T> implements ItemWriter<T>, InitializingBean {
});
}
return (List<T>) TransactionSynchronizationManager.getResource(bufferKey);
return (Chunk<T>) TransactionSynchronizationManager.getResource(bufferKey);
}
@Override

View File

@@ -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<T> implements ItemWriter<T>, 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<? extends T> items) throws Exception {
if (!CollectionUtils.isEmpty(items)) {
doWrite(items);
public void write(Chunk<? extends T> chunk) throws Exception {
if (!CollectionUtils.isEmpty(chunk.getItems())) {
doWrite(chunk);
}
}
@@ -100,7 +101,7 @@ public class Neo4jItemWriter<T> implements ItemWriter<T>, InitializingBean {
* if necessary.
* @param items the list of items to be persisted.
*/
protected void doWrite(List<? extends T> items) {
protected void doWrite(Chunk<? extends T> items) {
if (delete) {
delete(items);
}
@@ -109,7 +110,7 @@ public class Neo4jItemWriter<T> implements ItemWriter<T>, InitializingBean {
}
}
private void delete(List<? extends T> items) {
private void delete(Chunk<? extends T> items) {
Session session = this.sessionFactory.openSession();
for (T item : items) {
@@ -117,7 +118,7 @@ public class Neo4jItemWriter<T> implements ItemWriter<T>, InitializingBean {
}
}
private void save(List<? extends T> items) {
private void save(Chunk<? extends T> items) {
Session session = this.sessionFactory.openSession();
for (T item : items) {

View File

@@ -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<T> implements ItemWriter<T>, 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<? extends T> items) throws Exception {
if (!CollectionUtils.isEmpty(items)) {
doWrite(items);
public void write(Chunk<? extends T> chunk) throws Exception {
if (!CollectionUtils.isEmpty(chunk.getItems())) {
doWrite(chunk);
}
}
@@ -102,7 +104,7 @@ public class RepositoryItemWriter<T> implements ItemWriter<T>, InitializingBean
* @param items the list of items to be persisted.
* @throws Exception thrown if error occurs during writing.
*/
protected void doWrite(List<? extends T> items) throws Exception {
protected void doWrite(Chunk<? extends T> items) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Writing to the repository with " + items.size() + " items.");
}

View File

@@ -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<T> implements ItemWriter<T>, 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<? extends T> items) {
public void write(Chunk<? extends T> items) {
doWrite(sessionFactory, items);
sessionFactory.getCurrentSession().flush();
if (clearSession) {
@@ -98,7 +99,7 @@ public class HibernateItemWriter<T> implements ItemWriter<T>, 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<? extends T> items) {
protected void doWrite(SessionFactory sessionFactory, Chunk<? extends T> items) {
if (logger.isDebugEnabled()) {
logger.debug("Writing to Hibernate with " + items.size() + " items.");
}

View File

@@ -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.<br>
*
* It is expected that {@link #write(List)} is called inside a transaction.<br>
* It is expected that {@link #write(Chunk)} is called inside a transaction.<br>
*
* 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<T> implements ItemWriter<T>, InitializingBean {
@@ -164,24 +166,25 @@ public class JdbcBatchItemWriter<T> implements ItemWriter<T>, InitializingBean {
*/
@SuppressWarnings("unchecked")
@Override
public void write(final List<? extends T> items) throws Exception {
public void write(final Chunk<? extends T> 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<T> implements ItemWriter<T>, 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<T> implements ItemWriter<T>, 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);
}
}
}

View File

@@ -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.<br>
* It is required that {@link #write(Chunk)} is called inside a transaction.<br>
*
* 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<T> implements ItemWriter<T>, 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<? extends T> items) {
public void write(Chunk<? extends T> 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<T> implements ItemWriter<T>, 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<? extends T> items) {
protected void doWrite(EntityManager entityManager, Chunk<? extends T> items) {
if (logger.isDebugEnabled()) {
logger.debug("Writing to JPA with " + items.size() + " items.");

View File

@@ -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<T> extends AbstractFileItemWriter<T> {
}
@Override
public String doWrite(List<? extends T> items) {
public String doWrite(Chunk<? extends T> items) {
StringBuilder lines = new StringBuilder();
for (T item : items) {
lines.append(this.lineAggregator.aggregate(item)).append(this.lineSeparator);

View File

@@ -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 <T> item type
* @author Robert Kasanicky
* @author Mahmoud Ben Hassine
*/
public class MultiResourceItemWriter<T> extends AbstractItemStreamItemWriter<T> {
@@ -67,7 +70,7 @@ public class MultiResourceItemWriter<T> extends AbstractItemStreamItemWriter<T>
}
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
if (!opened) {
File file = setResourceToDelegate();
// create only if write is called

View File

@@ -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)}.<br>
* default destination, which will be used to send items in {@link #write(Chunk)}.<br>
* <br>
*
* The implementation is thread-safe after its properties are set (normal singleton
* behavior).
*
* @author Dave Syer
* @author Mahmoud Ben Hassine
*
*/
public class JmsItemWriter<T> implements ItemWriter<T> {
@@ -58,10 +61,10 @@ public class JmsItemWriter<T> implements ItemWriter<T> {
/**
* 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<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Writing to JMS with " + items.size() + " items.");

View File

@@ -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<T> extends AbstractFileItemWriter<T> {
}
@Override
public String doWrite(List<? extends T> items) {
public String doWrite(Chunk<? extends T> items) {
StringBuilder lines = new StringBuilder();
Iterator<? extends T> iterator = items.iterator();
if (!items.isEmpty() && state.getLinesWritten() > 0) {

View File

@@ -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;
* </p>
*
* @author Dave Syer
* @author Mahmoud Ben Hassine
* @since 2.1
*
*/
@@ -60,7 +62,7 @@ public class SimpleMailMessageItemWriter implements ItemWriter<SimpleMailMessage
private MailErrorHandler mailErrorHandler = new DefaultMailErrorHandler();
/**
* A {@link MailSender} to be used to send messages in {@link #write(List)}.
* A {@link MailSender} to be used to send messages in {@link #write(Chunk)}.
* @param mailSender The {@link MailSender} to be used.
*/
public void setMailSender(MailSender mailSender) {
@@ -87,13 +89,13 @@ public class SimpleMailMessageItemWriter implements ItemWriter<SimpleMailMessage
}
/**
* @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<? extends SimpleMailMessage> items) throws MailException {
public void write(Chunk<? extends SimpleMailMessage> 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<Object, Exception> failedMessages = e.getFailedMessages();

View File

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

View File

@@ -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<MimeMessage> {
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<MimeMessage> {
}
/**
* @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<? extends MimeMessage> items) throws MailException {
public void write(Chunk<? extends MimeMessage> 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<Object, Exception> failedMessages = e.getFailedMessages();

View File

@@ -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<T> extends AbstractItemStreamItemWr
* @throws Exception if an error occurs while writing items to the output stream
*/
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> 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<T> extends AbstractItemStreamItemWr
* @param items to be written
* @return written lines
*/
protected abstract String doWrite(List<? extends T> items);
protected abstract String doWrite(Chunk<? extends T> items);
/**
* @see ItemStream#close()

View File

@@ -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<T> implements ItemWriter<T> {
@@ -53,14 +55,14 @@ public class ClassifierCompositeItemWriter<T> implements ItemWriter<T> {
* classification by the {@link Classifier}.
*/
@Override
public void write(List<? extends T> items) throws Exception {
public void write(Chunk<? extends T> items) throws Exception {
Map<ItemWriter<? super T>, List<T>> map = new LinkedHashMap<>();
Map<ItemWriter<? super T>, Chunk<T>> map = new LinkedHashMap<>();
for (T item : items) {
ItemWriter<? super T> key = classifier.classify(item);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
map.put(key, new Chunk<>());
}
map.get(key).add(item);
}

View File

@@ -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<T> implements ItemStreamWriter<T>, InitializingBean {
@@ -78,9 +80,9 @@ public class CompositeItemWriter<T> implements ItemStreamWriter<T>, Initializing
}
@Override
public void write(List<? extends T> item) throws Exception {
public void write(Chunk<? extends T> chunk) throws Exception {
for (ItemWriter<? super T> writer : delegates) {
writer.write(item);
writer.write(chunk);
}
}

View File

@@ -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<T> implements ItemWriter<T> {
private List<T> writtenItems = new ArrayList<>();
@Override
public void write(List<? extends T> items) throws Exception {
writtenItems.addAll(items);
public void write(Chunk<? extends T> chunk) throws Exception {
writtenItems.addAll(chunk.getItems());
}
public List<? extends T> getWrittenItems() {

View File

@@ -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<T> implements ItemStreamWriter<T>, Ini
* This method delegates to the {@code write} method of the {@code delegate}.
*/
@Override
public synchronized void write(List<? extends T> items) throws Exception {
public synchronized void write(Chunk<? extends T> items) throws Exception {
this.delegate.write(items);
}

View File

@@ -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<T> extends AbstractItemStreamItemWriter<T>
* @throws XmlMappingException thrown if error occurs during XML Mapping.
*/
@Override
public void write(List<? extends T> items) throws XmlMappingException, IOException {
public void write(Chunk<? extends T> items) throws XmlMappingException, IOException {
if (!this.initialized) {
throw new WriterNotOpenException("Writer must be open before it can be written to");

View File

@@ -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<Foo> foos = new ArrayList<>();
Chunk<Foo> foos = new Chunk<>();
while ((foo = fooService.generateFoo()) != null) {
foos.add(foo);
}

View File

@@ -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<Foo> input = fooService.getGeneratedFoos();

View File

@@ -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<String> amqpItemWriter = new AmqpItemWriter<>(amqpTemplate);
amqpItemWriter.write(Arrays.asList("foo", "bar"));
amqpItemWriter.write(Chunk.of("foo", "bar"));
}

View File

@@ -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<String> amqpItemWriter = new AmqpItemWriterBuilder<String>().amqpTemplate(amqpTemplate).build();
amqpItemWriter.write(Arrays.asList("foo", "bar"));
amqpItemWriter.write(Chunk.of("foo", "bar"));
verify(amqpTemplate).convertAndSend("foo");
verify(amqpTemplate).convertAndSend("bar");
}

View File

@@ -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 <T> void verify(AvroItemReader<T> avroItemReader, List<T> actual) throws Exception {
protected <T> void verify(AvroItemReader<T> avroItemReader, Chunk<T> actual) throws Exception {
avroItemReader.open(new ExecutionContext());
List<T> 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<T> actualItems = actual.getItems();
assertThat(users).containsExactlyInAnyOrder(actualItems.get(0), actualItems.get(1), actualItems.get(2),
actualItems.get(3));
avroItemReader.close();
}

View File

@@ -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 <T> void verifyRecords(byte[] bytes, List<T> actual, Class<T> clazz, boolean embeddedSchema)
protected <T> void verifyRecords(byte[] bytes, Chunk<T> actual, Class<T> clazz, boolean embeddedSchema)
throws Exception {
doVerify(bytes, clazz, actual, embeddedSchema);
}
protected <T> void verifyRecordsWithEmbeddedHeader(byte[] bytes, List<T> actual, Class<T> clazz) throws Exception {
protected <T> void verifyRecordsWithEmbeddedHeader(byte[] bytes, Chunk<T> actual, Class<T> clazz) throws Exception {
doVerify(bytes, clazz, actual, true);
}
private <T> void doVerify(byte[] bytes, Class<T> clazz, List<T> actual, boolean embeddedSchema) throws Exception {
private <T> void doVerify(byte[] bytes, Class<T> clazz, Chunk<T> actual, boolean embeddedSchema) throws Exception {
AvroItemReader<T> avroItemReader = new AvroItemReaderBuilder<T>().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<T> actualItems = actual.getItems();
assertThat(records).containsExactlyInAnyOrder(actualItems.get(0), actualItems.get(1), actualItems.get(2),
actualItems.get(3));
}
protected static class OutputStreamResource implements WritableResource {

View File

@@ -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<User> avroGeneratedUsers = Arrays.asList(
private final Chunk<User> 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<PlainOldUser> plainOldUsers = Arrays.asList(
private Chunk<PlainOldUser> 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<User> avroGeneratedUsers() {
protected Chunk<User> avroGeneratedUsers() {
return this.avroGeneratedUsers;
}
protected List<GenericRecord> genericAvroGeneratedUsers() {
return this.avroGeneratedUsers.stream().map(u -> {
protected Chunk<GenericRecord> 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<PlainOldUser> plainOldUsers() {
protected Chunk<PlainOldUser> plainOldUsers() {
return this.plainOldUsers;
}
protected List<GenericRecord> genericPlainOldUsers() {
return this.plainOldUsers.stream().map(PlainOldUser::toGenericRecord).collect(Collectors.toList());
protected Chunk<GenericRecord> genericPlainOldUsers() {
return new Chunk(
this.plainOldUsers.getItems().stream().map(PlainOldUser::toGenericRecord).collect(Collectors.toList()));
}
protected static class PlainOldUser {

View File

@@ -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<Foo> items = new ArrayList<Foo>() {
Chunk<Foo> chunk = new Chunk<Foo>() {
{
add(new Foo(new Bar("val1")));
add(new Foo(new Bar("val2")));
}
};
writer.write(items);
writer.write(chunk);
List<Foo> items = chunk.getItems();
verify(template).put("val1", items.get(0));
verify(template).put("val2", items.get(1));
}
@Test
void testBasicDelete() throws Exception {
List<Foo> items = new ArrayList<Foo>() {
Chunk<Foo> chunk = new Chunk<Foo>() {
{
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<Foo> items = new ArrayList<Foo>() {
Chunk<Foo> chunk = new Chunk<Foo>() {
{
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<Foo> items = chunk.getItems();
verify(template).put("item1", items.get(0));
verify(template).put("item2", items.get(1));
}

View File

@@ -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<Item> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
Chunk<Item> items = Chunk.of(new Item("Foo"), new Item("Bar"));
writer.write(items);
@@ -114,7 +116,7 @@ class MongoItemWriterTests {
@Test
void testWriteNoTransactionWithCollection() throws Exception {
List<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
Chunk<Object> 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<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
final Chunk<Object> items = Chunk.of(new Item("Foo"), new Item("Bar"));
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) status -> {
assertDoesNotThrow(() -> writer.write(items));
@@ -147,7 +149,7 @@ class MongoItemWriterTests {
@Test
void testWriteTransactionWithCollection() {
final List<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
final Chunk<Object> items = Chunk.of(new Item("Foo"), new Item("Bar"));
writer.setCollection("collection");
@@ -162,7 +164,7 @@ class MongoItemWriterTests {
@Test
void testWriteTransactionFails() {
final List<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
final Chunk<Object> items = Chunk.of(new Item("Foo"), new Item("Bar"));
writer.setCollection("collection");
@@ -183,7 +185,7 @@ class MongoItemWriterTests {
*/
@Test
void testWriteTransactionReadOnly() {
final List<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
final Chunk<Object> 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<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
Chunk<Object> 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<Object> items = Arrays.asList(new Item("Foo"), new Item("Bar"));
Chunk<Object> 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<Object> items = Arrays.asList(new Item(1), new Item(2));
Chunk<Object> 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<Object> items = Arrays.asList(new Item(1), new Item(2));
Chunk<Object> items = Chunk.of(new Item(1), new Item(2));
writer.setCollection("collection");
@@ -285,7 +287,7 @@ class MongoItemWriterTests {
new TransactionTemplate(transactionManager).execute((TransactionCallback<Void>) 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) {

View File

@@ -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<String> items = new ArrayList<>();
Chunk<String> items = new Chunk<>();
items.add("foo");
items.add("bar");
@@ -126,7 +102,7 @@ class Neo4jItemWriterTests {
writer.setSessionFactory(this.sessionFactory);
writer.afterPropertiesSet();
List<String> items = new ArrayList<>();
Chunk<String> items = new Chunk<>();
items.add("foo");
items.add("bar");

View File

@@ -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<String> items = Collections.singletonList("foo");
Chunk<String> items = Chunk.of("foo");
writer.write(items);
@@ -83,7 +83,7 @@ class RepositoryItemWriterTests {
@Test
void testWriteItemsWithDefaultMethodName() throws Exception {
List<String> items = Collections.singletonList("foo");
Chunk<String> items = Chunk.of("foo");
writer.setMethodName(null);
writer.write(items);

View File

@@ -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<String, GemfireItemWriterBuilderTests.Foo> itemKeyMapper;
private List<GemfireItemWriterBuilderTests.Foo> items;
private Chunk<Foo> 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

View File

@@ -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<Item> saveItems;
private Chunk<Item> saveItems;
private List<Item> removeItems;
private Chunk<Item> 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));
}

View File

@@ -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<String> writer = new Neo4jItemWriterBuilder<String>().sessionFactory(this.sessionFactory)
.build();
List<String> items = new ArrayList<>();
Chunk<String> items = new Chunk<>();
items.add("foo");
items.add("bar");
@@ -68,7 +70,7 @@ class Neo4jItemWriterBuilderTests {
void testBasicDelete() throws Exception {
Neo4jItemWriter<String> writer = new Neo4jItemWriterBuilder<String>().delete(true)
.sessionFactory(this.sessionFactory).build();
List<String> items = new ArrayList<>();
Chunk<String> items = new Chunk<>();
items.add("foo");
items.add("bar");

View File

@@ -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<String> writer = new RepositoryItemWriterBuilder<String>().methodName("save")
.repository(this.repository).build();
List<String> items = Collections.singletonList("foo");
Chunk<String> items = Chunk.of("foo");
writer.write(items);
@@ -72,7 +74,7 @@ class RepositoryItemWriterBuilderTests {
RepositoryItemWriter<String> writer = new RepositoryItemWriterBuilder<String>().methodName("foo")
.repository(this.repository).build();
List<String> items = Collections.singletonList("foo");
Chunk<String> items = Chunk.of("foo");
writer.write(items);
@@ -88,7 +90,7 @@ class RepositoryItemWriterBuilderTests {
RepositoryItemWriter<String> writer = new RepositoryItemWriterBuilder<String>().methodName("foo")
.repository(repositoryMethodReference).build();
List<String> items = Collections.singletonList("foo");
Chunk<String> items = Chunk.of("foo");
writer.write(items);

View File

@@ -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<String> items = Arrays.asList(new String[] { "foo", "bar" });
Chunk<String> 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<String> items = Arrays.asList(new String[] { "foo", "bar" });
Chunk<String> 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());
}

View File

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

View File

@@ -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<Map[]> 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<String, Object> results = captor.getValue()[0];
@@ -158,7 +160,7 @@ public class JdbcBatchItemWriterNamedParameterTests {
ArgumentCaptor<SqlParameterSource[]> 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());
}

View File

@@ -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<Person> writer = new JpaItemWriter<>();
writer.setEntityManagerFactory(this.entityManagerFactory);
writer.afterPropertiesSet();
List<Person> items = Arrays.asList(new Person(1, "foo"), new Person(2, "bar"));
Chunk<Person> 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<Person> items = Arrays.asList(new Person(1, "foo"), new Person(2, "bar"));
Chunk<Person> items = Chunk.of(new Person(1, "foo"), new Person(2, "bar"));
// when
writer.write(items);

View File

@@ -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<String> items = Arrays.asList(new String[] { "foo", "bar" });
Chunk<String> 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<String> items = Arrays.asList("persist1", "persist2");
writer.write(items);
verify(em).persist(items.get(0));
verify(em).persist(items.get(1));
Chunk<String> 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);

View File

@@ -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<Foo> foos = getFoos();
Chunk<Foo> 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<Foo> foos = getFoos();
Chunk<Foo> 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<Foo> getFoos() {
List<Foo> foos = new ArrayList<>(3);
private Chunk<Foo> getFoos() {
Chunk<Foo> foos = new Chunk<>();
for (int i = 1; i < 4; i++) {
Foo foo = new Foo();

View File

@@ -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<Map<String, Object>> items = buildMapItems();
writer.write(items);
Chunk<Map<String, Object>> chunk = buildMapItems();
writer.write(chunk);
verifyWrite();
}
@@ -93,7 +95,7 @@ class JdbcBatchItemWriterBuilderTests {
writer.afterPropertiesSet();
List<Map<String, Object>> items = buildMapItems();
Chunk<Map<String, Object>> items = buildMapItems();
writer.write(items);
verifyWrite();
@@ -109,7 +111,7 @@ class JdbcBatchItemWriterBuilderTests {
writer.afterPropertiesSet();
List<Foo> items = new ArrayList<>(3);
Chunk<Foo> 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<Foo> items = new ArrayList<>(1);
Chunk<Foo> items = new Chunk<>();
items.add(new Foo(1, "two", "three"));
@@ -147,7 +149,7 @@ class JdbcBatchItemWriterBuilderTests {
writer.afterPropertiesSet();
List<Map<String, Object>> items = buildMapItems();
Chunk<Map<String, Object>> items = buildMapItems();
writer.write(items);
verifyWrite();
@@ -161,7 +163,7 @@ class JdbcBatchItemWriterBuilderTests {
writer.afterPropertiesSet();
List<Map<String, Object>> items = buildMapItems();
Chunk<Map<String, Object>> items = buildMapItems();
writer.write(items);
verifyWrite();
@@ -192,8 +194,8 @@ class JdbcBatchItemWriterBuilderTests {
verifyRow(7, "eight", "nine");
}
private List<Map<String, Object>> buildMapItems() {
List<Map<String, Object>> items = new ArrayList<>(3);
private Chunk<Map<String, Object>> buildMapItems() {
Chunk<Map<String, Object>> items = new Chunk<>();
Map<String, Object> item = new HashMap<>(3);
item.put("first", 1);

View File

@@ -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<String> items = Arrays.asList("foo", "bar");
Chunk<String> 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<String> items = Arrays.asList("foo", "bar");
Chunk<String> 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));
}
}

View File

@@ -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<String> items = new ArrayList<String>() {
{
add("1");
add("2");
add("3");
}
};
Chunk<String> 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());
}

View File

@@ -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<Void> {
private List<? extends String> list;
private Chunk<? extends String> list;
public WriterCallback(List<? extends String> list) {
public WriterCallback(Chunk<? extends String> 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));
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -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<String> itemWriter = new JmsItemWriterBuilder<String>().jmsTemplate(jmsTemplate).build();
ArgumentCaptor<String> 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");

View File

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

View File

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

View File

@@ -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<String> items = Arrays.asList("val1", "val2");
Chunk<String> chunk = Chunk.of("val1", "val2");
this.writer.write(items);
this.writer.write(chunk);
List<String> 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<String> items = Arrays.asList("val1", "val2");
Chunk<String> chunk = Chunk.of("val1", "val2");
this.writer.setDelete(true);
this.writer.write(items);
this.writer.write(chunk);
List<String> items = chunk.getItems();
verify(this.kafkaTemplate).sendDefault(items.get(0), null);
verify(this.kafkaTemplate).sendDefault(items.get(1), null);
verify(this.kafkaTemplate).flush();

View File

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

View File

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

View File

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

View File

@@ -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<Object> synchronizedItemStreamWriter;
private final List<Object> testList = Collections.unmodifiableList(new ArrayList<>());
private final Chunk<Object> testList = new Chunk<Object>();
private final ExecutionContext testExecutionContext = new ExecutionContext();

View File

@@ -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<String> writer = new ClassifierCompositeItemWriter<>();
private final List<String> defaults = new ArrayList<>();
private final Chunk defaults = new Chunk<>();
private final List<String> foos = new ArrayList<>();
private final Chunk foos = new Chunk<>();
@Test
void testWrite() throws Exception {
Map<String, ItemWriter<? super String>> map = new HashMap<>();
Map<String, ItemWriter<String>> map = new HashMap<>();
ItemWriter<String> fooWriter = new ItemWriter<String>() {
@Override
public void write(List<? extends String> items) throws Exception {
foos.addAll(items);
public void write(Chunk<? extends String> chunk) throws Exception {
foos.addAll(chunk.getItems());
}
};
ItemWriter<String> defaultWriter = new ItemWriter<String>() {
@Override
public void write(List<? extends String> items) throws Exception {
defaults.addAll(items);
public void write(Chunk<? extends String> 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

View File

@@ -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<Object> data = Collections.singletonList(new Object());
Chunk<Object> data = Chunk.of(new Object());
List<ItemWriter<? super Object>> writers = new ArrayList<>();
@@ -74,7 +77,7 @@ class CompositeItemWriterTests {
private void doTestItemStream(boolean expectOpen) throws Exception {
@SuppressWarnings("unchecked")
ItemStreamWriter<? super Object> writer = mock(ItemStreamWriter.class);
List<Object> data = Collections.singletonList(new Object());
Chunk<Object> data = Chunk.of(new Object());
ExecutionContext executionContext = new ExecutionContext();
if (expectOpen) {
writer.open(executionContext);

View File

@@ -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<String> defaults = new ArrayList<>();
private final Chunk defaults = new Chunk();
private final List<String> foos = new ArrayList<>();
private final Chunk foos = new Chunk();
@Test
void testWrite() throws Exception {
Map<String, ItemWriter<? super String>> map = new HashMap<>();
ItemWriter<String> fooWriter = items -> foos.addAll(items);
ItemWriter<String> defaultWriter = items -> defaults.addAll(items);
ItemWriter<String> fooWriter = new ItemWriter<String>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
foos.addAll(chunk.getItems());
}
};
ItemWriter<String> defaultWriter = new ItemWriter<String>() {
@Override
public void write(Chunk<? extends String> chunk) throws Exception {
defaults.addAll(chunk.getItems());
}
};
map.put("foo", fooWriter);
map.put("*", defaultWriter);
ClassifierCompositeItemWriter<String> writer = new ClassifierCompositeItemWriterBuilder<String>()
.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

View File

@@ -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<Object> data = Collections.singletonList(new Object());
Chunk<Object> data = Chunk.of(new Object());
List<ItemWriter<? super Object>> writers = new ArrayList<>();
@@ -63,7 +65,7 @@ class CompositeItemWriterBuilderTests {
@SuppressWarnings("unchecked")
void testProcessVarargs() throws Exception {
List<Object> data = Collections.singletonList(new Object());
Chunk<Object> data = Chunk.of(new Object());
List<ItemWriter<? super Object>> writers = new ArrayList<>();
@@ -90,7 +92,7 @@ class CompositeItemWriterBuilderTests {
@SuppressWarnings("unchecked")
private void ignoreItemStream(boolean ignoreItemStream) throws Exception {
ItemStreamWriter<? super Object> writer = mock(ItemStreamWriter.class);
List<Object> data = Collections.singletonList(new Object());
Chunk<Object> data = Chunk.of(new Object());
ExecutionContext executionContext = new ExecutionContext();
List<ItemWriter<? super Object>> writers = new ArrayList<>();

View File

@@ -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<Trade> objects = new ArrayList<Trade>() {
{
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<Trade> 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.

View File

@@ -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<QualifiedTrade> objects = List.of(
private final Chunk<QualifiedTrade> 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"));

View File

@@ -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<String> writer = new StaxEventItemWriter<>();
assertThrows(WriterNotOpenException.class, () -> writer.write(List.of("foo")));
assertThrows(WriterNotOpenException.class, () -> writer.write(Chunk.of("foo")));
}
@Test

View File

@@ -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 = "<!--" + ClassUtils.getShortName(StaxEventItemWriter.class)
+ "-testString-->";

View File

@@ -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<Foo> items;
private Chunk<Foo> 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<Foo>());
staxEventItemWriter.update(executionContext);
staxEventItemWriter.close();

View File

@@ -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<? extends Trade> data) {
public synchronized void write(Chunk<? extends Trade> data) {
count++;
System.out.println("Executing trade '" + data + "'");
}

View File

@@ -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<T> implements RepeatCallback {
@@ -55,7 +57,7 @@ public class ItemReaderRepeatCallback<T> implements RepeatCallback {
if (item == null) {
return RepeatStatus.FINISHED;
}
writer.write(Collections.singletonList(item));
writer.write(Chunk.of(item));
return RepeatStatus.CONTINUABLE;
}

View File

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

View File

@@ -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<Object> writer = new ItemWriter<Object>() {
@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<Object, Exception> 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<Object, Exception> callback = new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
writer.write(Collections.singletonList(item));
writer.write(Chunk.of(item));
return null;
}
};