Friday 28 January 2011

CRUD with Serial Persistence - 5

This part of the CRUD with Serial Persistence Tutorial
include the servlets that are used. There are not any
change related to the seralization here. But I have
made some minor changes to fix some bugs.
HEre is the final code:

createServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;

public class createServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("ARSmsg: createServlet began to work");
}

public void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
HttpSession session = req.getSession();
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");

String id=String.valueOf(personDAO.getPersonNextId());
String firstName ="Please enter data here";
String lastName="Regards. ";
String hobby="Ali R+";
//personDAO.createRec(Integer.valueOf(id), firstName, lastName, hobby);
personDAO.createRec(firstName, lastName, hobby);

session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);
req.setAttribute("nameReq", firstName);
req.setAttribute("lastReq", lastName);
req.setAttribute("hobbyReq", hobby);
req.setAttribute("idReq", id);

RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req,resp);
}
}



deleteServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;
import mainPackage.*;
import daoPackage.*;

public class deleteServlet
extends HttpServlet {

/**
* Called once at startup
*/
public void init()
throws ServletException {
System.out.println("ARSmsg: deleteServlet began to work");
}

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
Person person = new Person();
HttpSession session = req.getSession();

try {
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
personDAO.deleteRec(personDAO.getPersonCurrentId());
person = personDAO.readRec(personDAO.getPersonCurrentId());

if (person != null) {
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);
req.setAttribute("nameReq", person.getName());
req.setAttribute("lastReq", person.getLast());
req.setAttribute("hobbyReq", person.getHobby());
req.setAttribute("idReq", String.valueOf(person.getId()));
}
RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req, resp);
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}



readNextServlet.java
--------------------
package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;

public class readNextServlet extends HttpServlet {

public void init()
throws ServletException {
System.out.println("ARSmsg: readNextServlet began to work");
}

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
Person person = new Person();
HttpSession session = req.getSession();

try {
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
person = personDAO.readNextRec();

if (person != null) {
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);
req.setAttribute("nameReq", person.getName());
req.setAttribute("lastReq", person.getLast());
req.setAttribute("hobbyReq", person.getHobby());
req.setAttribute("idReq", String.valueOf(person.getId()));
System.out.println("id=" + personDAO.getPersonNextId());
}
RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}

private String getOutput(String name) {
StringBuffer buffer = new StringBuffer();
buffer.append("<html><body><h2>Hello. Your name is: ");
buffer.append(name);
buffer.append("</h2></body></html>");

return buffer.toString();
}
}



readPrevServlet.java
--------------------
package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;

public class readPrevServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("ARSmsg: readPrevServlet began to work");
}

public void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = req.getSession();

try
{
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
person = personDAO.readPrevRec();

if (person != null){
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);
String id=String.valueOf(person.getId());
String firstName =person.getName();
String lastName=person.getLast();
String hobby=person.getHobby();

req.setAttribute("nameReq", firstName);
req.setAttribute("lastReq", lastName);
req.setAttribute("hobbyReq", hobby);
req.setAttribute("idReq", id);
System.out.println("id="+personDAO.getPersonNextId());
}
RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req,resp);

}
catch (Exception e)
{
e.printStackTrace();
}
finally
{

}
}
}



updateServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;

public class updateServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("Init() worked");
}

public void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = req.getSession();

try
{
String firstName = req.getParameter("name");
String lastName = req.getParameter("last");
String hobby = req.getParameter("hobby");
int id = Integer.valueOf(req.getParameter("id"));
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
personDAO.updateRec(id, firstName, lastName, hobby);

if (person != null){
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);

req.setAttribute("nameReq", firstName);
req.setAttribute("lastReq", lastName);
req.setAttribute("hobbyReq", hobby);
req.setAttribute("idReq", String.valueOf(id));
}
RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req,resp);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{

}
}
}


listServlet.java
----------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;

public class listServlet
extends HttpServlet
{
/**
* Called once at startup
*/
public void init()
throws ServletException
{
System.out.println("ARSmsg: listServlet began to work");
}

public void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{

RequestDispatcher view = getServletContext().getRequestDispatcher("/selectionList.jsp");
view.forward(req,resp);
}
}




selectListServlet.java
----------------------
package servletPackage;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import mainPackage.*;
import daoPackage.*;
import java.util.Enumeration;
import java.util.Iterator;

public class selectListServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("ARSmsg: selectListServlet began to work");
}

public void doGet( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
resp.setContentType("text/html");
PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = req.getSession();


for(Enumeration e = req.getAttributeNames(); e.hasMoreElements(); ){
String attName = (String)e.nextElement();
System.out.println(attName);
}

int currentRow = Integer.valueOf(req.getParameter("curRow"));
System.out.println("currentRow=================="+currentRow);

try
{
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
person = personDAO.readRec(currentRow);
req.setAttribute("nameReq", person.getName());
req.setAttribute("lastReq", person.getLast());
req.setAttribute("hobbyReq", person.getHobby());
req.setAttribute("idReq", String.valueOf(person.getId()));

RequestDispatcher view = getServletContext().getRequestDispatcher("/index.jsp");
view.forward(req,resp);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{

}
}


}

CRUD with Serial Persistence - 4

This section of CRUD with Serial Persistence includes
the code for the rest of the package. This section
only makes calls to the DAO so basicly it has not
changed. But I have corrected some minor discrepancies.
So please be careful, they are the last version of
Simple CRuD Tutorial.

web.xml
-------

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Simple CRUD of ARS</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>new</servlet-name>
<servlet-class>servletPackage.createServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readnext</servlet-name>
<servlet-class>servletPackage.readNextServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readprev</servlet-name>
<servlet-class>servletPackage.readPrevServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>servletPackage.updateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>delete</servlet-name>
<servlet-class>servletPackage.deleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>servletPackage.listServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>selectlist</servlet-name>
<servlet-class>servletPackage.selectListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>new</servlet-name>
<url-pattern>/new</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readnext</servlet-name>
<url-pattern>/readnext</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readprev</servlet-name>
<url-pattern>/readprev</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/save</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>delete</servlet-name>
<url-pattern>/delete</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/list</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>selectlist</servlet-name>
<url-pattern>/selectlist</url-pattern>
</servlet-mapping>
</web-app>



