Monday, October 30, 2006

JPA outside EJB3 Container in TomCat 5.5



Web Application described bellow uses JSF for presentation layer,
methods for data management are encapsulated into JSF Managed
Beans and utilize JPA invokes Entity Manager. Persistence
layer is done with entity beans (Toplink Essentials).
Writing code for DataBean.java and JSF pages we follow Gordon Yorke (view [1]).
Basic explanation how to create entity beans for database tables (persistence layer) may be found in [1],[2],[3].

Main screen displays Dept table from scott’s schema. For each department "Employee" button displays records of all employees for selected department on the next page. Every employee record may be edited (including java.sql.Date type field "hiredate") or removed from scott.emp table.Button "Create new employee" inserts a new employee record for department been selected on the starting page . Button "Back to Departments" forwards back to starting page.


Web Application files layout:-




List of JSF pages:
***************************
File /department.jsp:-
***************************



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK ESSENTIALS IN TOMCAT 5.5.X</TH></TR>
</TABLE>
<H3>Displaying Dept table from scott's schema</H3>
<h:form>
<h:dataTable value="#{dataBean.depts}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Depatment"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.dname}"/>
<f:facet name="header">
<h:outputText value="Department name"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.loc}"/>
<f:facet name="header">
<h:outputText value="Location"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:commandButton value="employee"
type="submit"
actionListener="#{dataBean.empSelected}"
action="toEmp">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.deptno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
<h:message id="errorTag" for="errorTag" showDetail="true"/>
</CENTER></BODY></HTML>
</f:view>




**************************
File /employee.jsp:-
**************************



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK ESSENTIALS IN TOMCAT 5.5.X</TH></TR>
</TABLE>
<H3>Displaying employees records for department selected </H3>
<h:form>
<h:dataTable value="#{dataBean.empForDept}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.empno}"/>
<f:facet name="header">
<h:outputText value="Number"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.ename}"/>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
</h:column>
<h:column>
<f:verbatim>$</f:verbatim>
<h:outputText value="#{rowVar.sal}"/>
<f:facet name="header">
<h:outputText value="Salary"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.mgr}"/>
<f:facet name="header">
<h:outputText value="Manager ID"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.hiredate}"/>
<f:facet name="header">
<h:outputText value="Date of hire"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Department"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:commandButton value="Update"
type="submit"
actionListener="#{dataBean.empUpdate}"
action="toEntry">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Remove"/>
</f:facet>
<h:commandButton value="Remove"
type="submit"
actionListener="#{dataBean.empRemove}"
action="erase">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.empno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
<f:verbatim>
<hr/>
</f:verbatim>
<h:panelGroup style="vertical-align:middle;">
<h:commandButton value="Create New Employee"
type="submit"
actionListener="#{dataBean.createNewEmpAct}"
action="toEntry"/>
<h:outputText value=" "/>
<h:commandButton value="Back to Departments"
action="Back"/>
</h:panelGroup>
<f:verbatim>
<hr/>
</f:verbatim>
<h:outputText value="#{dataBean.empModificationResult}"/>
</h:form>
</CENTER></BODY></HTML>
</f:view>




**************************
File /entryEmp.jsp:-
**************************



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1252"/>
<title>Product</title>
</head>
<body>
<h:form>
<h:panelGrid columns="1" style="text-align:center;">
<h:panelGrid columns="2">
<h:outputText value="Employee Number"/>
<h:inputText value="#{dataBean.currentEmp.empno}"/>
<h:outputText value="Employee Name"/>
<h:inputText value="#{dataBean.currentEmp.ename}"/>
<h:outputText value="Employee MGR"/>
<h:inputText value="#{dataBean.currentEmp.mgr}"/>
<h:outputText value="Hire Date"/>
<h:inputText value="#{dataBean.hrString}"/>
<h:outputText value="Salary"/>
<h:inputText value="#{dataBean.currentEmp.sal}"/>
</h:panelGrid>
<f:verbatim>
<hr/>
</f:verbatim>
<h:panelGroup>
<h:commandButton value="#{dataBean.empEntryOperation}"
action="result"
actionListener="#{dataBean.completeEmpUpdate}"
style="text-align:center;"/>
<h:commandButton value="Cancel"
action="cancel"
style="text-align:center;"/>
</h:panelGroup>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>




