Pages

Tuesday, 18 December 2012

Simple JSP application to Read and Write XML Content

Simple JSP application to Read and Write XML Content

Let's take a case of simple news reader and writer application.

simple news.xml

<root_news>
<news id='1'>
    <date>1-1-11</date>
    <title>Stars at BBC Sports Awards</title>
    <description>Stars at BBC Sports Awards
Kate, the Duchess of Cambridge walks out to present Lord Sebastian Coe with the Lifetime Achievement Award during the BBC Sports Personality of the Year Awards 2012 in London, Sunday Dec. 16, 2012. (Photo: AP)</description>
</news>
<news id='2'>
    <date>2-2-12</date>
    <title>Cricket: 5 Legendary Umpires</title>
    <description>Cricket: 5 Legendary Umpires</description>
</news>
<news id='3'>
    <date>3-3-13</date>
    <title>PICS: Fun Christmas Activities</title>
    <description>Participants in the annual "Santa Speedo Run" leave the starting line in Boston
Participants in the annual "Santa Speedo Run," a charity race through the streets of the Back Bay neighborhood of Boston, Massachusetts leave the starting line.
</description>
</news>
<news id='4'>
    <date>4-4-14</date>
    <title>Apple in Talks with Foursquare Over Maps</title>
    <description>Apple Inc is in early discussions with Foursquare Labs Inc to integrate local data into the company's mapping application, the Wall Street Journal reported, citing people familiar with the talks.</description>
</news>
</root_news>


Our index.jsp displays one news section from xml file and has option to edit and update the news date,title and description. We are skipping validation for now to make it simpler.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="javax.xml.transform.Source"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="javax.xml.transform.Result"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.StringWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.FileOutputStream"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>News</title>
<%@page import="org.w3c.dom.Document"%>
<%@page import="java.io.InputStream"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory"%>
<%@page import="javax.xml.parsers.DocumentBuilder"%>
<%@page import="javax.xml.parsers.ParserConfigurationException"%>
<%@page import="org.xml.sax.SAXException"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.Element"%>
</head>
<body>

    <%
    Document doc = null;
    InputStream path = null;
    try {
        path = getServletContext().getResourceAsStream("news.xml");
        //File fXmlFile = new File(path);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(path);
        doc.getDocumentElement().normalize();           
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
   
    NodeList nodeList = doc.getElementsByTagName("news");
   
    String newsIdParam = "1";
   
    String date = "";
    String title = "";
    String desc = "";
   
    Element dateElement = null;
    Element titleElement = null;
    Element descElement = null;
   
    for(int i=0; i<nodeList.getLength();i++){
        Node node = nodeList.item(i);
        if(node.getNodeType() == Node.ELEMENT_NODE){
            Element element = (Element)node;
            String newsId = element.getAttribute("id");
            if(newsId.equals(newsIdParam)){
                NodeList childNodeList = element.getElementsByTagName("date");
                if(childNodeList !=null && childNodeList.getLength() == 1){
                    Node childNode = childNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        dateElement = (Element) childNode;
                        date = dateElement.getFirstChild().getNodeValue();
                    }                   
                }
                NodeList titleNodeList = element.getElementsByTagName("title");
                if(titleNodeList !=null && titleNodeList.getLength() == 1){
                    Node childNode = titleNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        titleElement = (Element) childNode;
                        title = titleElement.getFirstChild().getNodeValue();
                    }                   
                }
                NodeList descNodeList = element.getElementsByTagName("description");
                if(descNodeList !=null && descNodeList.getLength() == 1){
                    Node childNode = descNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        descElement = (Element) childNode;
                        desc = titleElement.getFirstChild().getNodeValue();
                    }                   
                }
            }   
        }
    }

    %>
    <form action="updateNews.jsp">
    <table>
        <tr>
            <td> Date :</td>
            <td><input type="text" id="date" name="date" value="<%=date %>"></input>
            </td>
        </tr>
        <tr>
            <td> Title :</td>
            <td><input type="text" id="title" name="title" value="<%=title %>"></input></td>
        </tr>
        <tr>
            <td> Description :</td>
            <td>    <textarea cols="50" rows="2" id="desc" name="desc"><%=desc %></textarea></td>
        </tr>
        <tr>
            <td> </td>
            <td><input type="submit" name="save" title="Update" value="Update"/></td>
        </tr>
    </table>
        <input type="hidden" name="id" value="1">
    </form>
</body>
</html>

