DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • How To Propagate Context Information Throw Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch

Trending

  • YAGNI in the Age of AI Coding
  • How to Migrate From LangChainGo to Genkit Go
  • Should Developers Switch From SQLite to DuckDB?
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Batch FlatFileItemWriter Hacking

Spring Batch FlatFileItemWriter Hacking

Code snippets demonstrating how to use the FlatFileItemWriter class in Spring.

By 
Upender Chinthala
·
Apr. 09, 16 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
65.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In this article I explained how to use FlatFileItemWriter class to write a flat file without using a complete Spring batch flow.

Person.java domain object

package com.flatfile.domain;

public class Person {

   private final String firstName;
   private final String lastName;
   private final String middleName;

   public Person(String fn,String ln,String mn){
      this.firstName=fn;
      this.lastName=ln;
      this.middleName=mn;
   }
   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public String getMiddleName() {
      return middleName;
   }

   public String toString() {
      return firstName+"	"+lastName+"	"+middleName;
   }


}

PersonBuilder.java

This is a builder pattern for constructing a Person object:

package com.flatfile.domain;

public final class PersonBuilder {


   private  String firstName;
   private  String lastName;
   private  String middleName;

   private PersonBuilder() {}
   public static PersonBuilder newBuilder() {
      return new PersonBuilder();
   }

   public PersonBuilder firstName(String fn) {
      this.firstName=fn;
      return this;
   }
   public PersonBuilder lastName(String ln) {
      this.lastName=ln;
      return this;
   }
   public PersonBuilder middleName(String mn) {
      this.middleName=mn;
      return this;
   }
   public Person build() {
      return new Person(firstName,lastName,middleName);
   }
}

HeaderCopyCallback.java

This is a class for writing header into flat file. For more details, see the file-writer.xml Spring bean context file:

package com.flatfile.callback;

import java.io.IOException;
import java.io.Writer;

import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.LineCallbackHandler;
import org.springframework.util.Assert;

public class HeaderCopyCallback implements LineCallbackHandler, FlatFileHeaderCallback {

   private String header="";

   public HeaderCopyCallback(String columns) {
      header=columns;
   }
   @Override
   public void writeHeader(Writer writer) throws IOException {
      writer.write(header);
   }

   @Override
   public void handleLine(String line) {

      Assert.notNull(line);
      this.header = line;
   }

}

FlatFileRecordsWriter.java

This is an interface for callback. See the implementation in FlatFileWriterTemplate.java, FileWriter.java class.

package com.flatfile.callback;

import java.util.List;

public interface FlatFileRecordsWriter<T> {

   List<? extends T> doWrite();
}

FlatFileWriterTemplate.java

Basically this template class is wrapping FlatFileItemWriter reference and also handling file opening,writing, and closing. This class is similar like JdbcTemplate

import java.util.List;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemWriter;

import com.flatfile.domain.Person;

public class FlatFileWriterTemplate {

   private final FlatFileItemWriter<Person> flatFileItemWriter;

   public FlatFileWriterTemplate(final FlatFileItemWriter<Person> flatFileItemWriter) {
      this.flatFileItemWriter=flatFileItemWriter;
   }

   public  void writeAll(FlatFileRecordsWriter<? extends Person> fwc) throws Exception {
       try {
          List<? extends Person> returnValue = fwc.doWrite();
          flatFileItemWriter.open(new ExecutionContext());
          flatFileItemWriter.write(returnValue);
       } 
       finally {
          flatFileItemWriter.close();
       }

   }


}

FlatFileWriter.java

FlatFileWriter class has two methods: write and writeAll.  The first write method takes one argument, i.e. a Person object, and writes it to a flat file. Another writeAll method takes the list of Person objects as an argument and writes them into a flat file.

package com.flatfile.manager;

import java.util.Arrays;
import java.util.List;

import com.flatfile.callback.FlatFileRecordsWriter;
import com.flatfile.callback.FlatFileWriterTemplate;
import com.flatfile.domain.Person;

public class FlatFileWriter {

   private final  FlatFileWriterTemplate flatFileWriterTemplate;

   public FlatFileWriter(FlatFileWriterTemplate flatFileWriterTemplate) {
      this.flatFileWriterTemplate=flatFileWriterTemplate;
   }