******************************************
File ./WEB-INF/classes/DataBean.java
******************************************



package dstu.net;

import javax.persistence.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;
import java.util.Collection;
import javax.persistence.Query;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.lang.Exception;



import dstu.net.Emp;
import dstu.net.Dept;

public class DataBean {

protected int departId;

protected dstu.net.Emp currentEmp;
protected JPAResourceBean jpaResourceBean;
protected static final String UPDATE_OPERATION = "Update";
protected static final String CREATE_OPERATION = "Create";
protected String empEntryOperation;
protected String empModificationResult;
protected static final String SUCCESS = "Success";
protected String hrString ;
protected java.sql.Date hrDate;


public DataBean() {}

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");


public dstu.net.Emp[] getEmps(){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectEmps").getResultList();
return(tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]));
} finally { em.close();}
}


public dstu.net.Dept[] getDepts(){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectDepts").getResultList();
return(tempCollection.toArray(new dstu.net.Dept[tempCollection.size()]));
} finally { em.close();}
}

public void empSelected(ActionEvent actionEvent) {
this.departId =
((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
setEmpModificationResult(" ");
}

public dstu.net.Emp[] getEmpForDept(){
try {
Collection tempCollection = getEmpForDepartment(this.departId);
return tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]);
} catch (RuntimeException ex){
handleException(ex);
}
return new dstu.net.Emp[0];
}

public Collection getEmpForDepartment(int deptId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
Query query = em.createNamedQuery("empForDepartment");
query.setParameter("deptId", deptId);
return query.getResultList();
} finally { em.close();}
}