Our updateNews.jsp will be called on click of update button in index.jsp page.
It will read parameters passed from index.jsp page, updates the xml node with new values,open xml file to write,and write the new content.

<%@page import="javax.xml.transform.OutputKeys"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@page import="javax.xml.transform.Source"%>
<%@page import="javax.xml.transform.dom.DOMSource"%>
<%@page import="javax.xml.transform.Result"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.StringWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="org.w3c.dom.Document"%>
<%@page import="java.io.InputStream"%>
<%@page import="javax.xml.parsers.DocumentBuilderFactory"%>
<%@page import="javax.xml.parsers.DocumentBuilder"%>
<%@page import="javax.xml.parsers.ParserConfigurationException"%>
<%@page import="org.xml.sax.SAXException"%>
<%@page import="org.w3c.dom.NodeList"%>
<%@page import="org.w3c.dom.Node"%>
<%@page import="org.w3c.dom.Element"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update News</title>
</head>
<body>

    <% String date=request.getParameter("date");
    String title=request.getParameter("title");
    String desc=request.getParameter("desc");
    String id = request.getParameter("id");
    out.println(date);
    out.println(title);
    out.println(desc);
    out.println(id);
   
    Document doc = null;
    InputStream path = null;
    try {
        path = getServletContext().getResourceAsStream("news.xml");
        //File fXmlFile = new File(path);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(path);
        doc.getDocumentElement().normalize();           
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
   
    NodeList nodeList = doc.getElementsByTagName("news");
   
    String newsIdParam = "1";
   
    Element dateElement = null;
    Element titleElement = null;
    Element descElement = null;
   
    for(int i=0; i<nodeList.getLength();i++){
        Node node = nodeList.item(i);
        if(node.getNodeType() == Node.ELEMENT_NODE){
            Element element = (Element)node;
            String newsId = element.getAttribute("id");
            if(newsId.equals(id)){
                NodeList childNodeList = element.getElementsByTagName("date");
                if(childNodeList !=null && childNodeList.getLength() == 1){
                    Node childNode = childNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        dateElement = (Element) childNode;
                    }                   
                }
                NodeList titleNodeList = element.getElementsByTagName("title");
                if(titleNodeList !=null && titleNodeList.getLength() == 1){
                    Node childNode = titleNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        titleElement = (Element) childNode;
                    }                   
                }
                NodeList descNodeList = element.getElementsByTagName("description");
                if(descNodeList !=null && descNodeList.getLength() == 1){
                    Node childNode = descNodeList.item(0);
                    if(childNode.getNodeType() == Node.ELEMENT_NODE){
                        descElement = (Element) childNode;
                    }                   
                }
            }   
        }
    }
   
    // updating values
    dateElement.getFirstChild().setNodeValue(date);
    titleElement.getFirstChild().setNodeValue(title);
    descElement.getFirstChild().setNodeValue(desc);
   
    doc.normalize();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer tFormer = tFactory.newTransformer();
    tFormer.setOutputProperty(OutputKeys.INDENT, "yes");
     //create string from xml tree
     StringWriter sw = new StringWriter();
     StreamResult result = new StreamResult(sw);
     DOMSource source = new DOMSource(doc);
     tFormer.transform(source, result);
     String xmlString = sw.toString();
     System.out.println(xmlString);
     System.out.println(result.getWriter().toString());
   
     File file = new File("D:\\Project\\news.xml");
     FileWriter fileWriter = new FileWriter(file);
     BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

     bufferedWriter.write(result.getWriter().toString());

     bufferedWriter.flush();
     bufferedWriter.close();   

    %>
</body>
</html>

Thats all ... :-)



Wednesday, 12 December 2012

Simple Csv Parser Example with POJO Class

Simple CSV parsing example with POJO class.

Copy below classes to appropriate folders and run the class CsvParserExample. 

Employee.java - com/csvparsing/pojo
CsvParserExample - com/csvparsing
ParseHelper -  com/csvparsing/common
employee.csv - com/csvparsing

Employee POJO,

package com.csvparsing.pojo;


/**
 * @author Sharoon
 *
 */
public class Employee {
   
    private int id;
    private String name;
    private String dob;
   
   
    public Employee(int id, String name,String dob){
        this.id = id;
        this.name = name;
        this.dob = dob;
    }
   
    public Employee() {
    }

    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the dob
     */
    public String getDob() {
        return dob;
    }
    /**
     * @param string the dob to set
     */
    public void setDob(String dob) {
        this.dob = dob;
    }

}