index.jsp
---------
<%--
Document : index
Created on : 15.Oca.2011, 18:23:21
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="mainPackage.*" %>
<%@ page import="daoPackage.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ARS's Simple CRUD</title>
<%
System.out.println("index.jsp JSP script began here.");
PersonDAOVectorImpl personDAO;
String nameVal="", lastVal="", hobbyVal="", idVal="";

if (session.getAttribute("personDAOsess") == null){
System.out.println("index.jsp personDAOsess == null ");
personDAO = new PersonDAOVectorImpl();
session.setAttribute("personDAOsess", personDAO);

Person person = personDAO.readRec(1);
nameVal= person.getName();
lastVal= person.getLast();
hobbyVal= person.getHobby();
idVal= String.valueOf(person.getId());

}
else {
System.out.println("index.jsp personDAOsess!!!!=null");
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");

nameVal = (String) request.getAttribute("nameReq");
lastVal = (String) request.getAttribute("lastReq");
hobbyVal = (String) request.getAttribute("hobbyReq");
idVal = (String) request.getAttribute("idReq");
}
%>
<SCRIPT>
function submitFunction(i) {
if (i==1) document.theDetail.action= "./new";
if (i==2) document.theDetail.action= "./save";
if (i==3) document.theDetail.action= "./delete";
if (i==4) document.theDetail.action= "./readnext";
if (i==5) document.theDetail.action= "./readprev";
if (i==6) document.theDetail.action= "./list";

document.theDetail.submit()
}
function InitScr() {
// alert ("Merhaba from Ali R+ with best wishes! ");
}

</SCRIPT>
</head>
<body style="background-color:yellow" onLoad="InitScr()">


<h1>The Simplest CRUD Application with JAVA</h1>

<br />

<form name="theDetail" action="" method="get">
<input type="hidden" name="id" value="<%= idVal%>"/><br />
First name: <input type="text" id ="nameId" name="name" value="<%= nameVal%>"/><br />
Last name : <input type="text" name="last" value="<%= lastVal%>"/><br />
Hobby : <input type="text" name="hobby" value="<%= hobbyVal%>"/><br />
<br />
<INPUT TYPE="button" VALUE="New" onClick="submitFunction(1)">
<INPUT TYPE="button" VALUE="Save" onClick="submitFunction(2)">
<INPUT TYPE="button" VALUE="Delete" onClick="submitFunction(3)">
<INPUT TYPE="button" VALUE="Next" onClick="submitFunction(4)">
<INPUT TYPE="button" VALUE="Prev" onClick="submitFunction(5)">
<INPUT TYPE="button" VALUE="List" onClick="submitFunction(6)">
</form>
</body>
</html>



tableARS.css
------------
table
{
position:fixed;
top:50px;
left:50px;
}
table, td, th
{
border:1px groove #ccccff ;
border-collapse:collapse;
}
th
{
background-color:#E3F6CE;
color: #ff9999;
}
td
{
background-color: whitesmoke;
color: black;
}




selectionList.jsp
-----------------
<%--
Document : list2
Created on : 19.Oca.2011, 20:15:28
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="mainPackage.*" %>
<%@ page import="daoPackage.*" %>

<html>

<head>

<style type="text/css">
span.title{
background-color: white;
color: #2470B3;
font-size: larger;
padding-top:5px;
padding-bottom:2px;
}
</style>

<link rel="stylesheet" type="text/css" href="selectionList.css" />

<%
PersonDAOVectorImpl personDAO;
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");

int id = personDAO.getPersonCurrentId();

System.out.println("ARSSSSsssss selectionList.jsp: id="+id);
%>

<script type='text/javascript'>
var currentRow=-1;