public void empUpdate(ActionEvent actionEvent){
Integer empId = ((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
try {
this.currentEmp = getEmpById(empId);
// Converting java.sql.Date to String for editing.
hrString=sdf.format(this.currentEmp.hiredate);
this.empEntryOperation = UPDATE_OPERATION;
} catch (RuntimeException ex) { handleException(ex); }
}

public dstu.net.Emp getEmpById(int empId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
return em.find(dstu.net.Emp.class, empId);
}finally{
em.close();
}
}

public void empRemove(ActionEvent actionEvent){
Integer empId = ((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
try {
requestEmpRemove(empId);
this.empModificationResult = "Success";
}catch (OptimisticLockException ex){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "Employee status has changed since last viewed";
}catch (Exception ex){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "An unexpected Error ocurred: " +ex.toString();
}
}


public void requestEmpRemove(int empId){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
dstu.net.Emp employee = em.find(dstu.net.Emp.class, empId);
em.remove(employee);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void updateEmployee (int empId,String newName,int newMgr, long newSalary,Date newDate){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
dstu.net.Emp employee = em.find(dstu.net.Emp.class, empId);
employee.setEname(newName);
employee.setMgr(newMgr);
employee.setSal(newSalary);
employee.setHiredate(newDate);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void createNewEmpAct(ActionEvent actionEvent){
try {
setHrString(" ");
this.currentEmp = new dstu.net.Emp();
this.currentEmp.setDeptno(this.departId);
this.empEntryOperation = CREATE_OPERATION;
} catch (RuntimeException ex) { handleException(ex);}

}


public void completeEmpUpdate(ActionEvent actionEvent) {

try {
// Converting string to java.sql.Date
java.util.Date parsedDate = sdf.parse(hrString);
this.currentEmp.setHiredate(new java.sql.Date(parsedDate.getTime()));
}
catch (Exception err) { }

try{

if (this.empEntryOperation == this.UPDATE_OPERATION){

updateEmployee(this.currentEmp.getEmpno(),this.currentEmp.getEname(),this.currentEmp.getMgr(),this.currentEmp.getSal(), this.currentEmp.getHiredate());

} else {

createNewEmp(this.currentEmp);

}

this.empModificationResult = SUCCESS;

}catch (RollbackException ex){
if (ex.getCause() instanceof OptimisticLockException){
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + "Employee status has changed since last viewed";
} else {
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + " An unexpected Error ocurred: " +ex.toString();
}
} catch (Exception ex) {
this.empModificationResult = "Failed to " + this.empEntryOperation.toLowerCase() + " An unexpected Error ocurred: " +ex.toString();
}
}

public void createNewEmp(dstu.net.Emp emp){
EntityManager em = jpaResourceBean.getEMF().createEntityManager();
try{
em.getTransaction().begin();
em.persist(emp);
em.getTransaction().commit();
}finally{
em.close();
}
}


public void setCurrentEmp(Emp currentEmp) {
this.currentEmp = currentEmp;
}

public Emp getCurrentEmp() {
return currentEmp;
}

public void setDepartId(int departId) {
this.departId = departId;
}

public int getDepartId() {
return departId;
}

public void setHrString(String hrString) {
this.hrString=hrString;
}

public String getHrString() {
return(hrString);
}

public void setEmpEntryOperation(String empEntryOperation) {
this.empEntryOperation = empEntryOperation;
}

public String getEmpEntryOperation() {
return empEntryOperation;
}

public void setEmpModificationResult(String empModificationResult) {
this.empModificationResult = empModificationResult;
}

public String getEmpModificationResult() {
return empModificationResult;
}

public void setJpaResourceBean(JPAResourceBean jpaResourceBean) {
this.jpaResourceBean = jpaResourceBean;
}

public JPAResourceBean getJpaResourceBean() {
return jpaResourceBean;
}

//This method is used to handle exceptions and display cause to user.
protected void handleException (RuntimeException ex){
StringBuffer details = new StringBuffer();
Throwable causes = ex;
while(causes.getCause() != null){
details.append(ex.getMessage());
details.append(" Caused by:");
details.append(causes.getCause().getMessage());
causes = causes.getCause();
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), details.toString());
FacesContext.getCurrentInstance().addMessage("errorTag", message);
}
}


*******************************************************************************
File ./WEB-INF/classes/JPAResourceBean.java (author Gordon Yorke)
*******************************************************************************



package dstu.net;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
* This is an Application Scoped bean that holds the JPA
* EntityManagerFactory. By making this bean Applciation scoped the
* EntityManagerFactory resource will be created only once for the application
* and cached here.
*
*@author Gordon Yorke
*/
public class JPAResourceBean {
protected EntityManagerFactory emf;
public EntityManagerFactory getEMF (){
if (emf == null){
emf = Persistence.createEntityManagerFactory("default",new java.util.HashMap());
}
return emf;
}
}




*************************************
File ./WEB-INF/classes/Emp.java:-
*************************************



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="emp")
@NamedQueries({
@NamedQuery(
name="selectEmps",
query="SELECT i FROM Emp i"
),
@NamedQuery(
name="empForDepartment",
query="SELECT o FROM Emp o WHERE o.deptno = :deptId"
)
})



public class Emp {

@Id
protected int empno;

protected String ename;
protected String job;
protected int mgr;
protected Date hiredate;
protected long sal;
protected long comm;
protected int deptno;

public void setEmpno(int empno) {
this.empno=empno;
}
public int getEmpno() {
return empno;
}

public void setEname(String ename) {
this.ename=ename;
}
public String getEname() {
return ename;
}

public void setJob(String job) {
this.job=job;
}

public String getJob() {
return job;
}

public void setMgr(int mgr) {
this.mgr=mgr;
}
public int getMgr() {
return mgr;
}

public void setHiredate(Date hiredate) {
this.hiredate=hiredate;
}
public Date getHiredate() {
return hiredate;
}

public void setSal(long sal) {
this.sal=sal;
}

public long getSal() {
return sal;
}

public void setComm(long comm) {
this.comm=comm;
}

public long getComm() {
return comm;
}


public void setDeptno(int deptno) {
this.deptno=deptno;
}

public int getDeptno() {
return deptno;
}
}




*************************************
File ./WEB-INF/classes/Dept.java:-
*************************************



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="dept")

@NamedQueries({
@NamedQuery(
name="deptForEmployee",
query="SELECT i FROM Dept i WHERE i.deptno = :deptId"
),

@NamedQuery(
name="selectDepts",
query="SELECT o FROM Dept o "
) })

public class Dept {

@Id
protected int deptno;
protected String dname;
protected String loc;

public void setDeptno(int deptno) {
this.deptno=deptno;
}
public int getDeptno() {
return deptno;
}

public void setDname(String dname) {
this.dname=dname;
}
public String getDname() {
return dname;
}

public void setLoc(String loc) {
this.loc=loc;
}

public String getLoc() {
return loc;
}

}




***********************************
File WEB-INF/faces-config.xml:-
***********************************



<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
<managed-bean>
<managed-bean-name>jpaResourceBean</managed-bean-name>
<managed-bean-class>dstu.net.JPAResourceBean</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope>
</managed-bean>

<managed-bean>
<managed-bean-name>dataBean</managed-bean-name>
<managed-bean-class>
dstu.net.DataBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>jpaResourceBean</property-name>
<value>#{jpaResourceBean}</value>
</managed-property>
</managed-bean>

<navigation-rule>
<from-view-id>/department.jsp</from-view-id>
<navigation-case>
<from-outcome>toEmp</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>Back</from-outcome>
<to-view-id>/department.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>toEntry</from-outcome>
<to-view-id>/entryEmp.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/entryEmp.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/employee.jsp</from-view-id>
<navigation-case>
<from-outcome>erase</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/entryEmp.jsp</from-view-id>
<navigation-case>
<from-outcome>cancel</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>




**********************************************************
File ./WEB-INF/classes/META-INF/persistence.xml
**********************************************************



<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>
oracle.toplink.essentials.PersistenceProvider
</provider>
<class>dstu.net.Emp</class>
<class>dstu.net.Dept</class>
<properties>
<property name="toplink.logging.level" value="FINE"/>
<property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@192.168.0.100:1522:jdevdbs"/>
<property name="toplink.jdbc.password" value="tiger"/>
<property name="toplink.jdbc.user" value="scott"/>
</properties>
</persistence-unit>
</persistence>






*************************
Runtime snapshots:-
*************************















Attempt to violate primary constraint "empno_PK" when inserting record
into table scott.emp will display message:-








In the case of success we get message:




References.


1. OTN JPA Reference
2. Toplink Named Queries in TomCat 5.5 (2)
3.Toplink Named Queries in TomCat 5.5 (1)

Friday, October 27, 2006

More Toplink Named Queries (JPA) in TomCat 5.5



This post follows up:-


Toplink Named Queries (JPA) in TomCat 5.5


****************************************************
Create two entity beans Emp.java and Dept.java
for tables emp and dept from scott's schema.
*****************************************************
First:-



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="emp")
@NamedQueries({
@NamedQuery(
name="selectEmps",
query="SELECT i FROM Emp i"
),
@NamedQuery(
name="empForDepartment",
query="SELECT o FROM Emp o WHERE o.deptno = :deptId"
)
})