Main Class CsvParserExample,

package com.csvparsing;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.csvparsing.common.ParseHelper;
import com.csvparsing.pojo.Employee;

/**
 *
 * @author Sharoon
 *
 */
public class CsvParserExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        // Reading employee List
        List resultList = getEmployeeList();
        formatAndDisplay(resultList);
       
        // Insert a record into employee List
        Employee newEmployee = new Employee();
        newEmployee.setId(11);
        newEmployee.setName("Vijay");
        newEmployee.setDob("14/05/1985");
       
        insertEmployeee(newEmployee);
       
    }

    private static void insertEmployeee(Employee newEmployee) {
        try {
            FileWriter pw = new FileWriter("src/com/csvparsing/employees.csv",true);
           
            if(newEmployee !=null){
                pw.append(String.valueOf(newEmployee.getId()));
                pw.append(",");
                pw.append(newEmployee.getName());
                pw.append(",");
                pw.append(newEmployee.getDob().toString());               
                pw.append("\n");
            }
             pw.flush();
             pw.close();
           
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Method to get the list of people by their name
     * @param string
     * @return
     */
    public static List<Object> getEmployeeList() {
        Employee employee = new Employee();
        return processRecordsFromCSV("employees.csv", employee);
    }

    public static List<Object> processRecordsFromCSV(String fileName, Object record) {
        List<Object> recordList = new ArrayList<Object>();
           try{
                   String path = "src/com/csvparsing/"+fileName;
                BufferedReader br = new BufferedReader( new FileReader(path));
                String strLine = "";
               
                String[] columns = ParseHelper.getColumns(br);
                while((strLine = br.readLine()) != null){
                    Object newRecord = record.getClass().newInstance();
                    String[] values = strLine.split(",");
                    int size = values.length;
                    if(columns.length != size)
                        continue;
                   
                    for(int i=0;i< size;i++){
                        String columnName = columns[i];
                        Field f1 = record.getClass().getDeclaredField(columnName);
                        f1.setAccessible(true);
                        f1.set(newRecord, getTypedValue(f1.getType(),values[i]));
                    }
                    recordList.add(newRecord);
                }
                br.close();
            } catch(Exception e){
                    System.out.println("Exception occured while parsing CSV file : " + e);                 
            }
           
            return recordList;
    }
   
   
    /**
     * Method to get typed value
     * @param type
     * @param value
     * @return
     */
    private static Object getTypedValue(Class<?> type, String value) {
        Object typedValue = null;
        if(type == int.class){
            value = !"".equals(value)?value:"0";
            typedValue = Integer.parseInt(value);
        } else if(type == Date.class){
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");               
            try {
                typedValue = (Date)(formatter.parse(value));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if(type == Double.class){
            value = !"".equals(value)?value:"0.0";
            typedValue = Double.parseDouble(value);
        } else if(type == Float.class){
            value = !"".equals(value)?value:"0.0f";
            typedValue = Double.parseDouble(value);
        } else if(type == boolean.class){
            value = !"".equals(value)?value:"0.0f";
            typedValue = Boolean.parseBoolean(value);
        } else if(type == String.class){
            typedValue = value;
        }
        return typedValue;
    }   
    /**
     *
     * @param employeeList
     */
    public static void formatAndDisplay(List<Employee> employeeList) {
        System.out.println(" ##  - Employee Records - ##");
        System.out.println("Id \t"+"|"+"Name\t"+"|"+"|"+"DOB");
        for(Employee employee:employeeList){
            System.out.print(employee.getId()+"\t"+"|");
            System.out.print(employee.getName()+"\t"+"|");
            System.out.print(employee.getDob());
            System.out.println();
        }
       
    }

}

ParseHelper Class to get Columns and its count.



package com.csvparsing.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;

/**
 * @author Sharoon
 *
 */
public class ParseHelper {

    public static int NO_OF_COLUMNS = 0;
   
    public static String[] getColumns(BufferedReader br) {
       
        String record = "";
        StringTokenizer st = null;
        String[] columns = null;
       
        try {
            if((record = br.readLine()) != null){
                st = new StringTokenizer(record, ",");
                columns = new String[st.countTokens()];
                while(st.hasMoreTokens())
                {
                   
                    columns[NO_OF_COLUMNS] = st.nextToken();
                    NO_OF_COLUMNS++;
                }               
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return columns;
    }
      

}


Csv File employee.csv