Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@

package org.springframework.batch.infrastructure.item.json;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Iterator;

import org.springframework.batch.infrastructure.item.Chunk;
import org.springframework.batch.infrastructure.item.ExecutionContext;
import org.springframework.batch.infrastructure.item.ItemStreamException;
import org.springframework.batch.infrastructure.item.support.AbstractFileItemWriter;
import org.springframework.core.io.WritableResource;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -46,6 +51,7 @@
* @param <T> type of object to write as json representation
* @author Mahmoud Ben Hassine
* @author Jimmy Praet
* @author Yanming Zhou
* @since 4.1
*/
public class JsonFileItemWriter<T> extends AbstractFileItemWriter<T> {
Expand All @@ -58,6 +64,8 @@ public class JsonFileItemWriter<T> extends AbstractFileItemWriter<T> {

private JsonObjectMarshaller<T> jsonObjectMarshaller;

private boolean hasExistingItems;

/**
* Create a new {@link JsonFileItemWriter} instance.
* @param resource to write json data to
Expand Down Expand Up @@ -91,10 +99,27 @@ public void setJsonObjectMarshaller(JsonObjectMarshaller<T> jsonObjectMarshaller
this.jsonObjectMarshaller = jsonObjectMarshaller;
}

@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
try {
if (this.append && this.resource != null && this.resource.exists() && this.resource.contentLength() > 0) {
reopen(this.resource.getFile());
}
}
catch (IOException ex) {
throw new ItemStreamException(ex.getMessage(), ex);
}
super.open(executionContext);
}

@SuppressWarnings("DataFlowIssue")
@Override
public String doWrite(Chunk<? extends T> items) {
StringBuilder lines = new StringBuilder();
if (this.hasExistingItems) {
lines.append(JSON_OBJECT_SEPARATOR).append(this.lineSeparator);
this.hasExistingItems = false;
}
Iterator<? extends T> iterator = items.iterator();
if (!items.isEmpty() && state.getLinesWritten() > 0) {
lines.append(JSON_OBJECT_SEPARATOR).append(this.lineSeparator);
Expand All @@ -109,4 +134,23 @@ public String doWrite(Chunk<? extends T> items) {
return lines.toString();
}

private void reopen(File file) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
long pos = raf.length();
boolean stopFound = false;
while (--pos >= 0) {
raf.seek(pos);
int current = raf.readByte();
if (!stopFound && current == JSON_ARRAY_STOP) {
stopFound = true;
}
else if (stopFound && !Character.isWhitespace(current)) {
this.hasExistingItems = current != JSON_ARRAY_START;
raf.setLength(this.hasExistingItems ? pos + 1 : pos);
break;
}
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.springframework.batch.infrastructure.item.json;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import org.junit.jupiter.api.BeforeEach;
Expand All @@ -25,18 +26,18 @@
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import tools.jackson.databind.json.JsonMapper;

import org.springframework.batch.infrastructure.item.Chunk;
import org.springframework.batch.infrastructure.item.ExecutionContext;
import org.springframework.batch.infrastructure.item.json.JsonFileItemWriter;
import org.springframework.batch.infrastructure.item.json.JsonObjectMarshaller;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.WritableResource;

import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.*;

/**
* @author Mahmoud Ben Hassine
* @author Yanming Zhou
*/
@ExtendWith(MockitoExtension.class)
class JsonFileItemWriterTests {
Expand All @@ -49,6 +50,7 @@ class JsonFileItemWriterTests {
@BeforeEach
void setUp() throws Exception {
File file = Files.createTempFile("test", "json").toFile();
file.deleteOnExit();
this.resource = new FileSystemResource(file);
}

Expand All @@ -72,4 +74,90 @@ void itemsShouldBeMarshalledToJsonWithTheJsonObjectMarshaller() throws Exception
Mockito.verify(this.jsonObjectMarshaller).marshal("bar");
}

@Test
void appendAllowed() throws Exception {
JsonFileItemWriter<String> writer = new JsonFileItemWriter<>(this.resource,
new JacksonJsonObjectMarshaller<>());
writer.setAppendAllowed(true);

writer.open(new ExecutionContext());
writer.close();

resourceShouldContains();

writer.open(new ExecutionContext());
writer.write(Chunk.of("aaa"));
writer.write(Chunk.of("bbb"));
writer.close();

resourceShouldContains("aaa", "bbb");

writer.open(new ExecutionContext());
writer.close();

resourceShouldContains("aaa", "bbb");

writer.open(new ExecutionContext());
writer.write(Chunk.of("ccc"));
writer.close();

resourceShouldContains("aaa", "bbb", "ccc");
}

@Test
void appendAllowedWithUnformattedJson() throws Exception {
JsonFileItemWriter<String> writer = new JsonFileItemWriter<>(this.resource,
new JacksonJsonObjectMarshaller<>());
writer.setAppendAllowed(true);

Files.writeString(this.resource.getFilePath(), "[\n \"foo\"]", StandardCharsets.UTF_8);

resourceShouldContains("foo");

writer.open(new ExecutionContext());
writer.write(Chunk.of("bar"));
writer.close();

resourceShouldContains("foo", "bar");
}

@Test
void appendNotAllowed() throws Exception {
JsonFileItemWriter<String> writer = new JsonFileItemWriter<>(this.resource,
new JacksonJsonObjectMarshaller<>());

writer.open(new ExecutionContext());
writer.close();

resourceShouldContains();

writer.open(new ExecutionContext());
writer.write(Chunk.of("aaa"));
writer.write(Chunk.of("bbb"));
writer.close();

resourceShouldContains("aaa", "bbb");

writer.open(new ExecutionContext());
writer.close();

resourceShouldContains();

writer.open(new ExecutionContext());
writer.write(Chunk.of("ccc"));
writer.close();

resourceShouldContains("ccc");

writer.open(new ExecutionContext());
writer.write(Chunk.of("ddd"));
writer.close();

resourceShouldContains("ddd");
}

private void resourceShouldContains(String... array) throws Exception {
assertArrayEquals(array, new JsonMapper().readValue(this.resource.getContentAsByteArray(), String[].class));
}

}