public class Emp {

@Id
protected int empno;

protected String ename;
protected String job;
protected int mgr;
protected Date hiredate;
protected long sal;
protected long comm;
protected int deptno;

public void setEmpno(int empno) {
this.empno=empno;
}
public int getEmpno() {
return empno;
}

public void setEname(String ename) {
this.ename=ename;
}
public String getEname() {
return ename;
}

public void setJob(String job) {
this.job=job;
}

public String getJob() {
return job;
}

public void setMgr(int mgr) {
this.mgr=mgr;
}
public int getMgr() {
return mgr;
}

public void setHiredate(Date hiredate) {
this.hiredate=hiredate;
}
public Date getHiredate() {
return hiredate;
}

public void setSal(long sal) {
this.sal=sal;
}

public long getSal() {
return sal;
}

public void setComm(long comm) {
this.comm=comm;
}

public long getComm() {
return comm;
}


public void setDeptno(int deptno) {
this.deptno=deptno;
}

public int getDeptno() {
return deptno;
}
}




*********
Second:-
*********



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.NamedQueries;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@Table(name="dept")

@NamedQueries({
@NamedQuery(
name="deptForEmployee",
query="SELECT i FROM Dept i WHERE i.deptno = :deptId"
),

@NamedQuery(
name="selectDepts",
query="SELECT o FROM Dept o "
) })

