Thursday, February 15, 2007


Install CentOS 4.4 on ASUS P5B Deluxe



CentOS 4.4 has been istalled on the box as a second operating system
utilizing SATA DVD RW connected to Intel's ICH8R SouthBridge
(SATA,RAID) port. Both Intel ICH8R and Jmicron JMB363 controllers
have been turned into AHCI mode before first OS (Windows 2003) install.
Driver for Marvell Youkon Gigabit Ethernet Adapter has been downloaded from:-



Following symlink was created to compile skge driver:-



Kernel config appears to be OK to load sky98lin module at next reboot , kernel recompilation was not needed:-



Detailed hardware detection of chipsets on P5B Deluxe MB may be viewed on screenshots:-











Network adapter view after SKGE driver install:-



Telnet connection screen from remote host:-



Sound card detection:-

Thursday, January 11, 2007


Regarding proper packaging files with project in NETBEANS 5.5



To package file with project having requered PATH in WAR you have
click on "Item" content field after typing PATH in PATH in WAR field.
Screen should look like on Windows:-





on Linux:-

In this case when you get back to this screen later it will look like on Windows:-





on Linux:-





If you just click "OK" after typing in PATH in WAR field , when you get back to this
screen you will find "PATH in WAR" field empty.
In this case packaging will place file in root folder of corresponding WAR archive.
instead of "WEB-INF" for example.
It works this way on Linux and on Windows.

Thursday, January 04, 2007


Facelets, (JBOSS) Seam, Netbeans and Glassfish



This posting demonstrates that we don't have to package components.xml
with sampleProject-war.



Working on second sample from :

Recent publication: Facelets, (JBOSS) Seam, Netbeans and Glassfish

I have commented out second entry in components.xml:-


<!DOCTYPE components PUBLIC
"-//JBoss/Seam Component Configuration DTD 1.1//EN"
"http://jboss.com/products/seam/components-1.1.dtd">

<components>

<component name="org.jboss.seam.core.init">
<property name="debug"> true </property>
</component>

<!--
<component name="org.jboss.seam.core.init">
<property name="jndiPattern"> java:comp/env/sampleProject-ejb/#{ejbName}/local </property>
</component>
-->

<component name="entityManager" class="org.jboss.seam.core.ManagedPersistenceContext">
<property name="persistenceUnitJndiName"> java:/sampleProject-ejbPU</property>
</component>

</components>




and kept web.xml's corresponding entry in place:-


<context-param>
<description>
</description>
<param-name>org.jboss.seam.core.init.jndiPattern</param-name>
<param-value>java:comp/env/sampleProject?ejb/#{ejbName}/local</param-value>
</context-param>
<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>
<filter>
<filter-name>SeamRedirectFilter </filter-name>
<filter-class>org.jboss.seam.servlet.SeamRedirectFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SeamRedirectFilter </filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
<filter>
<filter-name>SeamExceptionFilter</filter-name>
<filter-class>org.jboss.seam.servlet.SeamExceptionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SeamExceptionFilter </filter-name>
<url-pattern >*.xhtml</url-pattern>
</filter-mapping>
<ejb-local-ref>
<ejb-ref-name>sampleProject?ejb/ActionBean/local</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>dummy.ActionLocal</local>
<ejb-link >ActionBean</ejb-link>
</ejb-local-ref>




Packaging components.xml with sampleProject-war, generated following
entry into C: \Solaris\AppServer\domains\domain1\logs\server.log during deployment:-


[#|2007-01-04T13:58:38.265+0300|WARNING|sun-appserver-pe9.0|javax.enterprise.resource.webcontainer.jsf.lifecycle|
_ThreadID=15;_ThreadName=httpWorkerThread-8080-1;_RequestID=02b398d6-1127-4c3d-9444-5c446d01a0a5;|
Could not instantiate Seam component:
action org.jboss.seam.InstantiationException:
Could not instantiate Seam component: action
at org.jboss.seam.Component.newInstance(Component.java:1722)
at org.jboss.seam.Component.getInstance(Component.java:1625)
at org.jboss.seam.Component.getInstance(Component.java:1592)
at org.jboss.seam.Component.getInstance(Component.java:1586)
at org.jboss.seam.jsf.SeamELResolver.getValue(SeamELResolver.java:39)
. . . . . . . . .




Configuration suggested above didn’t.
However entry:-


[#|2007-01-05T12:59:02.046+0300|WARNING|sun-appserver-pe9.0|javax.enterprise.system.core.classloading|
_ThreadID=11;_ThreadName=httpWorkerThread-4848-0;_RequestID=6735512c-cb12-4daf-9af8-406d320f710d;|
Input stream has been finalized or forced closed without being explicitly closed; stream instantiation
reported in following stack trace
java.lang.Throwable
at com.sun.enterprise.loader.EJBClassLoader$SentinelInputStream.(EJBClassLoader.java:1123)
at com.sun.enterprise.loader.EJBClassLoader.getResourceAsStream(EJBClassLoader.java:788)
. . . . . . . . . ..




showed up in both cases during deployment , but didn't affect running application
No packaging components.xml with sapmleProject-war has been done before running
project.Regarding proper packaging view also:-


Packaging files with projects issues in NetBeans 5.5


Snapshots:-














Unload NetBeans 5.5 and run deployed apps:-





Load NetBeans and perform database control:-



We are going to make a slight modification to original project.



*****************
ActionLocal.java
*****************


package dummy;
import javax.ejb.Local;
/**
* This is the business interface for Action enterprise bean.
*/
@Local
public interface ActionLocal {
public String registration ();
}




*********************
ActionBean.java
*********************


package dummy;
import dummy.entity.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Outcome;
import org.jboss.seam.ejb.SeamInterceptor;

@Stateless
@Name( "action" )

public class ActionBean implements ActionLocal {
@In( create=true , required=true )
User user;

@PersistenceContext ( )
private EntityManager em;
public ActionBean ( ) { }
public String registration (){
List persons = em.createQuery("select x from User x where x.username=:username").setParameter("username", user.getUsername()).getResultList();
if (persons.size()==0)
{
em.persist(user);
return "success";
}
else
{
return "repeat";
}
}

}




***************************************************************
First client for sampleTemplate - template-client.xhtm
***************************************************************


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
This text above will not be displayed.
<ui:composition template="/template.xhtml">
This text will not be displayed.
<ui:define name="title">
Registration Form
</ui:define>
This text will also not be displayed.
<ui:define name="body">
<ui:define name="content">
<h:form>
<h:inputText id="username" value="#{user.username}"/>
<h:inputText id="password" value="#{user.password}"/>
<h:commandButton value="Sign in" action="#{action.registration}"/>
</h:form>
</ui:define>
</ui:define>
This text will not be displayed.
</ui:composition>
This text below will also not be displayed.
</body>
</html>




****************************************************************
Second client for sampleTemplate -TemplateClientOk.xhtml
****************************************************************


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">

<body>

<ui:composition template="sampleTemplate.xhtml">

<ui:define name="top">
Registration done for:
</ui:define>

<ui:define name="content">
<h:form>
<h:outputText id="username" value="#{user.username}"/>
</h:form>
</ui:define>

</ui:composition>

</body>
</html>




**************************************************************
Third client for sampleTemplate -TemplateClientNO.xhtml
**************************************************************


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">

<body>

<ui:composition template="sampleTemplate.xhtml">

<ui:define name="top">
Already registered user's name:
</ui:define>
<ui:define name="content">
<h:form>
<h:outputText id="username" value="#{user.username}"/>
</h:form>
</ui:define>

</ui:composition>

</body>
</html>




*****************************
Add to faces-config.xml
*****************************


<navigation-rule>
<from-view-id>/template-client.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/templateClientOK.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>repeat</from-outcome>
<to-view-id>/TemplateClientNO.xhtml</to-view-id>
</navigation-case>
</navigation-rule>





Now testing runs smoothly . Violation of primary key doesn't cause apps crash








Attempt to register twice is caught:-



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