user1514499
user1514499

Reputation: 771

spring batch getting data from file and passing to procedure

For a Spring batch project, I need to get the date from a file and then I need to pass this date to a procedure and then run the procedure.

Then the result of the procedure must be written to a csv file.
I tried using listeners but couldn't do this.

Can anyone please tell how this can be achieved or if possible can you share any sample code in github.

Upvotes: 1

Views: 1086

Answers (1)

Thrax
Thrax

Reputation: 1964

First of all, you will need to get the date from your file and store it in the JobExecutionContext. One of the most simple solution would be to create a custom Tasklet to read the text file and store the result String in the context via a StepExecutionListener

This tasklet takes a file parameter and stores the result string with the key file.date :

public class CustomTasklet implements Tasklet, StepExecutionListener {

    private String date;
    private String file;    

    @Override
    public void beforeStep(StepExecution stepExecution) {}

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        stepExecution.getJobExecution().getExecutionContext().put("file.date", date);
    }

    @Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

         // Read from file using FileUtils (Apache)
         date = FileUtils.readFileToString(file);
    }

    public void setFile(String file) {
        this.file = file;
    }
}

Use it this way :

 <batch:step>
      <batch:tasklet>
            <bean class="xx.xx.xx.CustomTasklet">
                <property name="file" value="${file.path}"></property>
            </bean>
        </batch:tasklet>
 </batch:step>

Then you will use a Chunk with late binding to retrieve the previously stored value (i.e. using #{jobExecutionContext['file.date']}).

The reader will be a StoredProcedureItemReader :

<bean class="org.springframework.batch.item.database.StoredProcedureItemReader">
    <property name="dataSource" ref="dataSource" />
    <property name="procedureName" value="${procedureName}" />
    <property name="fetchSize" value="50" />
    <property name="parameters">
        <list>
            <bean class="org.springframework.jdbc.core.SqlParameter">
                <constructor-arg index="0" value="#{jobExecutionContext['file.date']}" />
            </bean>
        </list>
    </property>
    <property name="rowMapper" ref="rowMapper" />
    <property name="preparedStatementSetter" ref="preparedStatementSetter" />
</bean>

The writer will be a FlatFileItemWriter :

<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
    <property name="resource" value="${file.dest.path}" />
    <property name="lineAggregator" ref="lineAggregator" />
</bean>

Upvotes: 1

Related Questions