public class Dept {

@Id
protected int deptno;
protected String dname;
protected String loc;

public void setDeptno(int deptno) {
this.deptno=deptno;
}
public int getDeptno() {
return deptno;
}

public void setDname(String dname) {
this.dname=dname;
}
public String getDname() {
return dname;
}

public void setLoc(String loc) {
this.loc=loc;
}

public String getLoc() {
return loc;
}

}




************************************************************
Create two JSF pages department.jsp and employee.jsp
************************************************************
First:-



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK NAMED QUERY</TH></TR>
</TABLE>
<H3>Displaying Dept table from scott's schema</H3>
<h:form>
<h:dataTable value="#{dataBean.depts}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Depatment"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.dname}"/>
<f:facet name="header">
<h:outputText value="Department name"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.loc}"/>
<f:facet name="header">
<h:outputText value="Location"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Select"/>
</f:facet>
<h:commandButton value="employee"
type="submit"
actionListener="#{dataBean.empSelected}"
action="toEmp">
<f:facet name="extraParameter">
<f:param name="commandButtonParam"
value="#{rowVar.deptno}"/>
</f:facet>
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
</CENTER></BODY></HTML>
</f:view>




*********
Second:-
*********



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK NAMED QUERY</TH></TR>
</TABLE>
<H3>Displaying Emp's table records of employees from department selected on previous page</H3>
<h:dataTable value="#{dataBean.empForDept}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.empno}"/>
<f:facet name="header">
<h:outputText value="Number"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.ename}"/>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
</h:column>
<h:column>
<f:verbatim>$</f:verbatim>
<h:outputText value="#{rowVar.sal}"/>
<f:facet name="header">
<h:outputText value="Salary"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.hiredate}"/>
<f:facet name="header">
<h:outputText value="Date of hiring"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.deptno}"/>
<f:facet name="header">
<h:outputText value="Department"/>
</f:facet>
</h:column>
</h:dataTable>
</CENTER></BODY></HTML>
</f:view>




********************************************
Now DataBean.java has to handle events:-
********************************************



package dstu.net;


import javax.persistence.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;
import java.util.Collection;
import javax.persistence.Query;

import dstu.net.Emp;
import dstu.net.Dept;

public class DataBean {

protected int departId;

public DataBean() {}

public dstu.net.Emp[] getEmps(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectEmps").getResultList();
return(tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]));
} finally { em.close();}
}


public dstu.net.Dept[] getDepts(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
try {
Collection tempCollection =
em.createNamedQuery("selectDepts").getResultList();
return(tempCollection.toArray(new dstu.net.Dept[tempCollection.size()]));
} finally { em.close();}
}

public void empSelected(ActionEvent actionEvent) {
// Look for directive: actionListener="#{dataBean.empSelected}"
// in department.jsp
this.departId =
((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
}

public dstu.net.Emp[] getEmpForDept(){
Collection tempCollection = getEmpForDepartment(this.departId);
return tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]);
}

public Collection getEmpForDepartment(int deptId){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
try{
Query query = em.createNamedQuery("empForDepartment");
query.setParameter("deptId", deptId);
return query.getResultList();
} finally { em.close();}
}

public void setDepartId(int departId) {
this.departId = departId;
}

public int getDepartId() {
return departId;
}

}




**********************************
File WEB-INF/faces-config.xml
**********************************



<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
<managed-bean>
<managed-bean-name>dataBean</managed-bean-name>
<managed-bean-class>
dstu.net.DataBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/department.jsp</from-view-id>
<navigation-case>
<from-outcome>toEmp</from-outcome>
<to-view-id>/employee.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>




******************************************************
File WEB-INF/classes/META-INF/persistence.xml
******************************************************



<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>
oracle.toplink.essentials.PersistenceProvider
</provider>
<class>dstu.net.Emp</class>
<class>dstu.net.Dept</class>
<properties>
<property name="toplink.logging.level" value="FINE"/>
<property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@192.168.0.100:1522:jdevdbs"/>
<property name="toplink.jdbc.password" value="tiger"/>
<property name="toplink.jdbc.user" value="scott"/>
</properties>
</persistence-unit>
</persistence>




Web Application files layout:-






Runtime snapshots:-





Monday, October 23, 2006

Toplink Named Queries (JPA) in TomCat 5.5