function SelectRow(newRow)
{
for(var j=1;j<5;++j)
{
var cell=document.getElementById('cell_'+newRow+','+j);
cell.style.background='#A3D0F7';
if(currentRow!=-1)
{
var cell=document.getElementById('cell_'+currentRow+','+j);

c = currentRow%2 == 0 ? 1 : 0;
if (c == 1) cell.style.background='e7e7e7';
else cell.style.background='whitesmoke';
}
}
currentRow=newRow;
document.getElementById('curRow').value=(currentRow-1)
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ali R+ Select Table Row</title>
</head>

<body>

<form name="theList" action="./selectlist" method="get">
<%
try {
Person person = personDAO.readRec(1);
// throws an exception if empty.
%>
<TABLE WIDTH="40%">
<TBODY>
<tr align="center">
<span class="title">Some of Ali R+'s Friends </span>
</tr>
<tr>
<th>Person Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Hobby</th>
</tr>
<%
for (int i = 1, c = 0;;) { //for all the elements of the data
System.out.println(person.getName());
if (c == 0) {
%>
<TR bgcolor="e7e7e7">
<%
} else {
%>
<TR bgcolor="whitesmoke">
<%
}
%>
<TD onclick='SelectRow(<%=(i+1)%>)' id='cell_<%=i+1%>,1'>
<%=person.getId()%>
</TD>
<TD onclick='SelectRow(<%=(i+1)%>)' id='cell_<%=i+1%>,2'>
<%=person.getName()%>
</TD>
<TD onclick='SelectRow(<%=(i+1)%>)' id='cell_<%=i+1%>,3'>
<%=person.getLast()%>
</TD>
<TD onclick='SelectRow(<%=(i+1)%>)' id='cell_<%=i+1%>,4'>
<%=person.getHobby()%>
</TD>
</TR>
<%
c = c == 0 ? 1 : 0;
i++;
if (i > personDAO.getPersonVect().size()) break;

try {
person = personDAO.readRec(i);
} catch (java.lang.ArrayIndexOutOfBoundsException _e0) {
break;
}
} //for all the elements of the data
%>
</TBODY>
</TABLE>
<%

} catch (java.lang.ArrayIndexOutOfBoundsException _e0) {

%>
<FONT>There is no data. </FONT>
<%
}
%>
<input type="hidden" id ="curRow" name="curRow" value="0"/><br />
<input type="submit"
value="View"
position:fixed
top:5px left:5px >
Please select a row by clicking on it and then click on the View button.
</form>
</body>
</html>



SelectionList.css
-----------------
table
{
position:fixed;
top:100px;
left:50px;
}
table, td, th
{
border:1px groove #ccccff ;
border-collapse:collapse;
}
th
{
background-color:#E3F6CE;
color: #ff9999;
}
td
{
color: black;
}



I have not included the source of static anf dinamic table select examples here.
If you are interested that means you need to study the 'Simple CRUD Tutorial' first.

CRUD with Serial Persistence - 3

This section will concentrate on the Serial Persistence
of the CRUD. I will also provide the complete code so
that you can compile and run it. The other option is
you are wellcome to make a request to get the WAR file
from arsaral (at) yahoo.com.


If you pay attention you may easily notice that the DAO
related sources are the same as the previous section.
Nevertheless I include them once more.

Please note that I may have corrected some minor discrepancies.





PersonDAO
---------
package daoPackage;

import java.util.Collection;
import mainPackage.*;

public interface PersonDAO {

public void createRec(String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public Person readRec(int personId)
throws PersonDAOSysException;

public void updateRec(int id, String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public void deleteRec(int personId)
throws PersonDAOSysException;

public boolean findByPrimaryKey(int personId)
throws PersonDAOSysException;

public Collection findByLastName(String lastName)
throws PersonDAOSysException;

public int findTotalNumberOfPersons()
throws PersonDAOSysException;
}


PersonDAOSysException.java
--------------------------
package daoPackage;

public class PersonDAOSysException extends RuntimeException {
public PersonDAOSysException (String str) {
super(str);
}
public PersonDAOSysException () {
super();
}
}


PersonDAOVectorImpl.java
------------------------
package daoPackage;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;
import javax.naming.*;
import java.sql.*;
import javax.sql.*;
import java.io.Serializable;
import mainPackage.*;

public class PersonDAOVectorImpl implements PersonDAO, Serializable {

private static Vector personVect;
private static int personNextId = 1;
private static int personCurrentId = 1;

public PersonDAOVectorImpl() {
System.out.println("PersonDAOVectorImpl constructor began.");
personVect = getDBConnection();

Enumeration vEnum = personVect.elements();
while (vEnum.hasMoreElements()) {
Person person = (Person) vEnum.nextElement();
System.out.println("ARSmsg: PersonDAOVectorImpl constructor person.name=" + person.getName() + " person.id=" + person.getId());
}
closeDBConnection();
}

public void createRec(String firstName, String lastName, String hobby)
throws PersonDAOSysException {
System.out.println("ARSmsg : createRec began.");

Person person = new Person();
try {
personVect = getDBConnection();
personNextId = personVect.size() + 1;
person.setId(personNextId);
person.setName(firstName);
person.setLast(lastName);
person.setHobby(hobby);
personVect.add(personVect.size(), person);
personCurrentId = personNextId;
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public void deleteRec(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg : deleteRec began.");
int posVect = 0;
try {
personVect = getDBConnection();
posVect = findRecSeq(personId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect != -1) {
personVect.removeElementAt(posVect - 1);
reorganiseVect();
} else {
System.out.println("ARSmsg: Delete - Not found!");
}
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public Collection findByLastName(String lastName) {
int posVect = 0;
Collection persons = new ArrayList();
Person person;

personVect = getDBConnection();
Iterator itr = personVect.iterator();

while (itr.hasNext()) {
person = (Person) itr.next();
//System.out.println("person.name=" + person.getName() + " person.id=" + person.getId());
if (person.getLast().equals(lastName)) {
persons.add(person.getId());
}
posVect = posVect + 1;
}
System.out.println("FindByLastName id=" + persons.toString());
closeDBConnection();
return (persons);
}

public int findTotalNumberOfPersons() throws PersonDAOSysException {
//System.out.println("ARSmsg: findTotalNumberOfPersons began-----------.");
int total = 0;
PreparedStatement stmt = null;
try {
personVect = getDBConnection();
total = personVect.size();
} catch (Exception ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeDBConnection();
}
System.out.println("ARSmsg: findTotalNumberOfPersons=" + total);
return total;
}

public Person readRec(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg : readRec began.");
Person person = new Person();
int posVect = 1;
try {
personVect = getDBConnection();
posVect = findRecSeq(personId);
System.out.println("read Rec personCurrentId=" + personCurrentId);
System.out.println("read Rec personNextId=" + personNextId);
System.out.println("readRec posVect=" + posVect);
if (posVect == -1) {
posVect = personCurrentId;
} else {
personCurrentId = posVect;
}
closeDBConnection();
return personVect.elementAt(posVect - 1);
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public Person readNextRec()
throws PersonDAOSysException {
System.out.println("ARSmsg : readNextRec began.");
Person person = new Person();
int posVect = 0;
try {
personVect = getDBConnection();
personCurrentId++;
posVect = findRecSeq(personCurrentId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = personVect.size();
personCurrentId--;
personCurrentId--;
}
person = (Person) personVect.elementAt(posVect - 1);
System.out.println("readNextRec person.name =" + (String) person.getName());
System.out.println();
closeDBConnection();
return person;

} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public Person readPrevRec() throws PersonDAOSysException {
System.out.println("ARSmsg : readPrevRec began.");
Person person = new Person();
int posVect = 0;
try {
personVect = getDBConnection();
personCurrentId--;
posVect = findRecSeq(personCurrentId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = 0;
personCurrentId++;
}
person = (Person) personVect.elementAt(posVect);
System.out.println("readPrevRec person.name =" + (String) person.getName());
closeDBConnection();
return person;

} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public void updateRec(int id, String firstName, String lastName,
String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg : updateRec began.");
int posVect = 0;
Person person = new Person();

try {
personVect = getDBConnection();

posVect = findRecSeq(id);
System.out.println("personNextId=" + personNextId);
System.out.println("posVect=" + posVect);

if (posVect == -1) {
posVect = personNextId;
}
System.out.println("posVect=" + posVect);

if (posVect < personVect.size() + 1) {
personVect.remove(posVect - 1);
person.setId(id);
} else {
person.setId(personNextId);
}
person.setName(firstName);
person.setLast(lastName);
person.setHobby(hobby);
personVect.add(posVect - 1, person);
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public boolean findByPrimaryKey(int id) {
int posVect = findRecSeq(id);
System.out.println("ARSmsg : findByPrimaryKey posVect=" + posVect);
if (posVect > -1) {
return (true);
}
return (false);
}

private int findRecSeq(int id) {
int posVect = 0;
Person person;

personVect = getDBConnection();
Iterator itr = personVect.iterator();

while (itr.hasNext()) {
person = (Person) itr.next();
posVect = posVect + 1;
//System.out.println("person.name=" + person.getName() + " person.id=" + person.getId());
if (person.getId() == id) {
closeDBConnection();
return posVect;
}
}
closeDBConnection();
return (-1);
}

private void reorganiseVect() {
int posVect = 0;
Person person;

Iterator itr = personVect.iterator();
while (itr.hasNext()) {
person = (Person) itr.next();
person.setId(posVect + 1);
posVect = posVect + 1;
}
personNextId = posVect + 1;
//personCurrentId = 1;
}

public void dumpVect() {
int posVect = 0;
Person person;

personVect = getDBConnection();
Iterator itr = personVect.iterator();
while (itr.hasNext()) {
person = (Person) itr.next();
System.out.println("id=" + person.getId()
+ " name=" + person.getName()
+ " lastName=" + person.getLast()
+ " hobby=" + person.getHobby());
}
closeDBConnection();
}

private Vector getDBConnection() throws PersonDAOSysException {
String filename = "personVect.ser";

Vector personVect = null;
FileInputStream fis = null;
ObjectInputStream in = null;

try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
personVect = (Vector) in.readObject();
in.close();
personNextId = personVect.size() + 1;
return personVect;
} catch (IOException ex) {
personVect = new Vector();

Person personalData;

personalData = new Person();
personalData.setId(1);
personalData.setName("Ali");
personalData.setLast("SARAL");
personalData.setHobby("Music Composition");
personVect.add(personalData);

personalData = new Person();
personalData.setId(2);
personalData.setName("Tamer");
personalData.setLast("ÜNAL");
personalData.setHobby("Folk Music");
personVect.add(personalData);

personalData = new Person();
personalData.setId(3);
personalData.setName("Ekrem");
personalData.setLast("CANBEK");
personalData.setHobby("Violin");
personVect.add(personalData);

personalData = new Person();
personalData.setId(4);
personalData.setName("Turan");
personalData.setLast("MUTLUAY");
personalData.setHobby("Choir");
personVect.add(personalData);

personalData = new Person();
personalData.setId(5);
personalData.setName("Rengin");
personalData.setLast("AHISKALI");
personalData.setHobby("Literature");
personVect.add(personalData);

personNextId = 6;
personCurrentId = 5;

System.out.println("ARSmsg: personVect.ser does not exist. A new one is created.");
return personVect;
//throw new PersonDAOSysException("\\DAOException:" + ex.getMessage() + " " + ex.toString());
} catch (ClassNotFoundException ex) {
throw new PersonDAOSysException("\\DAOException:" + ex.getMessage() + " " + ex.toString());
}
}

private void closeDBConnection() throws PersonDAOSysException {
String filename = "personVect.ser";

FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(personVect);
out.close();
} catch (IOException ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
}
}

public Vector getPersonVect() {
return personVect;
}

public void addPerson(Person personalData) {
personVect.add(personalData);
personNextId++;
}

public int getPersonNextId() {
return personNextId;
}

public int getPersonCurrentId() {
return personCurrentId;
}
}

CRUD with Serial Persistence - 2

This is the second part of CRUD with Serial Persistence Tutorial.
To have an idea of what a CRUD is please refer to the 'Simple
CRUD Tutorial' example on which you can find extensive information
in this blog. You can also find information about DAO (Data
Access Objects) in this blog under the title 'Simple DAO
Tutorial'.

This part will explain a DAO example with serialization and provide
the code for it. This serialization DAO example is built upon
the VectorDAO example in the 'Simple DAO Tutorial'.

In order to make a class serializable you must make all the classes
used by it serializable hence:

Person.java
-----------

package mainPackage;

/**
*
* @author Ali Riza SARAL
*/
import java.io.Serializable;

public class Person implements Serializable {

private String name;
private String last;
private String hobby;
private int id;

public Person(){}
public Person(int id, String name, String last, String hobby){
this.name = name;
this.last = last;
this.hobby = hobby;
this.id = id;
}
public String getName() {
return this.name;
}

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

public String getLast() {
return this.last;
}

public void setLast(String last) {
this.last = last;
}

public String getHobby() {
return this.hobby;
}

public void setHobby(String hobby) {
this.hobby = hobby;
}

public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}
}


The PersonDAO.java interface definition of the
PersonDAO does not change.

PersonDAO.java
--------------
package daoPackage;

import java.util.Collection;
import mainPackage.*;

public interface PersonDAO {

public void createRec(String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public Person readRec(int personId)
throws PersonDAOSysException;

public void updateRec(int id, String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public void deleteRec(int personId)
throws PersonDAOSysException;

public boolean findByPrimaryKey(int personId)
throws PersonDAOSysException;

public Collection findByLastName(String lastName)
throws PersonDAOSysException;

public int findTotalNumberOfPersons()
throws PersonDAOSysException;
}




and also

PersonDAOSysException.java
--------------------------
package daoPackage;

public class PersonDAOSysException extends RuntimeException {
public PersonDAOSysException (String str) {
super(str);
}
public PersonDAOSysException () {
super();
}
}




the driver program that tests the DAO is:

drivePersonDAOserialVector.java
-------------------------------

import mainPackage.*;
import daoPackage.*;

/**
*
* @author Ali Riza SARAL
*/
public class drivePersonDAOserialVector {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PersonDAOVectorImpl personDAO;
String nameVal = "", lastVal = "", hobbyVal = "", idVal = "";

personDAO = new PersonDAOVectorImpl();

Person person = personDAO.readRec(3);
nameVal = person.getName();
lastVal = person.getLast();
hobbyVal = person.getHobby();
idVal = String.valueOf(person.getId());

System.out.println(
"-------\nName:" + nameVal +
"LastName:" + lastVal +
"Hobby:" + hobbyVal +
"Id:" + idVal);

// personDAO.createRec("Ali", "KIDIK", "gazetecilik");
// personDAO.findByPrimaryKey(1);
// personDAO.findByLastName("SARAL");
// personDAO.findTotalNumberOfPersons();
// personDAO.updateRec(8, "TURAN", "xxx", "qqq");

// personDAO.readRec(4);
// personDAO.readPrevRec();
// personDAO.readNextRec();
// personDAO.readNextRec();
// personDAO.readNextRec();
// personDAO.readNextRec();
// personDAO.readNextRec();
// personDAO.readNextRec();
personDAO.readRec(1);
// personDAO.readPrevRec();
// personDAO.readPrevRec();
// personDAO.readPrevRec();
// personDAO.readPrevRec();
// personDAO.readPrevRec();
// personDAO.readPrevRec();
// personDAO.readPrevRec();
personDAO.deleteRec(4);
personDAO.dumpVect();

}
}

Please note that the serialization file personVect.ser is created in
C:\Program Files\glassfish-3.0.1\glassfish\domains\domain1
because I have not given any absolute address.

CRUD with Serial Persistence - 1

This is CRUD tutorial implemented using Serialization of a Vector
as a Data Container. I will get to this end via a couple of steps.

1- A very simple serialization example.
2- A 'Simple CRUD Tutorial' example on which you can find
extensive information in this blog.
3- A DAO example which uses serialization. You can find detailed
information on this DAO in this blog under the title 'Simple DAO
Tutorial'.
4- A combination of all three examples as 'CRUD with Serial
Persistence'.



1- A very simple serialization example.

PersistentData is the object that will be serialized in
"dataARS.ser".

PersistentData.java
-------------------
package serializeDemoARS;

import serializears.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Calendar;

public class PersistentData implements Serializable {

private int numAccumulator = 0;

public PersistentData() {
numAccumulator++;
}

public int getData() {
return numAccumulator;
}

public void setData(int num) {
numAccumulator = num;
}
}




You have to run the createData once to create the
"dataARS.ser" file.

createData.java
---------------
package serializeDemoARS;

import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class createData {

public static void main(String[] args) {
String filename = "dataARS.ser";

PersistentData data = new PersistentData();

System.out.println("Updated Value of PersistentData=" + data.getData());

FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(data);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public static int retrieveData() {
String filename = "dataARS.ser";

PersistentData data = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
data = (PersistentData) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// print out restored data
System.out.println("Current value of PersistentData=" + data.getData());
return data.getData();
}
}

Once you have created the "dataARS.ser" you can update it
as many times as you like. At each runing of the update program
it reads the serialized object and recreates an instance
of it. Then you increment the data and reserialize - namely
you write data object back to "dataARS.ser" as seen below.

updateData.java
---------------

package serializeDemoARS;

import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class updateData {

public static void main(String[] args) {
System.out.println("Beginning of NEW program");
String filename = "dataARS.ser";

int currentData = retrieveData();
currentData++;

PersistentData data = new PersistentData();
data.setData(currentData);
System.out.println("Updated Value of PersistentData=" + data.getData());

FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(data);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("End of program");
}

public static int retrieveData() {
String filename = "dataARS.ser";

PersistentData data = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
data = (PersistentData) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// print out restored data
System.out.println("Current value of PersistentData=" + data.getData());
return data.getData();
}
}

Wednesday 26 January 2011

Simple DAO Tutorial - 4

This is the 4th part of the Simple DAO Tutorial. Here the DAO is implemented using MySQL DB.


PersonDAOMySQLDBImpl.java
-------------------------
package daoPackage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import javax.naming.*;
import java.sql.*;
import javax.sql.*;
import mainPackage.*;

public class PersonDAOMySQLDBImpl implements PersonDAO {

private Connection conn;
private static int personNextId = 1;
private static int personCurrentId = 1;

public PersonDAOMySQLDBImpl() throws Exception {
System.out.println("ARSmsg: PersonDAOMySQLImpl constructor began-----------.");
getDBConnection();

try {
update("DROP TABLE IF EXISTS persontab ");
// db will automatically generate unique values for the id column
update(
"CREATE TABLE persontab("
+ "id INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),"
+ "firstname VARCHAR(20),"
+ "lastname VARCHAR(20), "
+ "hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}

try {
update(
"INSERT INTO persontab(firstname,lastname,hobby) VALUES('Ali Riza', 'SARAL', 'Music Composition')");
update(
"INSERT INTO persontab(firstname,lastname,hobby) VALUES('Tamer', 'ÜNAL', 'Folk Music')");
update(
"INSERT INTO persontab(firstname,lastname,hobby) VALUES('Ekrem', 'CANBEK', 'Violin')");
update(
"INSERT INTO persontab(firstName,lastName,hobby) VALUES('Turan', 'MUTLUAY', 'Choir')");
update(
"INSERT INTO persontab(firstName,lastName,hobby) VALUES('Rengin', 'AHISKALI', 'Literature')");
// do a query
query("SELECT * FROM persontab");

shutdown();
} catch (SQLException ex3) {
ex3.printStackTrace();
}
}

public void createRec(int id, String firstName,
String lastName, String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: createRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("insert into personTab(id, firstName, lastName,"
+ " hobby) values (?, ?, ?, ?)");
stmt.setString(1, String.valueOf(id));
stmt.setString(2, firstName);
stmt.setString(3, lastName);
stmt.setString(4, hobby);
stmt.executeUpdate();
personCurrentId = personNextId;
personNextId++;
query("SELECT * FROM personTab");
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

public void deleteRec(int studentId) throws PersonDAOSysException {
System.out.println("ARSmsg: deleteRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("delete from personTab where id = ?");
stmt.setString(1, String.valueOf(studentId));
stmt.executeUpdate();
stmt.close();
query("SELECT * FROM personTab");
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
reorganiseDB();
}

public boolean findByPrimaryKey(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: findByPrimaryKey began-----------.");
boolean result = false;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("select id from personTab where id = ?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
result = rs.next();
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException: " + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return result;
}

public Collection findByLastName(String lastName) throws PersonDAOSysException {
System.out.println("ARSmsg: findByLastName began-----------.");
Collection persons = new ArrayList();
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("select id from personTab where lastName = ?");
stmt.setString(1, lastName);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String personId = rs.getString(1);
persons.add(personId);
}
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException: " + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
System.out.println("FindByLastName id="+persons.toString());
return persons;
}

public int findTotalNumberOfPersons() throws PersonDAOSysException {
//System.out.println("ARSmsg: findTotalNumberOfPersons began-----------.");
int total = 0;
PreparedStatement stmt = null;
try {
getDBConnection();
stmt = conn.prepareStatement("select count(id) from personTab");
ResultSet rs = stmt.executeQuery();
rs.next();
total = rs.getInt(1);
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
System.out.println("ARSmsg: findTotalNumberOfPersons ="+total);
return total;
}

public Person readRec(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: readRec began-----------.");
Person person = null;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public Person readNextRec() throws PersonDAOSysException {
System.out.println("ARSmsg: readNextRec began-----------.");
Person person = null;
PreparedStatement stmt = null;
personCurrentId++;
int personId = personCurrentId;

try {
getDBConnection();
stmt = conn.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public Person readPrevRec() throws PersonDAOSysException {
System.out.println("ARSmsg: readPrevRec began-----------.");
Person person = null;
PreparedStatement stmt = null;
personCurrentId--;
int personId = personCurrentId;

try {
getDBConnection();
stmt = conn.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public void updateRec(int id, String firstName, String lastName,
String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: updateRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("update personTab set "
+ "firstName=?,lastName = ?,hobby = ? where id=?");
stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setString(3, hobby);
stmt.setString(4, String.valueOf(id));
stmt.executeUpdate();
stmt.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

private void reorganiseDB() {
System.out.println("ARSmsg: reorganiseDB began-----------.");
Person person;

getDBConnection();

try {
update("DROP TABLE IF EXISTS persontabtemp");
update("CREATE TABLE persontabtemp ("
+ "id INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),"
+ "firstname VARCHAR(20), "
+ "lastname VARCHAR(20), "
+ "hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}
closeDBConnection();

int recCount = findTotalNumberOfPersons();

for (int i = 1, j = 1; j < recCount+1; i++) {

if (findByPrimaryKey(i)) {
//System.out.println(i+" exists");
person = readRec(i);
createRecTemp(j,person.getName(), person.getLast(), person.getHobby());
j++;
} else {
System.out.println(i + " does not exist");
}
}

getDBConnection();

try {
update("DROP TABLE IF EXISTS persontab ");
update( "CREATE TABLE persontab("
+ "id INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),"
+ "firstname VARCHAR(20),"
+ "lastname VARCHAR(20), "
+ "hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}
closeDBConnection();

int recCountTemp = findTotalNumberOfPersonsTemp();

for (int i = 1; i < recCountTemp + 1; i++) {
person = readRecTemp(i);
createRec(i, person.getName(), person.getLast(), person.getHobby());
}
}

public void createRecTemp(int id, String firstName,
String lastName, String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: createRecTemp began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("insert into persontabtemp(id, firstName, lastName,"
+ " hobby) values (?, ?, ?, ?)");
stmt.setString(1, String.valueOf(id));
stmt.setString(2, firstName);
stmt.setString(3, lastName);
stmt.setString(4, hobby);
stmt.executeUpdate();
personCurrentId = personNextId;
personNextId++;
query("SELECT * FROM persontabtemp");
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

public int findTotalNumberOfPersonsTemp() throws PersonDAOSysException {
System.out.println("ARSmsg: findTotalNumberOfPersonsTemp began-----------.");
int total = 111;
PreparedStatement stmt = null;
try {
getDBConnection();
stmt = conn.prepareStatement("select count(id) from persontabtemp");
ResultSet rs = stmt.executeQuery();
rs.next();
total = rs.getInt(1);
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return total;
}

public Person readRecTemp(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: readRecTemp began-----------.");
Person person = null;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = conn.prepareStatement("select firstName, lastName, "
+ " hobby from persontabtemp where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

private void getDBConnection() throws PersonDAOSysException {
//System.out.println("ARSmsg: getDBConnection began-----------.");
String url = "jdbc:mysql://localhost:3306/";
String dbName = "persondao";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "3391309";

try {
Properties props = new Properties();
String curDir = System.getProperty("user.dir");
//System.out.println("curDir=" + curDir);
FileInputStream fis = new FileInputStream(curDir + "/PersonDAOARS.properties");
props.load(fis);
fis.close();

url = props.getProperty("MySQLurl");
dbName = props.getProperty("MySQLdbName");
driver = props.getProperty("MySQLdriver");
userName = props.getProperty("MySQLuserName");
password = props.getProperty("MySQLpassword");
} catch (FileNotFoundException e) {
throw new PersonDAOSysException("\\FileNotFoundException:" + e.getMessage() + " " + e.toString());
} catch (java.io.IOException e) {
throw new PersonDAOSysException("\\java.io.IOException:" + e.getMessage() + " " + e.toString());
}

try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
//System.out.println("Connected to the database");
//conn.close();
//System.out.println("Disconnected from database");
} catch (Exception ex) {
throw new PersonDAOSysException("\\nSQLException:" + ex.getMessage() + " " + ex.toString());
}
}

private void closeDBConnection() throws PersonDAOSysException {
//System.out.println("ARSmsg: closeDBConnection began-----------.");
try {
conn.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
}
}

private void closeStatement(PreparedStatement stmt) throws PersonDAOSysException {
//System.out.println("ARSmsg: closeStatement began-----------.");
try {
stmt.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
}
}

public synchronized void update(String expression) throws SQLException {
//for CREATE, DROP, INSERT and UPDATE
System.out.println("ARSmsg: update began-----------.");
Statement st = null;

st = conn.createStatement(); // statements

int i = st.executeUpdate(expression); // run the query

if (i == -1) {
System.out.println("db error : " + expression);
}
st.close();
}

public synchronized void query(String expression) throws SQLException {
//for SELECT
System.out.println("ARSmsg: query began-----------.");
Statement st = null;
ResultSet rs = null;

st = conn.createStatement();
rs = st.executeQuery(expression);

dump(rs);
st.close();
}

public static void dump(ResultSet rs) throws SQLException {
System.out.println("ARSmsg: dump began-----------.");
ResultSetMetaData meta = rs.getMetaData();
int colmax = meta.getColumnCount();
int i;
Object o = null;

for (; rs.next();) {
for (i = 0; i < colmax; ++i) {
o = rs.getObject(i + 1);
System.out.print(o.toString() + " ");
}
System.out.println(" ");
}
System.out.println();
}

public void shutdown() throws SQLException {
System.out.println("ARSmsg: shutdown began-----------.");
Statement st = conn.createStatement();

st.execute("FLUSH TABLES"); //write out buffersand clean shut down
conn.close(); // if there are no other open connection
}
}

Simple DAO Tutorial - 3

This is the 3rd part of the Simple DAO Tutorial. Here he Dao is implemented using HSQLDB.


PersonDAOHSQLDBImpl.java
------------------------
package daoPackage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import javax.naming.*;
import java.sql.*;
import javax.sql.*;
import mainPackage.*;

public class PersonDAOHSQLDBImpl implements PersonDAO {

private Connection con;
private static int personNextId = 1;
private static int personCurrentId = 1;

public PersonDAOHSQLDBImpl() throws Exception {
System.out.println("ARSmsg: PersonDAOHSQLDBImpl constructor began-----------.");
getDBConnection();

try {
update("DROP TABLE personTab IF EXISTS");
// db will automatically generate unique values for the id column
update(
"CREATE TABLE personTab ( id INTEGER IDENTITY, firstName VARCHAR(20), lastName VARCHAR(20), hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}

try {
update(
"INSERT INTO personTab(firstName,lastName,hobby) VALUES('Ali Riza', 'SARAL', 'Music Composition')");
update(
"INSERT INTO personTab(firstName,lastName,hobby) VALUES('Tamer', 'ÜNAL', 'Folk Music')");
update(
"INSERT INTO personTab(firstName,lastName,hobby) VALUES('Ekrem', 'CANBEK', 'Violin')");
update(
"INSERT INTO personTab(firstName,lastName,hobby) VALUES('Turan', 'MUTLUAY', 'Choir')");
update(
"INSERT INTO personTab(firstName,lastName,hobby) VALUES('Rengin', 'AHISKALI', 'Literature')");
// do a query
query("SELECT * FROM personTab");

shutdown();
} catch (SQLException ex3) {
ex3.printStackTrace();
}
}

public void createRec(int id, String firstName,
String lastName, String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: createRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("insert into personTab(id, firstName, lastName,"
+ " hobby) values (?, ?, ?, ?)");
stmt.setString(1, String.valueOf(id));
stmt.setString(2, firstName);
stmt.setString(3, lastName);
stmt.setString(4, hobby);
stmt.executeUpdate();
personCurrentId = personNextId;
personNextId++;
query("SELECT * FROM personTab");
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

public void deleteRec(int studentId) throws PersonDAOSysException {
System.out.println("ARSmsg: deleteRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("delete from personTab where id = ?");
stmt.setString(1, String.valueOf(studentId));
stmt.executeUpdate();
stmt.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
reorganiseDB();
}

public boolean findByPrimaryKey(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: findByPrimaryKey began-----------.");
boolean result = false;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("select id from personTab where id = ?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
result = rs.next();
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException: " + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return result;
}

public Collection findByLastName(String lastName) throws PersonDAOSysException {
System.out.println("ARSmsg: findByLastName began-----------.");
Collection persons = new ArrayList();
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("select id from personTab where lastName = ?");
stmt.setString(1, lastName);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String personId = rs.getString(1);
persons.add(personId);
}
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException: " + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
System.out.println(persons.toString());
return persons;
}

public int findTotalNumberOfPersons() throws PersonDAOSysException {
System.out.println("ARSmsg: findTotalNumberOfPersons began-----------.");
int total = 111;
PreparedStatement stmt = null;
try {
getDBConnection();
stmt = con.prepareStatement("select count(id) from personTab");
ResultSet rs = stmt.executeQuery();
rs.next();
total = rs.getInt(1);
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return total;
}

public Person readRec(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: readRec began-----------.");
Person person = null;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public Person readNextRec() throws PersonDAOSysException {
System.out.println("ARSmsg: readNextRec began-----------.");
Person person = null;
PreparedStatement stmt = null;
personCurrentId++;
int personId = personCurrentId;

try {
getDBConnection();
stmt = con.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public Person readPrevRec() throws PersonDAOSysException {
System.out.println("ARSmsg: readPrevRec began-----------.");
Person person = null;
PreparedStatement stmt = null;
personCurrentId--;
int personId = personCurrentId;

try {
getDBConnection();
stmt = con.prepareStatement("select firstName, lastName, "
+ " hobby from personTab where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

public void updateRec(int id, String firstName, String lastName,
String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: updateRec began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("update personTab set "
+ "firstName=?,lastName = ?,hobby = ? where id=?");
stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setString(3, hobby);
stmt.setString(4, String.valueOf(id));
stmt.executeUpdate();
stmt.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

private void reorganiseDB() {
System.out.println("ARSmsg: reorganiseDB began-----------.");
Person person;

getDBConnection();

try {
update("DROP TABLE personTabTemp IF EXISTS");
update("CREATE TABLE personTabTemp ( "
+ "id INTEGER IDENTITY, "
+ "firstName VARCHAR(20), "
+ "lastName VARCHAR(20), "
+ "hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}
closeDBConnection();

int recCount = findTotalNumberOfPersons();

for (int i = 0, j = 0; j < recCount; i++) {

if (findByPrimaryKey(i)) {
//System.out.println(i+" exists");
person = readRec(i);
createRecTemp(j, person.getName(), person.getLast(), person.getHobby());
j++;
} else {
System.out.println(i + " does not exist");
}
}

getDBConnection();

try {
update("DROP TABLE personTab IF EXISTS");
update("CREATE TABLE personTab ( "
+ "id INTEGER IDENTITY, "
+ "firstName VARCHAR(20), "
+ "lastName VARCHAR(20), "
+ "hobby VARCHAR(30))");
} catch (SQLException e) {
//ignore exception the second time if we create the same table
}
closeDBConnection();

int recCountTemp = findTotalNumberOfPersonsTemp();

for (int i = 0; i < recCountTemp; i++) {
person = readRecTemp(i);
createRec(i, person.getName(), person.getLast(), person.getHobby());
}
}

public void createRecTemp(int id, String firstName,
String lastName, String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg: createRecTemp began-----------.");
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("insert into personTabTemp(id, firstName, lastName,"
+ " hobby) values (?, ?, ?, ?)");
stmt.setString(1, String.valueOf(id));
stmt.setString(2, firstName);
stmt.setString(3, lastName);
stmt.setString(4, hobby);
stmt.executeUpdate();
personCurrentId = personNextId;
personNextId++;
query("SELECT * FROM personTabTemp");
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
}

public int findTotalNumberOfPersonsTemp() throws PersonDAOSysException {
System.out.println("ARSmsg: findTotalNumberOfPersonsTemp began-----------.");
int total = 111;
PreparedStatement stmt = null;
try {
getDBConnection();
stmt = con.prepareStatement("select count(id) from personTabTemp");
ResultSet rs = stmt.executeQuery();
rs.next();
total = rs.getInt(1);
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return total;
}

public Person readRecTemp(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg: readRecTemp began-----------.");
Person person = null;
PreparedStatement stmt = null;

try {
getDBConnection();
stmt = con.prepareStatement("select firstName, lastName, "
+ " hobby from personTabTemp where id=?");
stmt.setString(1, String.valueOf(personId));
ResultSet rs = stmt.executeQuery();
rs.next();

person = new Person(personId,
rs.getString(1),
rs.getString(2),
rs.getString(3));
System.out.print(personId + " ");
System.out.print(rs.getString(1) + " ");
System.out.print(rs.getString(2) + " ");
System.out.println(rs.getString(3) + "\n");
rs.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
} finally {
closeStatement(stmt);
closeDBConnection();
}
return person;
}

private void getDBConnection() throws PersonDAOSysException {
//System.out.println("ARSmsg: getDBConnection began-----------.");
String driverClassName = "";
String db_file_name_prefix = "";

try {
Properties props = new Properties();
String curDir = System.getProperty("user.dir");
//System.out.println("curDir=" + curDir);
FileInputStream fis = new FileInputStream(curDir + "/PersonDAOARS.properties");
props.load(fis);
fis.close();

driverClassName = props.getProperty("driverName");
//System.out.println("driverClassName=" + driverClassName);
db_file_name_prefix = props.getProperty("dbFileNamePrefix");
} catch (FileNotFoundException e) {
throw new PersonDAOSysException("\\FileNotFoundException:" + e.getMessage() + " " + e.toString());
} catch (java.io.IOException e) {
throw new PersonDAOSysException("\\java.io.IOException:" + e.getMessage() + " " + e.toString());
}

try {
Class.forName(driverClassName); //org.hsqldb.jdbcDriver

con = DriverManager.getConnection("jdbc:hsqldb:"
+ db_file_name_prefix, // filenames
"sa", // username
""); // password
} catch (SQLException ex) {
throw new PersonDAOSysException("\\nSQLException:" + ex.getMessage() + " " + ex.toString());
} catch (java.lang.ClassNotFoundException ex) {
throw new PersonDAOSysException("\\nClassNotFoundException:" + ex.getMessage() + " " + ex.toString());
}
}

private void closeDBConnection() throws PersonDAOSysException {
//System.out.println("ARSmsg: closeDBConnection began-----------.");
try {
con.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
}
}

private void closeStatement(PreparedStatement stmt) throws PersonDAOSysException {
//System.out.println("ARSmsg: closeStatement began-----------.");
try {
stmt.close();
} catch (SQLException ex) {
throw new PersonDAOSysException("SQLException:" + ex.getMessage());
}
}

public synchronized void update(String expression) throws SQLException {
//for CREATE, DROP, INSERT and UPDATE
System.out.println("ARSmsg: update began-----------.");
Statement st = null;

st = con.createStatement(); // statements

int i = st.executeUpdate(expression); // run the query

if (i == -1) {
System.out.println("db error : " + expression);
}
st.close();
}

public synchronized void query(String expression) throws SQLException {
//for SELECT
System.out.println("ARSmsg: query began-----------.");
Statement st = null;
ResultSet rs = null;

st = con.createStatement();
rs = st.executeQuery(expression);

dump(rs);
st.close();
}

public static void dump(ResultSet rs) throws SQLException {
System.out.println("ARSmsg: dump began-----------.");
ResultSetMetaData meta = rs.getMetaData();
int colmax = meta.getColumnCount();
int i;
Object o = null;

for (; rs.next();) {
for (i = 0; i < colmax; ++i) {
o = rs.getObject(i + 1);
System.out.print(o.toString() + " ");
}
System.out.println(" ");
}
System.out.println();
}

public void shutdown() throws SQLException {
System.out.println("ARSmsg: shutdown began-----------.");
Statement st = con.createStatement();

st.execute("SHUTDOWN"); //write out buffersand clean shut down
con.close(); // if there are no other open connection
}
}