Hi Friends ,i will going to demosntrate how we can generate xml using spring batch application .
In this example i have used maven project structure ,
Project Structure is look like given below
The Code is as given below :
database script ::
(1)
DROP TABLE IF EXISTS `studentdb`.`batchstrn`;
CREATE TABLE `studentdb`.`batchstrn` (
`BATCHRUNID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`BATCHID` int(10) unsigned NOT NULL,
`REQDATE` datetime NOT NULL,
`PROCSTARTDATE` datetime NOT NULL,
`STATUSCODE` varchar(45) NOT NULL,
PRIMARY KEY (`BATCHRUNID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
Main Class :
package org.zip;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//@Component
public class App {
public static void main(String[] args) {
App obj = new App();
obj.run();
}
//batchstrn
private void run() {
String[] springConfig = { "spring/batch/jobs/student_excelList.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("XML_GEN");
Map<String, JobParameter> mapofParam = new HashMap<String, JobParameter>();
mapofParam.put("BATCHID", new JobParameter("3"));
JobParameters jobparam= new JobParameters(mapofParam);
try {
JobExecution execution = jobLauncher.run(job, jobparam);
System.out.println("Exit Status : " + execution.getStatus());
System.out.println("Exit Status : " + execution.getAllFailureExceptions());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
">
<context:annotation-config />
<context:component-scan base-package="org.batch" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
<property name="username" value="root" />
<property name="password" value="admin!@#" />
</bean>
<bean id="readListener" class="org.batch.listener.XmlReadListener" />
<batch:job id="XML_GEN" >
<batch:step id="XML_GEN_STEP1" next="XML_GEN_STEP2">
<batch:tasklet ref="XML_GEN_batchinit" >
</batch:tasklet>
</batch:step>
<batch:step id="XML_GEN_STEP2" >
<batch:tasklet>
<batch:chunk reader="XML_GEN_itemreader" writer="XML_GEN_itemwriter"
processor="XML_GEN_itemprocessor" commit-interval="10">
<batch:listeners>
<batch:listener ref="readListener"/>
</batch:listeners>
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<!-- TASKLET -->
<bean id="XML_GEN_batchinit" class="org.batch.tasklet.Student_InitTasklet"
scope="step">
<property name="batchId" value="#{jobParameters['BATCHID']}" />
</bean>
<!-- READ -->
<bean id="XML_GEN_itemreader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql"
value="select * from student where status='A'"
/>
<property name="rowMapper">
<bean class="org.batch.mapper.Student_RowMapper" />
</property>
</bean>
<!-- PROCESS -->
<bean id="XML_GEN_itemprocessor" class="org.batch.processor.Student_Processor"
scope="step" >
<property name="batchRunId" value="#{jobExecutionContext['BATCHRUNID']}" />
</bean>
<!-- WRITE -->
<bean id="XML_GEN_itemwriter" class="org.batch.writer.StudentGeneration_Writer" scope="step">
<property name="dataSource" ref="dataSource" />
<property name="batchRunId" value="#{jobExecutionContext['BATCHRUNID']}" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository"/>
</bean>
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
</bean>
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager
"/>
</beans>
CONTEXT.XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- stored job-meta in memory -->
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<!-- Read environment property -->
<bean id="envProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:META-INF/i18n/zip-batch.properties</value>
</list>
</property>
</bean>
</beans>
In this example i have used maven project structure ,
Project Structure is look like given below
The Code is as given below :
database script ::
(1)
DROP TABLE IF EXISTS `studentdb`.`batchstrn`;
CREATE TABLE `studentdb`.`batchstrn` (
`BATCHRUNID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`BATCHID` int(10) unsigned NOT NULL,
`REQDATE` datetime NOT NULL,
`PROCSTARTDATE` datetime NOT NULL,
`STATUSCODE` varchar(45) NOT NULL,
PRIMARY KEY (`BATCHRUNID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
Main Class :
package org.zip;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//@Component
public class App {
public static void main(String[] args) {
App obj = new App();
obj.run();
}
//batchstrn
private void run() {
String[] springConfig = { "spring/batch/jobs/student_excelList.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("XML_GEN");
Map<String, JobParameter> mapofParam = new HashMap<String, JobParameter>();
mapofParam.put("BATCHID", new JobParameter("3"));
JobParameters jobparam= new JobParameters(mapofParam);
try {
JobExecution execution = jobLauncher.run(job, jobparam);
System.out.println("Exit Status : " + execution.getStatus());
System.out.println("Exit Status : " + execution.getAllFailureExceptions());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
The Configuration file for job is as given below :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
">
<context:annotation-config />
<context:component-scan base-package="org.batch" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
<property name="username" value="root" />
<property name="password" value="admin!@#" />
</bean>
<bean id="readListener" class="org.batch.listener.XmlReadListener" />
<batch:job id="XML_GEN" >
<batch:step id="XML_GEN_STEP1" next="XML_GEN_STEP2">
<batch:tasklet ref="XML_GEN_batchinit" >
</batch:tasklet>
</batch:step>
<batch:step id="XML_GEN_STEP2" >
<batch:tasklet>
<batch:chunk reader="XML_GEN_itemreader" writer="XML_GEN_itemwriter"
processor="XML_GEN_itemprocessor" commit-interval="10">
<batch:listeners>
<batch:listener ref="readListener"/>
</batch:listeners>
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<!-- TASKLET -->
<bean id="XML_GEN_batchinit" class="org.batch.tasklet.Student_InitTasklet"
scope="step">
<property name="batchId" value="#{jobParameters['BATCHID']}" />
</bean>
<!-- READ -->
<bean id="XML_GEN_itemreader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="dataSource" />
<property name="sql"
value="select * from student where status='A'"
/>
<property name="rowMapper">
<bean class="org.batch.mapper.Student_RowMapper" />
</property>
</bean>
<!-- PROCESS -->
<bean id="XML_GEN_itemprocessor" class="org.batch.processor.Student_Processor"
scope="step" >
<property name="batchRunId" value="#{jobExecutionContext['BATCHRUNID']}" />
</bean>
<!-- WRITE -->
<bean id="XML_GEN_itemwriter" class="org.batch.writer.StudentGeneration_Writer" scope="step">
<property name="dataSource" ref="dataSource" />
<property name="batchRunId" value="#{jobExecutionContext['BATCHRUNID']}" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository"/>
</bean>
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
</bean>
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager
"/>
</beans>
CONTEXT.XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- stored job-meta in memory -->
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<!-- Read environment property -->
<bean id="envProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:META-INF/i18n/zip-batch.properties</value>
</list>
</property>
</bean>
</beans>
PROCESSOR:
package org.batch.processor;
import org.batch.model.Student;
import org.springframework.batch.item.ItemProcessor;
public class Student_Processor implements ItemProcessor<Student, Student> {
private int batchRunId;
@Override
public Student process(Student stdent) throws Exception {
// TODO Auto-generated method stub
return stdent;
}
public int getBatchRunId() {
return batchRunId;
}
public void setBatchRunId(int batchRunId) {
this.batchRunId = batchRunId;
}
}
WRITER :
package org.batch.writer;
/*import org.apache.commons.beanutils.PropertyUtils;*/
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.batch.model.Student;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class StudentGeneration_Writer implements ItemWriter<Student>,StepExecutionListener{
private JdbcTemplate jdbcTemplate;
int batchRunId;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
// TODO Auto-generated method stub
String sqlUpdate="UPDATE batchstrn SET STATUSCODE='S' WHERE BATCHRUNID=?";
jdbcTemplate.update(sqlUpdate,batchRunId);
return ExitStatus.COMPLETED;
}
@Override
public void beforeStep(StepExecution arg0) {
// TODO Auto-generated method stub
}
@Override
public void write(List<? extends Student> studentList) throws Exception {
// TODO Auto-generated method stub
List<Student> listStudent = new ArrayList<Student>();
for(Student dto:studentList)
{
Student studentObj = new Student();
studentObj.setId(dto.getId());
studentObj.setName(dto.getName());
studentObj.setCollege(dto.getCollege());
studentObj.setStatus(dto.getStatus());
listStudent.add(studentObj);
}
createXml(listStudent);
}
public int getBatchRunId() {
return batchRunId;
}
public void setBatchRunId(int batchRunId) {
this.batchRunId = batchRunId;
}
//new
public static void createXml(List<? extends Student> studentList)
{
/*
private String id ;
private String name;
private String college;
private String status;
*/
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("college");
doc.appendChild(rootElement);
// staff elements
for (Student student : studentList) {
Element staff = doc.createElement("Student");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue(student.getId());
staff.setAttributeNode(attr);
Element firstname = doc.createElement("name");
firstname.appendChild(doc.createTextNode(student.getName()));
staff.appendChild(firstname);
Element lastname = doc.createElement("college");
lastname.appendChild(doc.createTextNode(student.getCollege()));
staff.appendChild(lastname);
Element nickname = doc.createElement("status");
nickname.appendChild(doc.createTextNode(student.getStatus()));
staff.appendChild(nickname);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("D:\\file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
}
}
catch (Exception pce) {
pce.printStackTrace();
}
}
}
THANKS for reading this article.for any query ping me on pathak.nisarg@yahoo.com
Happy Learning!!