Target of this technical exercise to make implementation
of Toplink Essentials (i.e. JPA outside EJB3 container)
easier for comprehension.Sun JSF RI has been used for this
test.Toplink Essentials jars [1] have been downloaded from OTN
and placed in WEB-INF/lib folder.

Snapshot of Web Application file layout:-




************************
Entity Bean - Emp.java
************************



package dstu.net;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.OneToOne;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.Version;
import java.sql.Date;
import javax.persistence.Table;

@Entity
@NamedQuery(
name="selectEmps",
query="SELECT i FROM Emp i"
)

@Table(name="emp")
public class Emp {

@Id
protected int empno;

protected String ename;
protected String job;
protected int mgr;
protected Date hiredate;
protected long sal;
protected long comm;
protected int deptno;

public void setEmpno(int empno) {
this.empno=empno;
}
public int getEmpno() {
return empno;
}

public void setEname(String ename) {
this.ename=ename;
}
public String getEname() {
return ename;
}

public void setJob(String job) {
this.job=job;
}

public String getJob() {
return job;
}

public void setMgr(int mgr) {
this.mgr=mgr;
}
public int getMgr() {
return mgr;
}

public void setHiredate(Date hiredate) {
this.hiredate=hiredate;
}
public Date getHiredate() {
return hiredate;
}

public void setSal(long sal) {
this.sal=sal;
}

public long getSal() {
return sal;
}

public void setComm(long comm) {
this.comm=comm;
}

public long getComm() {
return comm;
}


public void setDeptno(int deptno) {
this.deptno=deptno;
}

public int getDeptno() {
return deptno;
}
}




****************************************
DataBean.java invokes Entity Manager
and returns collection of "Emp" beans
****************************************



package dstu.net;


import javax.persistence.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import dstu.net.Emp;

public class DataBean {

public DataBean() {}

public dstu.net.Emp[] getEmps(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("default");
EntityManager em = emf.createEntityManager();
try {
Collection<dstu.net.Emp> tempCollection =
em.createNamedQuery("selectEmps").getResultList();
dstu.net.Emp[] emps = tempCollection.toArray(new dstu.net.Emp[tempCollection.size()]);
return(emps);
} finally { em.close();}
}
}




***************************************************
File WEB-INF/clasess/META-INF/persistence.xml:-
***************************************************



<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>
oracle.toplink.essentials.PersistenceProvider
</provider>
<class>dstu.net.Emp</class>
<properties>
<property name="toplink.logging.level" value="FINE"/>
<property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
<property name="toplink.jdbc.url" value="jdbc:oracle:thin:@192.168.0.100:1522:jdevdbs"/>
<property name="toplink.jdbc.password" value="tiger"/>
<property name="toplink.jdbc.user" value="scott"/>
</properties>
</persistence-unit>
</persistence>




*********************************
File WEB-INF/faces-config.xml:-
*********************************



<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
<managed-bean>
<managed-bean-name>dataBean</managed-bean-name>
<managed-bean-class>
dstu.net.DataBean
</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>




*************************************
JSF Page displaying query results:-
*************************************



<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">TOPLINK NAMED QUERY</TH></TR>
</TABLE>
<H3>Displaying Emp table from scott's schema</H3>

<h:dataTable value="#{dataBean.emps}"
var="rowVar"
border="1">
<h:column>
<h:outputText value="#{rowVar.empno}"/>
<f:facet name="header">
<h:outputText value="Number"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.ename}"/>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
</h:column>
<h:column>
<f:verbatim>$</f:verbatim>
<h:outputText value="#{rowVar.sal}"/>
<f:facet name="header">
<h:outputText value="Salary"/>
</f:facet>
</h:column>
<h:column>
<h:outputText value="#{rowVar.hiredate}"/>
<f:facet name="header">
<h:outputText value="Date of hiring"/>
</f:facet>
</h:column>
</h:dataTable>
</CENTER></BODY></HTML>
</f:view>




Runtime image:-




View more complicated Web Application designed with Toplink Essentials


References.
1. http://www.oracle.com/technology/products/ias/toplink/jpa/tutorials/jsf-jpa-tutorial.html

Friday, October 13, 2006


