Spring Batch: Processing Data From Web Service to MongoDB
In this post, we will look at how to create a Spring Batch application that consumes web service data and insert it in the MongoDB database.
Join the DZone community and get the full member experience.
Join For FreeOverview
In this post, we will look on how to create a Spring Batch application that consumes web service data and insert it in the MongoDB database.
Requirements
Developers who are reading this article must be familiarized with Spring Batch (Example) and MongoDB.
Environments
Mongo database is deployed in MLab. Please follow the step in this Quick-Start.
Batch application is deployed in Heroku PaaS. For details, look here.
IDE STS or IntelliJ or Eclipse.
Java 8 JDK.
NB: Batch can be run locally as well.
Scenario
The global scenario steps are:
- Read data from web service, in this case: https://sunrise-sunset.org/api
Get coordinates of a list of cities, then call the API to read sunrise and sunset date time.
2. Process data and extract business data
Business processing of collected data
3. Insert processed data in MongoDB
Save processed data as mongo documents
Coding
- Input: List of cities data in JSON format in a local file as below:
[
{
"name":"Danemark",
"cities":[
{
"name":"Copenhague",
"lat":55.676098,
"lng":12.568337,
"timeZone":"CET"
},
{
"name":"Aarhus",
"lat":56.162939,
"lng":10.203921,
"timeZone":"CET"
},
{
"name":"Odense",
"lat":55.39594,
"lng":10.38831,
"timeZone":"CET"
},
{
"name":"Aalborg",
"lat":57.046707,
"lng":9.935932,
"timeZone":"CET"
}
]
}
]
Our scenario takes input data from local json file. Mapping beans are as below:
Country bean:
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
ignoreUnknown = true) (
public class BCountry implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private List<BCity> cities;
public BCountry() {
super();
}
public BCountry(String name, List<BCity> cities) {
super();
this.name = name;
this.cities = cities;
}
public BCountry(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<BCity> getCities() {
return cities;
}
public void setCities(List<BCity> cities) {
this.cities = cities;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cities == null) ? 0 : cities.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BCountry other = (BCountry) obj;
if (cities == null) {
if (other.cities != null)
return false;
} else if (!cities.equals(other.cities))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String toString() {
return "BCountry [name=" + name + ", cities=" + cities + "]";
}
}
and City Bean:
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
ignoreUnknown = true) (
public class BCity implements Serializable {
private static final long serialVersionUID = 1L;
private String name, timeZone;
private double lat, lng;
public BCity() {
super();
}
public BCity(String name, String timeZone, double lat, double lng) {
super();
this.name = name;
this.timeZone = timeZone;
this.lat = lat;
this.lng = lng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String toString() {
return "BCity [name=" + name + ", timeZone=" + timeZone + ", lat=" + lat + ", lng=" + lng + "]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(lat);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(lng);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((timeZone == null) ? 0 : timeZone.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BCity other = (BCity) obj;
if (Double.doubleToLongBits(lat) != Double.doubleToLongBits(other.lat))
return false;
if (Double.doubleToLongBits(lng) != Double.doubleToLongBits(other.lng))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (timeZone == null) {
if (other.timeZone != null)
return false;
} else if (!timeZone.equals(other.timeZone))
return false;
return true;
}
}
Batch reader implement @LineMapper. You can adapt the reader to our data sources (Example):
import java.util.List;
import org.springframework.batch.item.file.LineMapper;
import com.ahajri.batch.beans.BCountry;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
public class BCountryJsonLineMapper implements LineMapper<List<BCountry>> {
private final ObjectMapper mapper = new ObjectMapper();
public List<BCountry> mapLine(String line, int lineNumber) throws Exception {
CollectionType collectionType =mapper.getTypeFactory().constructCollectionType(List.class, BCountry.class);
return mapper.readValue(line, collectionType);
}
}
When processing data Batch, check if business processed data for a given city on the same day is already saved in the database. Generic way for searching data in MongoDB is detailed in this post.
ItemProcessor transform @BCountry object to MongoDB Document objects. The process is detailed below:
public class BCountryPrayTimeEventItemProcessor implements ItemProcessor<List<BCountry>, List<Document>> {
private static final String EVENTS_COLLECTION_NAME = "event";
private static final Logger LOG = LoggerFactory.getLogger(BCountryPrayTimeEventItemProcessor.class);
private PrayTimeService prayTimeService;
private CloudMongoService cloudMongoService;
public List<Document> process(List<BCountry> items) throws Exception {
final List<Document> docs = new ArrayList<>();
items.stream().forEach(item -> {
final String countryName = item.getName();
item.getCities().stream().forEach(c -> {
final Document prayTimeCityEventDoc = new Document();
// loop cities and extract pray time for today
final String cityName = c.getName();
final String cityTimeZone = c.getTimeZone();
final double lat = c.getLat();
final double lng = c.getLng();
final LocalDateTime nowOfCity = LocalDateTime.now(ZoneId.of(cityTimeZone));
final QueryParam[] queryParams = new QueryParam[5];
queryParams[0] = new QueryParam("city_name", OperatorEnum.EQ.name(), cityName);
queryParams[1] = new QueryParam("event_type", OperatorEnum.EQ.name(), EventType.PRAY_TIME.name());
queryParams[2] = new QueryParam("month", OperatorEnum.EQ.name(), nowOfCity.getMonthValue());
queryParams[3] = new QueryParam("day_of_month", OperatorEnum.EQ.name(), nowOfCity.getDayOfMonth());
queryParams[4] = new QueryParam("country_name", OperatorEnum.EQ.name(), countryName);
List<Document> foundEvents = null;
try {
foundEvents = cloudMongoService.search(EVENTS_COLLECTION_NAME, queryParams);
} catch (BusinessException e1) {
LOG.error("====>No pray time found for city " + cityName + " on " + nowOfCity.getDayOfMonth() + "/"
+ nowOfCity.getMonthValue());
}
try {
if (CollectionUtils.isEmpty(foundEvents)) {
// Pray time not created yet
prayTimeCityEventDoc.put("country_name", countryName);
prayTimeCityEventDoc.put("city_name", cityName);
prayTimeCityEventDoc.put("event_type", EventType.PRAY_TIME.name());
prayTimeCityEventDoc.put("recurring", RecurringEnum.YEARLY.name());
prayTimeCityEventDoc.put("month", nowOfCity.getMonthValue());
prayTimeCityEventDoc.put("day_of_month", nowOfCity.getDayOfMonth());
prayTimeCityEventDoc.put("lat", lat);
prayTimeCityEventDoc.put("lng", lng);
prayTimeCityEventDoc.put("creation_date", HCDateUtils.convertToDateViaSqlTimestamp(nowOfCity));
final Map<String, Object> prayInfos = prayTimeService.getPrayTimeByLatLngDate(lat, lng,
Date.from(nowOfCity.atZone(ZoneId.of(cityTimeZone)).toInstant()), cityTimeZone);
prayTimeCityEventDoc.put("pray_infos", Document.parse(new Gson().toJson(prayInfos)));
docs.add(prayTimeCityEventDoc);
} else {
LOG.info(String.format("====>Pray time already exists for city: %s, month: %d, day: %d",
cityName, nowOfCity.getMonthValue(), nowOfCity.getDayOfMonth()));
}
} catch (BusinessException e) {
LOG.error("Problem while calculating pray time: ", e);
throw new RuntimeException(e);
}
});
});
return docs;
}
}
Batch Configuration class:
public class BatchConfiguration {
private static final String SCANDINAVIAN_COUNTRIES_JSON_FILE = "scandinavian-countries.json";
private static final String EVENT_COLLECTION_NAME = "event_collection";
private static final Logger LOG = LoggerFactory.getLogger(BatchConfiguration.class);
private JobBuilderFactory jobBuilderFactory;
private StepBuilderFactory stepBuilderFactory;
private MLabMongoService mlabMongoService;
public ResourcelessTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager txManager)
throws Exception {
MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(txManager);
factory.afterPropertiesSet();
return factory;
}
public JobRepository jobRepository(MapJobRepositoryFactoryBean factory) throws Exception {
return (JobRepository) factory.getObject();
}
private SimpleJobLauncher jobLauncher;
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
jobLauncher.setJobRepository(jobRepository);
return jobLauncher;
}
private void initJobLauncher() {
jobLauncher = new SimpleJobLauncher();
}
FlatFileItemReader<List<BCountry>> reader() {
FlatFileItemReader<List<BCountry>> reader = new FlatFileItemReader<>();
reader.setName("scandinaviandCountriesReader");
reader.setResource(new ClassPathResource(SCANDINAVIAN_COUNTRIES_JSON_FILE));
reader.setLineMapper(new BCountryJsonLineMapper());
return reader;
}
public ItemWriter<List<Document>> writer() {
return new ItemWriter<List<Document>>() {
public void write(List<? extends List<Document>> items) throws Exception {
try {
if (!CollectionUtils.isEmpty(items) && items.size() > 0) {
List<Document> flatDocs = items.stream().flatMap(List::stream).collect(Collectors.toList());
mlabMongoService.insertMany(EVENT_COLLECTION_NAME, flatDocs);
} else {
LOG.warn("No event to save ....");
}
} catch (BusinessException e) {
throw new RuntimeException(e);
}
}
};
}
public BCountryTimeEventItemProcessor processor() {
return new BCountryTimeEventItemProcessor();
}
public Job scandvTimeJob() {
return jobBuilderFactory.get("scandvTimeJob").incrementer(new RunIdIncrementer()).flow(step1()).end()
.build();
}
public Step step1() {
return stepBuilderFactory.get("step1").<List<BCountry>, List<Document>>chunk(10).reader(reader())
.processor(processor()).writer(writer()).build();
}
// end::jobstep[]
//run at midnight 15 minutes every day
cron = "0 15 0 * * *") (
public void startScandvEventTimeJob() throws Exception {
LOG.info(" ====> Job Started at :" + new Date());
JobParameters param = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis()))
.toJobParameters();
JobExecution execution = jobLauncher.run(scandvPrayTimeJob(), param);
LOG.info(" ====> Job finished with status :" + execution.getStatus());
}
}
Deploy de Batch to Heroku:
git add .
git commit -m "Deploy Batch"
git push heroku master
NB: to disable default Batch launching add this to application.yml
spring:
batch:
job:
enabled: false
You can find the whole source code here :
Opinions expressed by DZone contributors are their own.
Comments