Skip to content

Add a streaming Json item reader #607

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
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
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ allprojects {
hibernateValidatorVersion = '6.0.4.Final'
hsqldbVersion = '2.4.0'
jackson2Version = '2.9.2'
gsonVersion = '2.8.5'
javaMailVersion = '1.6.0'
javaxBatchApiVersion = '1.0'
javaxInjectVersion = '1'
Expand Down Expand Up @@ -326,6 +327,7 @@ project('spring-batch-infrastructure') {

optional "javax.jms:javax.jms-api:$jmsVersion"
optional "com.fasterxml.jackson.core:jackson-databind:${jackson2Version}"
optional "com.google.code.gson:gson:${gsonVersion}"
compile("org.hibernate:hibernate-core:$hibernateVersion") { dep ->
optional dep
exclude group: 'org.jboss.spec.javax.transaction', module: 'jboss-transaction-api_1.1_spec'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2018 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
*
* http://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.json;

import com.google.gson.JsonSyntaxException;

import org.springframework.batch.item.json.domain.Trade;

/**
* @author Mahmoud Ben Hassine
*/
public class GsonJsonItemReaderFunctionalTests extends JsonItemReaderFunctionalTests {

@Override
protected JsonObjectReader<Trade> getJsonObjectReader() {
return new GsonJsonObjectReader<>(Trade.class);
}

@Override
protected Class<? extends Exception> getJsonParsingException() {
return JsonSyntaxException.class;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These exceptions being exposed outside the impl is a leaky abstraction. We should be catching the implementation's exception and wrapping it in a standard exception. Using the Marshaller as an example, it throws an XmlMappingException if there is an issue and that would wrap the underlying implementation's exception.

Copy link
Contributor Author

@fmbenhassine fmbenhassine May 30, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree! Good catch. The best exception I see as a wrapper is org.springframework.batch.item.ParseException.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 53262e6. Now the implementation detail exception is wrapped in a ParseException.

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2018 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
*
* http://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.json;

import com.fasterxml.jackson.core.JsonParseException;

import org.springframework.batch.item.json.domain.Trade;

/**
* @author Mahmoud Ben Hassine
*/
public class JacksonJsonItemReaderFunctionalTests extends JsonItemReaderFunctionalTests {

@Override
protected JsonObjectReader<Trade> getJsonObjectReader() {
return new JacksonJsonObjectReader<>(Trade.class);
}

@Override
protected Class<? extends Exception> getJsonParsingException() {
return JsonParseException.class;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright 2018 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
*
* http://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.json;

import java.math.BigDecimal;

import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.json.builder.JsonItemReaderBuilder;
import org.springframework.batch.item.json.domain.Trade;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;

import static org.hamcrest.Matchers.instanceOf;

/**
* @author Mahmoud Ben Hassine
*/
public abstract class JsonItemReaderFunctionalTests {

@Rule
public ExpectedException expectedException = ExpectedException.none();

protected abstract JsonObjectReader<Trade> getJsonObjectReader();

protected abstract Class<? extends Exception> getJsonParsingException();

@Test
public void testJsonReading() throws Exception {
JsonItemReader<Trade> itemReader = new JsonItemReaderBuilder<Trade>()
.jsonObjectReader(getJsonObjectReader())
.resource(new ClassPathResource("org/springframework/batch/item/json/trades.json"))
.name("tradeJsonItemReader")
.build();

itemReader.open(new ExecutionContext());

Trade trade = itemReader.read();
Assert.assertNotNull(trade);
Assert.assertEquals("123", trade.getIsin());
Assert.assertEquals("foo", trade.getCustomer());
Assert.assertEquals(new BigDecimal("1.2"), trade.getPrice());
Assert.assertEquals(1, trade.getQuantity());

trade = itemReader.read();
Assert.assertNotNull(trade);
Assert.assertEquals("456", trade.getIsin());
Assert.assertEquals("bar", trade.getCustomer());
Assert.assertEquals(new BigDecimal("1.4"), trade.getPrice());
Assert.assertEquals(2, trade.getQuantity());

trade = itemReader.read();
Assert.assertNull(trade);
}

@Test
public void testEmptyResource() throws Exception {
JsonItemReader<Trade> itemReader = new JsonItemReaderBuilder<Trade>()
.jsonObjectReader(getJsonObjectReader())
.resource(new ByteArrayResource("[]".getBytes()))
.name("tradeJsonItemReader")
.build();

itemReader.open(new ExecutionContext());

Trade trade = itemReader.read();
Assert.assertNull(trade);
}

@Test
public void testInvalidResourceFormat() {
this.expectedException.expect(ItemStreamException.class);
this.expectedException.expectMessage("Failed to initialize the reader");
this.expectedException.expectCause(instanceOf(IllegalStateException.class));
JsonItemReader<Trade> itemReader = new JsonItemReaderBuilder<Trade>()
.jsonObjectReader(getJsonObjectReader())
.resource(new ByteArrayResource("{}, {}".getBytes()))
.name("tradeJsonItemReader")
.build();

itemReader.open(new ExecutionContext());
}

@Test
public void testInvalidResourceContent() throws Exception {
this.expectedException.expect(ParseException.class);
this.expectedException.expectCause(Matchers.instanceOf(getJsonParsingException()));
JsonItemReader<Trade> itemReader = new JsonItemReaderBuilder<Trade>()
.jsonObjectReader(getJsonObjectReader())
.resource(new ByteArrayResource("[{]".getBytes()))
.name("tradeJsonItemReader")
.build();
itemReader.open(new ExecutionContext());

itemReader.read();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright 2018 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
*
* http://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.json.domain;

import java.math.BigDecimal;

/**
* @author Mahmoud Ben Hassine
*/
public class Trade {

private String isin = "";

private long quantity = 0;

private BigDecimal price = new BigDecimal(0);

private String customer = "";

public Trade() {
}

public Trade(String isin, long quantity, BigDecimal price, String customer) {
this.isin = isin;
this.quantity = quantity;
this.price = price;
this.customer = customer;
}

public void setCustomer(String customer) {
this.customer = customer;
}

public void setIsin(String isin) {
this.isin = isin;
}

public void setPrice(BigDecimal price) {
this.price = price;
}

public void setQuantity(long quantity) {
this.quantity = quantity;
}

public String getIsin() {
return isin;
}

public BigDecimal getPrice() {
return price;
}

public long getQuantity() {
return quantity;
}

public String getCustomer() {
return customer;
}

@Override
public String toString() {
return "Trade: [isin=" + this.isin + ",quantity=" + this.quantity + ",price=" + this.price + ",customer="
+ this.customer + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customer == null) ? 0 : customer.hashCode());
result = prime * result + ((isin == null) ? 0 : isin.hashCode());
result = prime * result + ((price == null) ? 0 : price.hashCode());
result = prime * result + (int) (quantity ^ (quantity >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Trade other = (Trade) obj;
if (customer == null) {
if (other.customer != null)
return false;
}
else if (!customer.equals(other.customer))
return false;
if (isin == null) {
if (other.isin != null)
return false;
}
else if (!isin.equals(other.isin))
return false;
if (price == null) {
if (other.price != null)
return false;
}
else if (!price.equals(other.price))
return false;
if (quantity != other.quantity)
return false;
return true;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"isin": "123",
"quantity": 1,
"price": 1.2,
"customer": "foo"
},
{
"isin": "456",
"quantity": 2,
"price": 1.4,
"customer": "bar"
}
]
Loading