   public void write(final Person person) throws Exception {
     flatFileWriterTemplate.writeAll(new FlatFileRecordsWriter<Person>() {
      public List<? extends Person> doWrite() {
         return Arrays.asList(person);
      }
   });

  }

   public void writeAll(final List<? extends Person> person) throws Exception {
      flatFileWriterTemplate.writeAll(new FlatFileRecordsWriter<Person>() {
       public List<? extends Person> doWrite() {
          return person;
       }
    });

   }

}

FlatFileWriterTest.java

The below JUnit class shows how to use to FlatFileWriter's write and writeAll methods. 

package com.flatfile.writer;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.flatfile.domain.Person;
import com.flatfile.domain.PersonBuilder;
import com.flatfile.manager.FlatFileWriter;

@ContextConfiguration("/file-writer.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class FlatFileWriterTest {

   @Autowired
   private FlatFileWriter writer;

   @Test
   public void writeSinglePerson() throws Exception {

      Person person = PersonBuilder.newBuilder()
             .firstName("Scott")
             .lastName("Miller")
             .middleName("S").build();
         writer.write(person);

   }

   @Test
   public void writeMultiplePersonRecords() throws Exception {

      Person person1 = PersonBuilder.newBuilder()
             .firstName("Robert")
             .lastName("Hope")
             .middleName("C").build();

      Person person2 = PersonBuilder.newBuilder()
            .firstName("James")
            .lastName("Blake")
            .middleName("R").build();

      Person person3 = PersonBuilder.newBuilder()
            .firstName("Larry")
            .lastName("Chen")
            .middleName("S").build();

         writer.writeAll(Arrays.asList(person1,person2,person3));

   }
}

file-writer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
 http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean id="flatFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
<property name="resource" ref="outputResource" />
<property name="appendAllowed" value="true" />
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value=";"/>
<property name="fieldExtractor">
<bean  class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="firstName,lastName,middleName" />
</bean>
</property>
</bean>
</property>
<property name="headerCallback" ref="headerCopier" />
</bean>




<bean id="headerCopier"class="com.writer.HeaderCopyCallback" >
<constructor-arg value="FirstName;LastName;MiddleName"></constructor-arg>
</bean>

<bean id="outputResource" class="org.springframework.core.io.ClassPathResource">
<constructor-arg type="java.lang.String"
value="data/headerSample/person.txt" />
</bean>

<bean id="writerManager" class="com.flatfile.manager.FlatFileWriter">
<constructor-arg>
<bean class="com.flatfile.callback.FlatFileWriterTemplate">
<constructor-arg ref="flatFileWriter"></constructor-arg>
</bean>
</constructor-arg>
</bean>
</beans>

flatFileWriter

This class is an item writer that writes data to a file or stream. The writer also provides a restart. The location of the output file is defined by a Resource and must represent a writable file. Uses buffered writers to improve performance.

The implementation is not thread-safe.  (Spring doc)

DelimitedLineAggregator

A LineAggregator implementation that converts an object into a delimited list of strings. The default delimiter is a comma (from Spring doc).

BeanWrapperFieldExtractor

This is a field extractor for a Java bean. Given an array of property names, it will reflectively call getters on the item and return an array of all the values(from Spring docs). It extract Person's firstName,lastName, and middleName values and return to FlatFileItemWriter.

headerCopier

See the HeaderCopyCallback.java above for implementation. The bean provides header columns for the flat file.

outputResource

ClasspathResource-> Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources (from Spring doc). This bean points to the flat file location after writing header and records.

writerManager

This bean has a FlatFileWriterTempate reference and the client is going to invoke a writerManager.write/writeAll method. See the above class FlatFileWriter.java and FlatFilwWriterTest.java for example.

For the complete code please visit this link: https://github.com/upenderc/flatfile-hack

Spring Framework Spring Batch

Opinions expressed by DZone contributors are their own.

Related

  • High-Performance Batch Processing Using Apache Spark and Spring Batch
  • How To Propagate Context Information Throw Spring Batch
  • Batch Processing Large Data Sets with Spring Boot and Spring Batch
  • Migrating COBOL Batch to Spring Batch

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook