Thursday, November 02, 2006

Catching Rollback Exceptions in TopLink Essentials



This post follows up:

Toplink JPA outside EJB3 Container in TomCat 5.5



We just do exactly what advised in OTN Toplink Essentials JPA Reference.
******************************************************************
Modify WEB-INF/classes/DataBean.java and replace methods:
******************************************************************



public void empSelected(ActionEvent actionEvent) {

this.departId =
((Integer)((UIParameter)actionEvent.getComponent().getFacet("extraParameter")).getValue()).intValue();
setEmpModificationResult(" ");
}

// Handling rollback when delete.

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();
}
}

//Handling rollback wnen insert or update.

public void completeEmpUpdate(ActionEvent actionEvent) {

try {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date parsedDate = formatter.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 setEmpModificationResult(String empModificationResult) {
this.empModificationResult = empModificationResult;
}

public String getEmpModificationResult() {
return empModificationResult;
}




***************************************
Add to the bottom of employee.jsp:-
***************************************



<f:verbatim>
<hr/>
</f:verbatim>
<h:outputText value="#{dataBean.empModificationResult}"/>




Now attempt to violate primary key "empno" when inserting record
into table scott.emp won't crash apps and will display message:-








In case of success we get message:


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.

Wednesday, September 27, 2006


Access to JavaBean as JNDI resource from JSP in TomCat 5.5



The target of an article is to build sample web application using filter servlet to obtain access to JavaBean as JNDI resource

In general we follow ch. 25.3 from [1].However,instead of creating
new bean for every new session, we create shared bean analyzing
value of object bean with call:-



bean = (MyBean) hSession.getAttribute("key");




In case when ( been == null) following code runs :-



bean = (MyBean) env.lookup("bean/MyBeanFactory");
hSession. setAttribute ("key", bean) ;




Object bean is supposed to be assigned the pointer to newly
created instance of MyBean class due to calling method
getObjectInstance( ) from MyBeanFactory class.
To get it working in TomCat 5.5.17 tune ./META-INF/context.xml to configure Tomcat's resource factory.
Web Application file layout :








*************************************
Create file ./META-INF/context.xml
*************************************



<Context debug="0"
docBase="JNDIBean" path="/JNDIBean" reloadable="true">
<Resource name="bean/MyBeanFactory" auth="Container"
type="coreservlets.MyBean"
factory="coreservlets.MyBeanFactory" />
</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-env-ref>
<description>
Object factory for MyBean instances.
</description>
<resource-env-ref-name>
bean/MyBeanFactory
</resource-env-ref-name>
<resource-env-ref-type>
coreservlets.MyBean
</resource-env-ref-type>
</resource-env-ref>

<filter>
<filter-name>JndiFilter</filter-name>
<filter-class>coreservlets.JndiTFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>JndiFilter</filter-name>
<url-pattern>/JndiJsp.jsp</url-pattern>
</filter-mapping>

</web-app>




****************
File JndiJsp.jsp
****************



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head><title>Jndi Bean</title></head> <body>
<h4>Getting Names object via JNDI ... </h4>

<jsp:useBean id="MBN" type="coreservlets.MyBean" scope="session" />
<table border = "1">
<tr>
<th>Fisrt Name</th><th>Last Name</th>
</tr>
<tr>
<td><jsp:getProperty name="MBN" property="firstName" /></td>
<td><jsp:getProperty name="MBN" property="lastName" /></td>
</tr>
</table>
</body>
</html>




*****************
File MyBean.java
*****************



package coreservlets;

public class MyBean {
private String firstName = "Missing first name";
private String lastName = "Missing last name";

public MyBean() {}

public String getFirstName() {
return(firstName);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return(lastName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}




*************************************
Modified version of JndiTFilter.java
*************************************



package coreservlets;

import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;

public class JndiTFilter implements Filter {

private FilterConfig config;
private Context envCtx;

public JndiTFilter( ) { }

public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;

try {
envCtx = (Context) new InitialContext().lookup("java:comp/env");
envCtx.close();
} catch (NamingException ne) {
try { envCtx.close(); } catch (NamingException nex) { }
throw new ServletException(ne);
}

}

public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain)
throws IOException,ServletException {
MyBean bean = null;

HttpServletRequest hRequest = null;

if (request instanceof HttpServletRequest)
hRequest = (HttpServletRequest) request;

HttpSession hSession = hRequest.getSession();

if (hSession != null) {

// Creating shared bean with envCtx.lookup()
// Compare with source ( ch.25.3 from [1])

bean = (MyBean) hSession.getAttribute("MBN");
if (bean == null) {
try {
bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
} catch (NamingException ne) { }
hSession. setAttribute ("MBN", bean) ;
}

String firstName = request.getParameter("firstName");
if ((firstName != null) && (!firstName.trim().equals(""))) {
bean.setFirstName(firstName);
}
String lastName = request.getParameter("lastName");
if ((lastName != null) && (!lastName.trim().equals(""))) {
bean.setLastName(lastName);
}
}
chain.doFilter(request,response);
}
public void destroy() { }
}




**************************
File MyBeanFactory.java
**************************



package coreservlets;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {
public Object getObjectInstance(Object obj,
Name name, Context nameCtx, Hashtable environment)
throws NamingException {

// Acquire an instance of our specified bean class
MyBean bean = new MyBean();
// Customize the bean properties from our attributes

Reference ref = (Reference) obj;
Enumeration addrs = ref.getAll();
while (addrs.hasMoreElements()) {
RefAddr addr = (RefAddr) addrs.nextElement();
String nameUser = addr.getType();
String value = (String) addr.getContent();
if (nameUser.equals("firstName")) {
bean.setFirstName(value);
} else if (nameUser.equals("lastName")) {
bean.setLastName(value);
}
}
// Return the customized instance
return (bean);
}
}



References.

1.Java Servlet and JSP Cookbook. Bruce W. Perry. O'Reilly,2004

Friday, August 04, 2006


Install TomCat 5.5.17 with Apache Portable Runtime 1.2.7 on Linux



Tomcat can use the Apache Portable Runtime to provide superior scalability, performance, and better integration with native server technologies. The Apache Portable Runtime is a highly portable library that is at the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO functionality (such as sendfile, epoll and OpenSSL),OS level functionality (random number generation, system status, etc), and native process handling
(shared memory, NT pipes and Unix sockets).View for details:
http://tomcat.apache.org/tomcat-5.5-doc/apr.html


Install Apache Portable RunTime 1.2.7 and openssl-0.9.8b on the box (CentOS 4.2).

APR Source directory - /usr/local/src/apr-1.2.7

APR Target directory - /usr/local/apr

OPEN SSL Target directory - /usr/local/ssl

Account "tomcat" has the same .bash_profile as in [1].

Tomcat Server version 5.5.17 has been installed by "tomcat" as usual.



# su - tomcat




Compile $CATALINA_HOME/bin/jsvc :-



cd $CATALINA_HOME/bin
tar xvfz jsvc.tar.gz
cd jsvc-src
autoconf
./configure
make
cp jsvc ..
cd ..




Proceed with compiling libraries for APR:-



$ cd $CATALINA_HOME/bin/tomcat-native-1.1.3/jni/native
$ sh buildconf --with-apr=/usr/local/src/apr-1.2.7
$ ./configure --with-apr=/usr/local/apr --with-ssl=/usr/local/ssl
$ make
$ cd .libs
[tomcat@ServerCentOS4U2 .libs]$ pwd
/home/tomcat/apache-tomcat-5.5.17/bin/tomcat-native-1.1.3/jni/native/.libs
[tomcat@ServerCentOS4U2 .libs]$ ls -l
total 1572
-rw-r--r-- 1 tomcat users 937506 Aug 4 15:47 libtcnative-1.a
lrwxrwxrwx 1 tomcat users 19 Aug 4 15:47 libtcnative-1.la -> ../libtcnative-1.la
-rw-r--r-- 1 tomcat users 990 Aug 4 15:47 libtcnative-1.lai
lrwxrwxrwx 1 tomcat users 22 Aug 4 15:47 libtcnative-1.so -> libtcnative-1.so.0.1.3
lrwxrwxrwx 1 tomcat users 22 Aug 4 15:47 libtcnative-1.so.0 -> libtcnative-1.so.0.1.3
-rwxr-xr-x 1 tomcat users 657270 Aug 4 15:47 libtcnative-1.so.0.1.3




Create as root startup script /etc/init.d/TomCatJsvc:-




# Script to start TomCat 5.5.17 as daemon with version 1.1.3 "tc" native support
# library for Apache Portable Runtime 1.2.7
# Variable CATALINA_OPTS provides the path to "tc" native library


JAVA_HOME='/home/tomcat/jdk1.5.0_06'
CATALINA_HOME='/home/tomcat/apache-tomcat-5.5.17'
CLASSPATH=$CATALINA_HOME/bin/bootstrap.jar:$CATALINA_HOME/bin/commons-daemon.jar:$JAVA_HOME/lib/tools.jar
CATALINA_OPTS="$CATALINA_OPTS -Djava.library.path=/home/tomcat/apache-tomcat-5.5.17/bin/tomcat-native-1.1.3/jni/native/.libs"
TOMCAT_USER=tomcat
TMPDIR=/var/tmp

RC=0

case "$1" in
start)

$CATALINA_HOME/bin/jsvc -user $TOMCAT_USER -home $JAVA_HOME -Dcatalina.home=$CATALINA_HOME -Djava.io.tmpdir=$TMPDIR -Djava.awt.headless=true -outfile $CATALINA_HOME/logs/catalina.out -errfile $CATALINA_HOME/logs/catalina.err $CATALINA_OPTS -cp $CLASSPATH org.apache.catalina.startup.Bootstrap

RC=$?

[ $RC = 0 ] && touch /var/lock/subsys/tomcat
;;

stop)

PID=`cat /var/run/jsvc.pid`
kill $PID

RC=$?

[ $RC = 0 ] && rm -f /var/lock/subsys/tomcat /var/run/jsvc.pid
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
exit $RC




Enable Open SSL on TomCat 5.5.17 :-



# su - tomcat
$ cd $CATALINA_HOME/conf/
$ /usr/local/ssl/bin/openssl genrsa -des3 -out tomcatkey.pem 2048
$ /usr/local/ssl/bin/openssl req -new -x509 -key tomcatkey.pem -out tomcatcert.pem -days 1095




Changes have been done to $CATALINA_HOME/conf/server.xml:








To start server:-



# /etc/init.d/TomCatJsvc start




Snapshot of $CATLINA_HOME/logs/catalina.out at startup:






Snapshots of "https" connections to server through port 8443:-










References.
1.http://bderzhavets.blogspot.com/2006/08/running-tomcat-5.html

Tuesday, August 01, 2006


Running TomCat 5.5 as Linux Daemon



Perform standard Tomat 5.5.X server install by account "tomcat".
Compile as officially advised in [1] $CATALINA_HOME/bin/jsvc binary :-



cd $CATALINA_HOME/bin
tar xvfz jsvc.tar.gz
cd jsvc-src
autoconf
./configure
make
cp jsvc ..
cd ..




To be succeed starting up TomCat's jsvc daemon with JDK 1.5
create as root script "/etc/init.d/TomCatJsvc",
compare it with daemon startup script suggested in [1]:-



JAVA_HOME='/home/tomcat/jdk1.5.0_06'
CATALINA_HOME='/home/tomcat/apache-tomcat-5.5.16'
CLASSPATH=$CATALINA_HOME/bin/bootstrap.jar:$CATALINA_HOME/bin/commons-daemon.jar:$JAVA_HOME/lib/tools.jar
TOMCAT_USER=tomcat
TMPDIR=/var/tmp


RC=0

case "$1" in

start)

$CATALINA_HOME/bin/jsvc -user $TOMCAT_USER -home $JAVA_HOME -Dcatalina.home=$CATALINA_HOME -Djava.io.tmpdir=$TMPDIR -Djava.awt.headless=true -outfile $CATALINA_HOME/logs/catalina.out -errfile $CATALINA_HOME/logs/catalina.err -cp $CLASSPATH org.apache.catalina.startup.Bootstrap

RC=$?

[ $RC = 0 ] && touch /var/lock/subsys/tomcat
;;

stop)

PID=`cat /var/run/jsvc.pid`
kill $PID

RC=$?

[ $RC = 0 ] && rm -f /var/lock/subsys/tomcat /var/run/jsvc.pid
;;

*)
echo "Usage: $0 {start|stop}"
exit 1
esac
exit $RC




Then run as root:-



# /etc/init.d/TomCatJsvc start




If "ps -ef|grep tomcat" output looks like:-




and $CATALINA_HOME/logs/catalina.out:-





then you should be fine with launching browser to http://localhost:8080.

For automatic startup/shutdown TomCat's daemon create 3 symbolic links:-



# ln -s /etc/init.d/TomCatJsvc /etc/rc5.d/S99TomCatJsvc
# ln -s /etc/init.d/TomCatJsvc /etc/rc0.d/K09TomCatJsvc
# ln -s /etc/init.d/TomCatJsvc /etc/rc6.d/K09TomCatJsvc




References

1.http://tomcat.apache.org/tomcat-5.5-doc/setup.html


Sunday, July 30, 2006


Advanced Configuration - Multiple Tomcat 5.5 Instances on Linux



Create account tomuser as in [1] with .bash_profile following bellow.

Export new environment variable CATALINA_BASE pointing for example to ~tomuser.



# su - tomuser
$pwd
/home/tomuser
$cat .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs
export CATALINA_BASE=~tomuser
export CATALINA_HOME=/home/tomcat/apache-tomcat-5.5.16
export JAVA_HOME=/home/tomcat/jdk1.5.0_06
export ANT_HOME=/home/tomcat/apache-ant-1.6.5
PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
export PATH
export CLASSPATH=.:..:../..:$CATALINA_HOME/common/lib/servlet-api.jar:$CATALINA_HOME/common/lib/jsp-api.jar:
$CATALINA_HOME/common/lib/naming-factory-dbcp.jar
export DISPLAY=:0.0
unset USERNAME




Then:-



$cp -R $CATALINA_HOME/conf .
$cp -R $CATALINA_HOME/webapps .
$cp -R $CATALINA_HOME/shared .
$cp -R $CATALINA_HOME/work .
$cp -R $CATALINA_HOME/temp .
$cp -R $CATALINA_HOME/logs .
$cd /home/tomuser/conf/Catalina/localhost




Modify 3 files admin.xml,host-manager.xml,manager.xml.

Context should contain new value for docBase.

In particular manager.xml should look like:-



<Context docBase="/home/tomuser/server/webapps/manager"
privileged="true" antiResourceLocking="false" antiJARLocking="false">

<!-- Link to the user database we will get roles from -->
<ResourceLink name="users" global="UserDatabase"
type="org.apache.catalina.UserDatabase"/>
</Context>




Next:-



$cp -R $CATALINA_HOME/server .
$cd conf




Modify server.xml. Three ports values should be changed:-



<Server port="8015" shutdown="SHUTDOWN">

.......

<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="8090" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />

.......

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8019"
enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />




To start new TomCat instance:-



$ $CATALINA_HOME/bin/startup.sh -Dcatalina.base=$CATALINA_BASE




Screenshot of $CATALINA_BASE/logs/catalina.out:-





Screenshot of "admin" report:-




To perform deployment with "ant" to new instance of TomCat :-



$ cd apache-tomcat-5.5.16-deployer




Make one change to build.xml,replacing old port value for TomCat by new one.



<!-- Configure properties to access the Manager application -->
<property name="url" value="http://localhost:8090/manager"/>
<property name="username" value="tomcat"/>
<property name="password" value="tomcat"/>\>




References



1.http://bderzhavets.blogspot.com/2006/07/installation-tomcat5.html


Tuesday, July 25, 2006


Installation TomCat(5.5.17) Client Deployer on Linux(CentOS 4.2)



First :-



# chmod g+r ~tomcat
# chmod g+x ~tomcat




In case when TCD is supposed to be installed on the same host
with server have "ant" installed by tomcat,where tomcat is account used for server install,otherwhise (after creation account tomuser):



1.Perform installation of JDK 1.5 and "ant" by tomuser.
2.Just for example, make assignments:-
ANT_HOME=~tomuser/apache-ant-1.6.5
JAVA_HOME=~tomuser/jdk1.5.0_06
Then modify PATH as follows:
export PATH=$ANT_HOME/bin:$JAVA_HOME/bin:$PATH




Create account tomuser :



# adduser tomuser -g users




with .bash_profile for local deployment



# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs

export JAVA_HOME=~tomcat/jdk1.5.0_06
export ANT_HOME=~tomcat/apache-ant-1.6.5
PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
export PATH
export DISPLAY=:0.0
unset USERNAME




or with .bash_profile for remote deployment



# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs

export JAVA_HOME=~tomuser/jdk1.5.0_06
export ANT_HOME=~tomuser/apache-ant-1.6.5
PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
export PATH
export DISPLAY=:0.0
unset USERNAME




Login as tomuser and untar deployer package.

Then change directory to ~tomuser/apache-tomcat-5.5.17-deployer.

Create file deployer.properties under /home/tomuser/apache-tomcat-5.5.17-deployer

with content:-



name="compile.debug" value="true"
name="compile.deprecation" value="false"
name="compile.optimize" value="true"




Modify two rows in build.xml:-



<property name="webapp" value="bunk-support"/>
<property name="path" value="/bank-support"/>




In case when TomCat Server is running on the remote host with
IP address: IP-Address and name: Host_Name ,entry
"http://localhost:8080/manager" in build.xml
should be replaced by "http://IP-Address:8080/manager" or by "http://Host_Name:8080/manager" .

Create bank-support directory and download source for chapter 15
of Marty Hall's "Core Servlets and JavaServer Pages" book (second edition,v 1). Create file ./WEB-INF/web.xml:-


Then compile with "javac" Bean Class BankCustomer.java under WEB-INF/classes before calling "ant".
Servlet ShowBalance.java would be better
to compile during "ant" build phase.

Jasper Compiler will be also invoked to compile all JSPs.


Snapshot of source directory:-


Snapshot of target directory:-


Thursday, July 06, 2006


Refreshing Master-Detail JSF page after inserting
or deleting row from Detail table (JDeveloper 10.1.3)



Pick up as a sample jpauser schema from [1].
Add one more view to jpauser schema :-



create view OrderView as select * from order_table;




Add method findOrderView(Double) to JPRSFacade Session EJB based
on same TopLink POJOS as in [1] plus Orderview.java




Create Master-Detail page step by step:-










Add code generated by "findOrderView" to code generated by"removeEntity" button.

Save new code for"removeEntity" button into JSF managed bean
for current page.




Now we are done with refresh after delete.


Create page for data entry and bind "persistEntity" at this page.




Then implement refreshing of main page after inserting new record into detail table:

1.Open the browse page and right click in the visual editor. Choose Go To Page Definition.

2.In the Structure window, expand the highest level node. Right click the executables node and choose

Insert inside executables -> invokeAction

3.In the Common Properties tab, specify "tableRefresh" as the Id for the action and choose your detail-table query method name : findOrderView in the Binds dropdown list.

4.Click the Advanced Properties tab

Choose ifNeeded as the Refresh property and to ensure the action is called each time the page is rendered.

Enter ${!adfFacesContext.postback} as the RefreshCondition and click OK.





Project has been deployed to standalone OC4J instance

and behaved as expected

References



1.http://bderzhavets.blogspot.com/2006/05/toplink-jpa-inside-ejb-3.html