Aditya
Aditya

Reputation: 1058

Dynamically changing name of output excel file when importing it via spring batch framework

I have a spring batch application which imports excel files and it produces an output excel file with status column which can be either success or failure. Currently the application is working file. Below is the code for preparing job parameters

JobParameters jobParametersBuilder = new JobParametersBuilder().addString(TYPE, type)
    .addString(NAME, name).addString(FULL_PATH_FILE_NAME, filePath)
    .addLong(TIME, System.currentTimeMillis()).addString(OUTPUT_FILE_NAME, outputFile)
    .addString(INPUT_FILE_NAME, inputFile).toJobParameters();

As you can see, I have specified the name of the output file in the parameters. Now as mentioned above there can be two values with can come in status column of output excel files. Is there any way to change the outptut file name if there are some errors in the status column

eg: if there are not errors in any status column then the output name should be same as earlier output-xyz_currentTimeStamp (sample name) but if there is error in the status column then the name of file should be output/error-xyz_currentTimeStamp (sample name).

I was wondering if the name is already specified in the parameters then how can one dynamically change the file name in case of error.

enter image description here

Upvotes: 1

Views: 210

Answers (1)

Mahmoud Ben Hassine
Mahmoud Ben Hassine

Reputation: 31640

You have two options:

  1. Determine upfront that at least one of lines that will be written will have the status of "Exception" and dynamically configure the writer with the right file name. You can create a Tasklet step that does the check and puts the information in the execution context. The next step which is chunk-oriented can use a step-scoped writer which is dynamically configured with the pre-calculated file name from the execution context, something like:
@Bean
@StepScope
public FlatFileItemWriter itemWriter(@Value("#{jobExecutionContext['fileName']}") String fileName) {
    return new FlatFileItemWriterBuilder()
            .resource(new FileSystemResource(fileName))
            // set other properties
            .build();
}
  1. Use a subsequent step that checks if one of the written lines has a status of "Exception" and rename the file accordingly

Upvotes: 1

Related Questions