Skip to content

Commit 127dd73

Browse files
parthkariamaibin
authored andcommitted
BAEL-243 Spring Batch using Partitioner (eugenp#2419)
* BAEL-1004 changes in variable names * BAEL-243 Spring Batch using Partitioner
1 parent 69d8c10 commit 127dd73

13 files changed

Lines changed: 399 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* Copyright 2006-2013 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.baeldung.spring_batch_intro.partitioner;
18+
19+
import java.util.HashMap;
20+
import java.util.Map;
21+
22+
import org.springframework.batch.core.partition.support.Partitioner;
23+
import org.springframework.batch.item.ExecutionContext;
24+
import org.springframework.core.io.Resource;
25+
import org.springframework.util.Assert;
26+
27+
public class CustomMultiResourcePartitioner implements Partitioner {
28+
29+
private static final String DEFAULT_KEY_NAME = "fileName";
30+
31+
private static final String PARTITION_KEY = "partition";
32+
33+
private Resource[] resources = new Resource[0];
34+
35+
private String keyName = DEFAULT_KEY_NAME;
36+
37+
/**
38+
* The resources to assign to each partition. In Spring configuration you
39+
* can use a pattern to select multiple resources.
40+
* @param resources the resources to use
41+
*/
42+
public void setResources(Resource[] resources) {
43+
this.resources = resources;
44+
}
45+
46+
/**
47+
* The name of the key for the file name in each {@link ExecutionContext}.
48+
* Defaults to "fileName".
49+
* @param keyName the value of the key
50+
*/
51+
public void setKeyName(String keyName) {
52+
this.keyName = keyName;
53+
}
54+
55+
/**
56+
* Assign the filename of each of the injected resources to an
57+
* {@link ExecutionContext}.
58+
*
59+
* @see Partitioner#partition(int)
60+
*/
61+
@Override
62+
public Map<String, ExecutionContext> partition(int gridSize) {
63+
Map<String, ExecutionContext> map = new HashMap<String, ExecutionContext>(gridSize);
64+
int i = 0, k = 1;
65+
for (Resource resource : resources) {
66+
ExecutionContext context = new ExecutionContext();
67+
Assert.state(resource.exists(), "Resource does not exist: " + resource);
68+
context.putString(keyName, resource.getFilename());
69+
context.putString("opFileName", "output" + k++ + ".xml");
70+
71+
map.put(PARTITION_KEY + i, context);
72+
i++;
73+
}
74+
return map;
75+
}
76+
77+
}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
package org.baeldung.spring_batch_intro.partitioner;
2+
3+
import java.io.IOException;
4+
import java.net.MalformedURLException;
5+
import java.text.ParseException;
6+
7+
import javax.sql.DataSource;
8+
9+
import org.baeldung.spring_batch_intro.model.Transaction;
10+
import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper;
11+
import org.springframework.batch.core.Job;
12+
import org.springframework.batch.core.Step;
13+
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
14+
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
15+
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
16+
import org.springframework.batch.core.configuration.annotation.StepScope;
17+
import org.springframework.batch.core.launch.JobLauncher;
18+
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
19+
import org.springframework.batch.core.repository.JobRepository;
20+
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
21+
import org.springframework.batch.item.UnexpectedInputException;
22+
import org.springframework.batch.item.file.FlatFileItemReader;
23+
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
24+
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
25+
import org.springframework.batch.item.xml.StaxEventItemWriter;
26+
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
27+
import org.springframework.beans.factory.annotation.Autowired;
28+
import org.springframework.beans.factory.annotation.Value;
29+
import org.springframework.context.annotation.Bean;
30+
import org.springframework.context.annotation.Configuration;
31+
import org.springframework.core.io.ClassPathResource;
32+
import org.springframework.core.io.FileSystemResource;
33+
import org.springframework.core.io.Resource;
34+
import org.springframework.core.io.support.ResourcePatternResolver;
35+
import org.springframework.core.task.TaskExecutor;
36+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
37+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
38+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
39+
import org.springframework.oxm.Marshaller;
40+
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
41+
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
42+
import org.springframework.transaction.PlatformTransactionManager;
43+
44+
@Configuration
45+
@EnableBatchProcessing
46+
public class SpringbatchPartitionConfig {
47+
48+
@Autowired
49+
ResourcePatternResolver resoursePatternResolver;
50+
51+
@Autowired
52+
private JobBuilderFactory jobs;
53+
54+
@Autowired
55+
private StepBuilderFactory steps;
56+
57+
@Bean(name = "partitionerJob")
58+
public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException {
59+
return jobs.get("partitionerJob")
60+
.start(partitionStep())
61+
.build();
62+
}
63+
64+
@Bean
65+
public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException {
66+
return steps.get("partitionStep")
67+
.partitioner("slaveStep", partitioner())
68+
.step(slaveStep())
69+
.taskExecutor(taskExecutor())
70+
.build();
71+
}
72+
73+
@Bean
74+
public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException {
75+
return steps.get("slaveStep")
76+
.<Transaction, Transaction> chunk(1)
77+
.reader(itemReader(null))
78+
.writer(itemWriter(marshaller(), null))
79+
.build();
80+
}
81+
82+
@Bean
83+
public CustomMultiResourcePartitioner partitioner() {
84+
CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner();
85+
Resource[] resources;
86+
try {
87+
resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv");
88+
} catch (IOException e) {
89+
throw new RuntimeException("I/O problems when resolving the input file pattern.", e);
90+
}
91+
partitioner.setResources(resources);
92+
return partitioner;
93+
}
94+
95+
@Bean
96+
@StepScope
97+
public FlatFileItemReader<Transaction> itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException {
98+
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
99+
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
100+
String[] tokens = { "username", "userid", "transactiondate", "amount" };
101+
tokenizer.setNames(tokens);
102+
reader.setResource(new ClassPathResource("input/partitioner/" + filename));
103+
DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<Transaction>();
104+
lineMapper.setLineTokenizer(tokenizer);
105+
lineMapper.setFieldSetMapper(new RecordFieldSetMapper());
106+
reader.setLinesToSkip(1);
107+
reader.setLineMapper(lineMapper);
108+
return reader;
109+
}
110+
111+
@Bean(destroyMethod = "")
112+
@StepScope
113+
public StaxEventItemWriter<Transaction> itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException {
114+
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>();
115+
itemWriter.setMarshaller(marshaller);
116+
itemWriter.setRootTagName("transactionRecord");
117+
itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename));
118+
return itemWriter;
119+
}
120+
121+
@Bean
122+
public Marshaller marshaller() {
123+
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
124+
marshaller.setClassesToBeBound(new Class[] { Transaction.class });
125+
return marshaller;
126+
}
127+
128+
@Bean
129+
public TaskExecutor taskExecutor() {
130+
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
131+
taskExecutor.setMaxPoolSize(5);
132+
taskExecutor.setCorePoolSize(5);
133+
taskExecutor.setQueueCapacity(5);
134+
taskExecutor.afterPropertiesSet();
135+
return taskExecutor;
136+
}
137+
138+
private JobRepository getJobRepository() throws Exception {
139+
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
140+
factory.setDataSource(dataSource());
141+
factory.setTransactionManager(getTransactionManager());
142+
// JobRepositoryFactoryBean's methods Throws Generic Exception,
143+
// it would have been better to have a specific one
144+
factory.afterPropertiesSet();
145+
return (JobRepository) factory.getObject();
146+
}
147+
148+
private DataSource dataSource() {
149+
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
150+
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL)
151+
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
152+
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
153+
.build();
154+
return db;
155+
}
156+
157+
private PlatformTransactionManager getTransactionManager() {
158+
return new ResourcelessTransactionManager();
159+
}
160+
161+
public JobLauncher getJobLauncher() throws Exception {
162+
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
163+
// SimpleJobLauncher's methods Throws Generic Exception,
164+
// it would have been better to have a specific one
165+
jobLauncher.setJobRepository(getJobRepository());
166+
jobLauncher.afterPropertiesSet();
167+
return jobLauncher;
168+
}
169+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.baeldung.spring_batch_intro.partitioner;
2+
3+
import org.springframework.batch.core.Job;
4+
import org.springframework.batch.core.JobExecution;
5+
import org.springframework.batch.core.JobParameters;
6+
import org.springframework.batch.core.launch.JobLauncher;
7+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
8+
9+
public class SpringbatchPartitionerApp {
10+
public static void main(final String[] args) {
11+
// Spring Java config
12+
final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
13+
context.register(SpringbatchPartitionConfig.class);
14+
context.refresh();
15+
16+
final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
17+
final Job job = (Job) context.getBean("partitionerJob");
18+
System.out.println("Starting the batch job");
19+
try {
20+
final JobExecution execution = jobLauncher.run(job, new JobParameters());
21+
System.out.println("Job Status : " + execution.getStatus());
22+
System.out.println("Job succeeded");
23+
} catch (final Exception e) {
24+
e.printStackTrace();
25+
System.out.println("Job failed");
26+
}
27+
}
28+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
username, user_id, transaction_date, transaction_amount
2+
devendra, 1234, 31/10/2015, 10000
3+
john, 2134, 3/12/2015, 12321
4+
robin, 2134, 2/02/2015, 23411
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
username, user_id, transaction_date, transaction_amount
2+
devendra, 1234, 31/10/2015, 10000
3+
john, 2134, 3/12/2015, 12321
4+
robin, 2134, 2/02/2015, 23411
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
username, user_id, transaction_date, transaction_amount
2+
devendra, 1234, 31/10/2015, 10000
3+
john, 2134, 3/12/2015, 12321
4+
robin, 2134, 2/02/2015, 23411
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
username, user_id, transaction_date, transaction_amount
2+
devendra, 1234, 31/10/2015, 10000
3+
john, 2134, 3/12/2015, 12321
4+
robin, 2134, 2/02/2015, 23411
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
username, user_id, transaction_date, transaction_amount
2+
devendra, 1234, 31/10/2015, 10000
3+
john, 2134, 3/12/2015, 12321
4+
robin, 2134, 2/02/2015, 23411
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<transactionRecord>
3+
<transactionRecord>
4+
<amount>10000.0</amount>
5+
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
6+
<userId>1234</userId>
7+
<username>devendra</username>
8+
</transactionRecord>
9+
<transactionRecord>
10+
<amount>12321.0</amount>
11+
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
12+
<userId>2134</userId>
13+
<username>john</username>
14+
</transactionRecord>
15+
<transactionRecord>
16+
<amount>23411.0</amount>
17+
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
18+
<userId>2134</userId>
19+
<username>robin</username>
20+
</transactionRecord>
21+
</transactionRecord>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<transactionRecord>
3+
<transactionRecord>
4+
<amount>10000.0</amount>
5+
<transactionDate>2015-10-31T00:00:00+05:30</transactionDate>
6+
<userId>1234</userId>
7+
<username>devendra</username>
8+
</transactionRecord>
9+
<transactionRecord>
10+
<amount>12321.0</amount>
11+
<transactionDate>2015-12-03T00:00:00+05:30</transactionDate>
12+
<userId>2134</userId>
13+
<username>john</username>
14+
</transactionRecord>
15+
<transactionRecord>
16+
<amount>23411.0</amount>
17+
<transactionDate>2015-02-02T00:00:00+05:30</transactionDate>
18+
<userId>2134</userId>
19+
<username>robin</username>
20+
</transactionRecord>
21+
</transactionRecord>

0 commit comments

Comments
 (0)