Web Applications designed with Struts 1.2.9 in TomCat 5.5.17



Consider conversion to struts 1.2.9 architecture sample MVC
application bank-suppport (view [2],[1]).
Create directory BankActions129 under deployer folder ([1]) and copy struts-blank.war right there.

Next:-



$ cd *yer/BankActions129
$jar xvf struts-blank.war




Place apps files into subdirectories of BankActions129 as required:-




Convert HttpServlet ShowBalance:-




to Action Servlet with the same name:-




Make required changes to ./WEB-INF/struts-config.xml:-




Make sure ./WEB-INF/web.xml looks like:-




<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
<display-name>Struts Bank Support Sample </display-name>

<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>


<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>


<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-nested</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>

</web-app>




Modify starting JSP and run:-








References.
1. http://librenix.com/?inode=9205
2. Core Servlets and JSP ,Marty Hall,Sun Press 2003
Online version:
http://volume1.coreservlets.com/archive/index.html
Chapter 15: Integrating Servlets and JSP:
The Model View Controller (MVC) Architecture

Thursday, October 05, 2006


Tuning Datasource for Oracle 10g in TomCat 5.5 on Linux



It's a brief instruction how to tune files:



./WEB-INF/web.xml
./META-INF/context.xml




for Web application supposed to be deployed to TomCat 5.5.17
and use Datasource (JNDI API) to connect to Oracle 10gR2 database


Create following directory structure and and put file "ojdbc14.jar" (Oracle JDBC Driver) into ./WEB-INF/lib

Tune files ./WEB-INF/web.xml & ./META-INF/context.xml as follows.



$ ls -CR
.:
OrclData.jsp errorpg.jsp SqlQuery.html index.jsp META-INF WEB-INF

./META-INF:
context.xml

./WEB-INF:
lib
web.xml

./WEB-INF/lib
ojdbc14.jar




*****************************
File ./META-INF/context.xml
*****************************



<Context debug="0" docBase="OraDataSrc" path="/OraDataSrc" reloadable="true">
<Resource name="jdbc/oracle10g"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@ServerRHL.informatics.dstu.net:1521:jdvs"
username="hr"
password="hr"
maxActive="100"
maxIdle="10"/>
</Context>




*************************
File ./WEB-INF/web.xml
*************************



<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
version="2.4">

<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/oracle10g</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>




********************
File SqlQuery.html
********************


<html>
<head>
<title>Help page</title>
</head>
<body>
<h2>Please submit SQL Query </h2>
<form method="get" action="/OraDataSrc/OrclData.jsp">
<table border="1">
<tr> <td valign="top">
<input type="text" name="sqlquery" size="100">
</td></tr>
</table></form>
<p>
<input type="submit" value="Submit Query">
</body>
</html>




*******************
File OrclData.jsp
*******************



<html>
<head>
<%@ page errorPage="errorpg.jsp"
import="java.sql.*,
javax.naming.Context,
javax.naming.InitialContext,
javax.naming.NamingException,
javax.sql.*,
javax.servlet.*,
javax.servlet.http.*" %>
</head>
<body>
<%!
DataSource datasrc ;
public void _jspInit() {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
datasrc = (DataSource) envCtx.lookup ("jdbc/oracle10g");
} catch (NamingException ne) {ne.getMessage();}
}
%>

<%
Connection conn = datasrc.getConnection();
Statement stmt = conn.createStatement();
String sqlquery = request.getParameter("sqlquery");
ResultSet rs = stmt.executeQuery(sqlquery);
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
%>
<table border = \"1\"> <tr>
<% for (int i = 1; i <= colCount; ++i) { %>
<th> <%= rsm.getColumnName(i) %> </th>
<% } %>
</tr>
<tr>
<% while (rs.next()) {
for (int j = 1; j <= colCount; ++j) { %>
<td> <%= rs.getString(j) %> </td>
<% } %>
</tr>
<% }
stmt.close();
conn.close();
%>
</table>
</body>
</html>




Goto directory containing build.xml and modify it as needed.
OraDataSrc directory should be a subdirectory of previous one.
Run:-



$ ant -f build.xml
$ ant -f build.xml deploy




Application OraDataSrc may be started and tested from TomCat's
Manager Utility.