Thursday 26 November 2015

Procedure Call Using Jasper Reports ,Spring MVC

Hello friends.today i am going to demonstrate you how we can call procedure through Jasper reports.

The Project Structure is given below :

The Code is as given below.

MODEL CLASS 

package org.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="student")
public class Student
{

@Id @Column(name="id")
private String studentid;
@Column
private String name;



public Student(){}
public String getStudentid() {
return studentid;
}


public void setStudentid(String studentid) {
this.studentid = studentid;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}





}

CONTROLLER:
package org.demo.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

import org.apache.commons.dbcp.BasicDataSource;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller

public class StudentController
{

    
   @RequestMapping(value="/show_student", method=RequestMethod.GET)
   public String showStudent(@ModelAttribute("student1") Student student) {
      
       return "show_student";
   }
   
   @RequestMapping(method = RequestMethod.POST , value = "/GenerateReport")
   public @ResponseBody void generatePdfReport(ModelAndView modelAndView,HttpServletRequest request,HttpServletResponse response) throws SQLException{
 
WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
StudentDAO dao=(StudentDAO)context.getBean("studentDAO");
BasicDataSource dataSource = (BasicDataSource)context.getBean("myDataSource");
String contextPath = request.getServletContext().getRealPath("report/StudentReport.jrxml");
dao.generatePdfReport(dataSource,contextPath);
      
    }
   }

DAO LAYER:
package org.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.query.JRQueryExecuterFactory;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.commons.dbcp.BasicDataSource;
import org.codehaus.jackson.map.ObjectMapper;
import org.demo.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.orm.hibernate3.HibernateTemplate;

@SuppressWarnings("deprecation")
public class StudentDAO {
private HibernateTemplate template;
@Autowired
private BasicDataSource myDataSource;

public HibernateTemplate getTemplate() {
return template;
}

public void setTemplate(HibernateTemplate template) {
this.template = template;
}

public StudentDAO(HibernateTemplate template) {
this.template = template;
}

public void insert(Student student) {

template.save(student);

}

public List<Student> getStudents() {
return template.find("from student");

}

public void generatePdfReport(BasicDataSource dataSource, String contextPath)
throws SQLException {

Connection conn = dataSource.getConnection();

try {

InputStream input = new FileInputStream(new File(contextPath));

System.out.println("Context Path is  : =" + contextPath);
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println("Compiling Report Designs");

JasperReport jasperReport = JasperCompileManager
.compileReport(jasperDesign);

jasperReport.setProperty(
"net.sf.jasperreports.query.executer.factory.plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");


JRProperties.setProperty(
JRQueryExecuterFactory.QUERY_EXECUTER_FACTORY_PREFIX
+ "plsql",
"com.jaspersoft.jrx.query.PlSqlQueryExecuterFactory");
System.out.println("Creating JasperPrint Object");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("studId", "1");

JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, parameters, conn);

int pages=jasperPrint.getPages().size();
if(pages != 0)
{
File f = new File("d:\\Studentnew.pdf");
f.createNewFile();

// Exporting the report
OutputStream output = new FileOutputStream(f);

JasperExportManager.exportReportToPdfStream(jasperPrint, output);

System.out.println("Report Generation Complete");
}
else
{
System.out.println(" NO DATA FOUND TO EXPORT .....");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

}

public void callStoredProcedure(BasicDataSource datasource) {

ObjectMapper m = new ObjectMapper();
JdbcTemplate template = new JdbcTemplate(datasource);
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(template)
.withProcedureName("getStudent");

Map<String, Object> inParamMap = new HashMap<String, Object>();

inParamMap.put("int_stockcode", 1);

SqlParameterSource in = new MapSqlParameterSource(inParamMap);

Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in);

System.out.println(simpleJdbcCallResult);

System.out.println(simpleJdbcCallResult.get("name"));
// Student anotherBean = m.convertValue(simpleJdbcCallResult,
// Student.class);

// System.out.println(anotherBean.getStudentid());
// System.out.println(anotherBean.getName());
Iterator iterator = simpleJdbcCallResult.entrySet().iterator();

while (iterator.hasNext()) {
Student student = new Student();

/*
* student.setStudentid((String)simpleJdbcCallResult.get("id"));
* student.setName((String)simpleJdbcCallResult.get("name"));
* System.out.println("st5udent : =>"+student.getName());
*/
/*
* System.out.println("The key is: " + mapEntry.getKey() +
* ",value is :" + mapEntry.getValue());
*/
}

}

public static void main(String[] args) {

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"/context-conf.xml");

BasicDataSource datasource = (BasicDataSource) context
.getBean("myDataSource");
StudentDAO dao = (StudentDAO) context.getBean("studentDAO");

dao.callStoredProcedure(datasource);

}
}



WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ProcCallJasperSpring</display-name>
  <welcome-file-list>
    <welcome-file>add_student.jsp</welcome-file>
  </welcome-file-list>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/context-conf.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>


context-conf.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:mvc="http://www.springframework.org/schema/mvc"
    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/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"
        >
     
    
    
    
        <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<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="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>org.demo.model.Student</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg ref="mySessionFactory" />
</bean> 
<bean id="studentDAO" class="org.dao.StudentDAO">
   <constructor-arg ref="hibernateTemplate" />
</bean>
      
    
     
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:message" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    
    
     </beans>

InitStudent.js


function InitStudent()
{



$('#AddStudent').click(function()
{   
 
 AddStudent();
 
});

 
$('#GenerateReport').click(function()
{   
 
GenerateReport();
 
});

 
}


StudentLogic.js

function  AddStudent()
{
$.ajax({
  url: "add_student.html",
  dataType:'json',
  type:'post',
  data:  $('#StudentDetail').serialize(),
beforeSend: function() {
$.blockUI();
},
  success: function (dataCheck)
  {
  },
  error: function (xhr, ajaxOptions, thrownError) {}
});  
}
function GenerateReport()
{
$.ajax({
  url: "GenerateReport.html",
  dataType:'json',
  type:'post',
  data:  {},
beforeSend: function() {
$.blockUI();
},
  success: function (dataCheck)
  {
  },
  error: function (xhr, ajaxOptions, thrownError) {}
});  
}

add_student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://www.springframework.org/tags/form"
    prefix="springForm"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ADD STUDENT FORM </title>
<style>
.error {
    color: #ff0000;
    font-style: italic;
    font-weight: bold;
}
</style>
</head>



<script type="text/javascript" src="script/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="script/bootstrap.js"></script>
<script type="text/javascript" src="script/jquery-ui.min.js"></script>
<script type="text/javascript" src="script/jquery.layout-latest.js"></script>
<script type="text/javascript" src="script/local/grid.locale-en.js" ></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>



<script type="text/javascript" src="script/js/javascript.js"></script>

<script type="text/javascript" src="script/js/InitStudent.js"></script>

<script type="text/javascript" src="script/js/StudentLogic.js"></script>

<script type="text/javascript">

$(document).ready(function(){
InitStudent();
});
</script>
<body>
 
    <%-- <springForm:form method="POST" commandName="student"
        action="ValidateRequest"> --%>
        
        <form action="ValidateRequest" method="POST"></form>
        <table>
            <tr>
                <td>ID:</td>
                <td><input type="text" id="txtid" name="txtid">   </td>
               <%--  <td><springForm:errors path="txtid" cssClass="error" /></td> --%>
            </tr>
           
           <tr>
                <td>NAME:</td>
                <td><input type="text" id="txtname" name="txtname"></td>
                <%-- <td><springForm:errors path="txtname" cssClass="error" /></td> --%>
            </tr>
            
          
            <tr>
                <td colspan="3"><input type="submit"  id="AddStudent"  name="AddStudent" value="Submit"></td>
                <td colspan="3"><input type="submit"  id="GenerateReport"  name="GenerateReport" value="Generate Report"></td>
                
            </tr>
        </table>
 
  
 
</body>
</html>



 Procedure that i call from Java code is given below :

DELIMITER $$

DROP PROCEDURE IF EXISTS `getStudent` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getStudent`(studid VARCHAR(20))
BEGIN

SELECT id,name,college FROM student WHERE id = studid;
END $$

DELIMITER ;


Report will look like given below :


Happy Learning..!!



for any query ping me on pathak.nisarg@yahoo.com

Thanks for Reading..!

Saturday 14 November 2015

Spring Batch Xml Generation

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");

}


}

The Configuration file for job is as given below :

<?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>


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!!







Friday 18 September 2015

Spring Batch Processing Example

Hello Friends ,hope you all are fine.today i am going to demonstrate you ,how we can configure spring batch application.

Spring batch is useful to  process large volume data.consider scenario where we want to read data from database and write those all data into xml file.in this we can use Spring Batch.Spring Batch Provides classes and api's to read/write resources, transaction management,job processing statistics etc.

Apart from Spring jars, i have used two main jars which will be used for batch processing  :
(1)spring-batch-core-2.2.0.RELEASE.jar,
(2)spring-batch-infrastructure-2.2.0.RELEASE.jar

In this example i have used maven project structure ,i will read all files from particular directory ,make one zip of it and then i will dump all file details of that particular directory in database, apart from that i am also keeping track how many times batch will get executed.

Project Structure is look like 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;

(2)

DROP TABLE IF EXISTS `studentdb`.`zip_dtl`;
CREATE TABLE  `studentdb`.`zip_dtl` (
  `ZIP_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `FILE_NAME` varchar(45) NOT NULL,
  `FILE_PATH` varchar(45) NOT NULL,
  PRIMARY KEY (`ZIP_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=288 DEFAULT CHARSET=latin1;





Main Class  :
package org.zip;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
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();


}

private void run() {

String[] springConfig = { "spring/batch/jobs/job-zip-gen.xml" }; //xml that contains job configuration parameters

ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("zipGenJob");


try {

JobExecution execution = jobLauncher.run(job, new JobParameters());
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 :
job-zip-gen.xml
<?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
">


<import resource="../config/context.xml" />

<context:annotation-config/>
<context:component-scan base-package="org.zip"></context:component-scan>


<!-- datasource -->
<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="baseReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
        <property name="dataSource" ref="dataSource" />
        <property name="sqlQuery" value="select * from contact" />
</bean> -->


<job id="zipGenJob" xmlns="http://www.springframework.org/schema/batch">

<step id="zipGen">
   <tasklet ref="ZipGenerationTasklet" />
</step>
</job>


<bean id="ZipGenerationTasklet" class="org.zip.tasklet.ZipGenerationTasklet" >

<!-- <property name="dataSource" ref="dataSource"/> -->
<!-- <property name="directory" value="file:csv/inputs/" /> -->
<!--  <property name="SOURCE_FOLDER" value="${zip.batch.output_zip_file}"></property> -->
<!-- <property name="OUTPUT_ZIP_FILE" value="${zip.batch.source_folder}"></property> -->

</bean>



<!-- <task:scheduled-tasks>
   
<task:scheduled ref="zipGenJob" method="run" cron="*/5 * * * * *" />
   </task:scheduled-tasks>   -->

</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">


<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>

<!-- addd by nisarg pathak  -->

<!-- Read 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>

Model Class :

package org.zip.model;

import java.io.Serializable;

public class ZIPGEN implements Serializable {


/**
*
*/
private static final long serialVersionUID = 1L;
private int  ZIP_ID;
private String FILE_NAME;
public int getZIP_ID() {
return ZIP_ID;
}
public void setZIP_ID(int zIP_ID) {
ZIP_ID = zIP_ID;
}
public String getFILE_NAME() {
return FILE_NAME;
}
public void setFILE_NAME(String fILE_NAME) {
FILE_NAME = fILE_NAME;
}
public String getFILE_PATH() {
return FILE_PATH;
}
public void setFILE_PATH(String fILE_PATH) {
FILE_PATH = fILE_PATH;
}
private String FILE_PATH;



}



Tasklet to get files as well as dump those file details is as given below :

package org.zip.tasklet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.sql.DataSource;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Component;

@Component
public class ZipGenerationTasklet implements Tasklet, InitializingBean,StepExecutionListener {

/*private Resource directory;*/
List<String> fileList =new ArrayList<String>();
    private  String OUTPUT_ZIP_FILE= "D:\\MyFile.zip";
    private String SOURCE_FOLDER ="D:\\NisargPics";

private JdbcTemplate jdbcTemplate;
int batchid;
BigInteger batch_run_id;
private long batchId=2;

private SimpleJdbcCall simpleJdbcCall;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
simpleJdbcCall = new SimpleJdbcCall(dataSource).withFunctionName("get_id");
}

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



System.out.println("Proc call to get auto incr. value .....!");

SqlParameterSource  mapParam = new MapSqlParameterSource().addValue("name_","zip_dtl");


Map<String,Object> map =  simpleJdbcCall.execute(mapParam);

System.out.println("Executing The Procedure  .....!");
BigInteger id = (BigInteger)map.get("sequence_no_");

// batch_run_id=jdbcTemplate.queryForObject("SELECT sequence_no+1 FROM sequence_generate_tab", BigInteger.class);

String sql="INSERT INTO BATCHSTRN (BATCHRUNID,BATCHID,REQDATE,PROCSTARTDATE,STATUSCODE)"
+ "VALUES (?, ?, ?, ?, 'S')";

jdbcTemplate.update(sql,batch_run_id,batchId,getCurrentTimeStamp(),getCurrentTimeStamp());



System.out.println("Execution Start .....!");

generateFileList(new File(SOURCE_FOLDER));
zipIt(OUTPUT_ZIP_FILE,id);
   


System.out.println("Execution End .....!");

return RepeatStatus.FINISHED;

}
/*
public Resource getDirectory() {
return directory;
}

public void setDirectory(Resource directory) {
this.directory = directory;
}
*/
public void zipIt(String zipFile, BigInteger id){

//System.out.println("id:::::::::->"+id);

String sql = "INSERT INTO ZIP_DTL " +
"(ZIP_ID,FILE_NAME, FILE_PATH) VALUES (?, ?, ?)";
    byte[] buffer = new byte[1024];

    try{

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    System.out.println("Output to Zip : " + zipFile);

    int i =2;
    for(String file : this.fileList){
   
    System.out.println("File Added : " + file);
   
    //
   
    jdbcTemplate.update(sql,new Object[]{id,file,file});
     
    i=i+1;
     
   
    ZipEntry ze= new ZipEntry(file);
        zos.putNextEntry(ze);

        FileInputStream in =
                      new FileInputStream(SOURCE_FOLDER + File.separator + file);

        int len;
        while ((len = in.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
        }

        in.close();
    }

    zos.closeEntry();
    //remember close it
    zos.close();

    System.out.println("Done");
   }catch(IOException ex){
      ex.printStackTrace();  
   }
  }

   /**
    * Traverse a directory and get all files,
    * and add the file into fileList
    * @param node file or directory
    */
   public void generateFileList(File node){

    //add file only
if(node.isFile()){
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}

if(node.isDirectory()){
String[] subNote = node.list();
for(String filename : subNote){
generateFileList(new File(node, filename));
}
}

   }

   /**
    * Format the file path for zip
    * @param file file path
    * @return Formatted file path
    */
   private String generateZipEntry(String file){
    return file.substring(SOURCE_FOLDER.length()+1, file.length());
   }

@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub

}

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
// TODO Auto-generated method stub

stepExecution.getJobExecution().getExecutionContext()
.put("BATCHRUNID", batch_run_id);

return null;
}

@Override
public void beforeStep(StepExecution arg0) {
// TODO Auto-generated method stub

}

public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
}




for the sake of simplicity , I have shared the  project ,you can download it from following link
Download Project


for any query ping me on npjava90@gmail.com
Happy Learning...!!

Thanks

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...