Latest Entries »

Showing posts with label Icefaces. Show all posts
Showing posts with label Icefaces. Show all posts

Saturday, July 11, 2009

Integrating JSF, Hibernate and Spring

Hello Folks,This post describes the steps to configure Spring Hibernate JSF application. Integration of these three technologies makes a solid framework for web application development.
Creating the application with out IDE:Download the jars for JSF (Ex: Icefaces).Download the jars for Hibernate library.
Download the jars for Spring Library.
Jar's need are
ant-1.6.5.jar, ant-antlr-1.6.5.jar, ant-junit-1.6.5.jar, ant-launcher-1.6.5.jar, ant-swing-1.6.5.jar, antlr-2.7.6.jar, asm-attrs.jar, asm.jar, c3po-0.9.1.jar, cglib-2.1.3.jar, checkstyle-all.jar, cleanimports.jar, commons-beanutils-1.7.0.jar, commons-codec-1.3.jar, commons-collections-2.1.1.jar, commons-collections-3.1.1.jar, commons.digester-1.6.jar, commons-el-1.0.jar, commons-fileupload-1.0.jar, commons-lang-2.1.jar, commons-logging-1.0.4.jar, commons-validator-1.3.1.jar, concurrent-1.3.2.jar, connector.jar, dom4j-1.6.1.jar, ehcache-1.2.3.jar, hibernate3.jar, jass.jar, jacc-1_0-fr.jar, javassist.jar, jaxen-1.1-beta-7.jar, jdbc2_0-stdext.jar, jgroups-2.2.8.jar, jstl-1.1.0.jar, jta.jar, junit-3.8.1.jar, log4j-1.2.11.jar, myfaces-api-1.1.5.jar, myfaces-impl-1.1.5.jar, mysql-connector-java-3.0.16-ga-bin.jar, mysqlconnector-java-3.1.6-bin.jar, oro-2.0.8.jar, oscache-2.1.jar, proxool-0.8.3.jar, spring.jar, swarmcache-1.0rc2.jar, syndiag2.jar, tomahawk-1.1.6.jar, versioncheck.jar, xerces-2.6.2.jar, xml-apis.jar



















Now create the web application and copy all the above lib files under the WEB-INF folder.

Creating the web project with the MyEclipse IDE:Create New Web Application, add JSF capabilities (you can add different kind of flavours of JSF to your application Ex: Icefaces, Richfaces). Now add the spring capabilities and hibernate capabilities.
Create hibernate POJO's and DAO's classes (Hibernate Annotaions library is required to build POJO's & DAO's). Register all the POJO & DAO classes in the spring application contect file, to create hibernate POJO & DAO classes select the MyEclipse Hibernate Prespective. Add the database driver and connect to the database using DB browser. Navigate to the database-->tables, select all the tables and right click go to hibernate reverse engineering option. MyEclipse will take you to the several screens, here you need to select create POJO and create DAO options which will generate POJO & DAO classes.Register all the POJO & DAO classes in the applicationContext.xml file
Sample Code :












Add this spring context file in web.xml




At this point our web application got the relationship between the spring and hibernate and we registered them in web.xml. Now the tedious part of the application is to integrate this part with the JSF.

To integrate JSF and Spring , Spring API provides a variable resolver called DelegatingVariableResolver (but dude it work's only with JSF1.1 and it is not compatible with JSF1.2)




If we create one custom funtion works as DelegatingVariableResolver, then our application will be independent of spring API.


Sample Code:
import javax.faces.context.Facescontext;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class ServiceFinder {

public static object findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();

ServletContext servletContext = (ServletContext)context.getExternalContext().getContext();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

Object o = appContext.getBean(beanName);

return o;
}
}










And call this funtion in your managed bean like :

ProductionDAO productionDAO = (ProductionDAO) ServiceFinder
.findBean("ProductionDAO");

This completes the integration part of JSF, HIbernate and Spring.

Application Architechture:

Web application consists of 3 layers
1. Presentaion Layer
2. Business Layer
3. Data Access Layer


In our application the presentation layer, business layer and data access layer are physically located on the same JEE server. The different layers of the application are isolated from each other and connected through well defined interfaces.








Presentation Layer

JSF is used to build the presentation layer of the application. JFS allows us to create rich gui for web application. It resolves the technical challenges of creating rich gui web application. In this layer we have jsp pages and JSF components. All the request to the web server are passes through faces servlet.

Business Layer

The POJO classes and classes to process the business logic are used to create the Business Layer. The POJO classes with the help of spring framework creates an ideal solution to implement the Business Layer.

Data Access Layer

The data access layer handles all the logic to save and retrieve the data from data base. Hibernate O/R mapping tools is an ideal solution for enterprise application of any size. Hibernate handles all the logic to store and retrieve POJO objects. It also handles resource management and transaction management activities.

Sunday, April 5, 2009

Lazy initialization in Hibernate with icefaces JSF and Spring

To avoid hibernate lazy initialization there are different methods depending upon the project configuration. My project configuration is icefaces as a presentation layer, spring as a business layer and hibernates as a transaction layer.

Use the following class code as a listener and you need to register this class in faces-config.xml










package com.project.util;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;


public class OpenSessionInViewPhaseListener implements PhaseListener {

/**
*
*/
private static final long serialVersionUID = -3263031646854899605L;

@SuppressWarnings("unchecked")
private static ThreadLocal ts = new ThreadLocal();

private class ThreadData {
private boolean participate;
private Session session;
private SessionFactory sessionFactory;
private int beforeTimes;
private int afterTimes;
}

@SuppressWarnings("unchecked")
public void beforePhase(PhaseEvent pe) {
ThreadData td = (ThreadData) ts.get();
if (td == null) {
td = new ThreadData();
} else {
td.beforeTimes++;
return;
}
if (pe.getPhaseId() == PhaseId.RESTORE_VIEW) {
td.sessionFactory = lookupSessionFactory(pe.getFacesContext());
td.session = null;
td.participate = false;

if (isSingleSession()) {
// single session mode
if (TransactionSynchronizationManager
.hasResource(td.sessionFactory)) {
// Do not modify the Session: just set the participate flag.
td.participate = true;
} else {
td.session = getSession(td.sessionFactory);
TransactionSynchronizationManager.bindResource(
td.sessionFactory, new SessionHolder(td.session));
}
} else {
// deferred close mode
if (SessionFactoryUtils
.isDeferredCloseActive(td.sessionFactory)) {
// Do not modify deferred close: just set the participate
// flag.
td.participate = true;
} else {
SessionFactoryUtils.initDeferredClose(td.sessionFactory);
}
}

}
ts.set(td);
}

@SuppressWarnings("unchecked")
public void afterPhase(PhaseEvent pe) {
if (pe.getPhaseId() == PhaseId.RENDER_RESPONSE) {
ThreadData td = (ThreadData) ts.get();
if (td == null)
return;
if (td.afterTimes != 0) {
td.afterTimes++;
return;
}
td.afterTimes++;
if (!td.participate) {
if (isSingleSession()) {
// single session mode
TransactionSynchronizationManager
.unbindResource(td.sessionFactory);
try {
closeSession(td.session, td.sessionFactory);
} catch (RuntimeException ex) {
ex.printStackTrace();
}
} else {
// deferred close mode
SessionFactoryUtils.processDeferredClose(td.sessionFactory);
}
}
ts.set(null);
}
}

public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}

public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";

private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME;

private boolean singleSession = true;

/**
* Set the bean name of the SessionFactory to fetch from Spring's root
* application context. Default is "sessionFactory".
*
* @see #DEFAULT_SESSION_FACTORY_BEAN_NAME
*/
public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
this.sessionFactoryBeanName = sessionFactoryBeanName;
}

/**
* Return the bean name of the SessionFactory to fetch from Spring's root
* application context.
*/
protected String getSessionFactoryBeanName() {
return sessionFactoryBeanName;
}

/**
* Set whether to use a single session for each request. Default is "true".
*
* If set to false, each data access operation or transaction will use its
* own session (like without Open Session in View). Each of those sessions
* will be registered for deferred close, though, actually processed at
* request completion.
*
* @see SessionFactoryUtils#initDeferredClose
* @see SessionFactoryUtils#processDeferredClose
*/
public void setSingleSession(boolean singleSession) {
this.singleSession = singleSession;
}

/**
* Return whether to use a single session for each request.
*/
protected boolean isSingleSession() {
return singleSession;
}

/**
* Look up the SessionFactory that this filter should use.
*
* Default implementation looks for a bean with the specified name in
* Spring's root application context.
*
* @return the SessionFactory to use
* @see #getSessionFactoryBeanName
*/
protected SessionFactory lookupSessionFactory(FacesContext facesContext) {
WebApplicationContext wac = FacesContextUtils
.getRequiredWebApplicationContext(facesContext);
return (SessionFactory) wac.getBean(getSessionFactoryBeanName(),
SessionFactory.class);
}

/**
* Get a Session for the SessionFactory that this filter uses. Note that
* this just applies in single session mode!
*
* The default implementation delegates to SessionFactoryUtils' getSession
* method and sets the Session's flushMode to NEVER.
*
* Can be overridden in subclasses for creating a Session with a custom
* entity interceptor or JDBC exception translator.
*
* @param sessionFactory
* the SessionFactory that this filter uses
* @return the Session to use
* @throws DataAccessResourceFailureException
* if the Session could not be created
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,
* boolean)
* @see org.hibernate.FlushMode#NEVER
*/
@SuppressWarnings("deprecation")
protected Session getSession(SessionFactory sessionFactory)
throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.AUTO);
return session;
}

/**
* Close the given Session. Note that this just applies in single session
* mode!
*
* The default implementation delegates to SessionFactoryUtils'
* releaseSession method.
*
* Can be overridden in subclasses, e.g. for flushing the Session before
* closing it. See class-level javadoc for a discussion of flush handling.
* Note that you should also override getSession accordingly, to set the
* flush mode to something else than NEVER.
*
* @param session
* the Session used for filtering
* @param sessionFactory
* the SessionFactory that this filter uses
*/
protected void closeSession(Session session, SessionFactory sessionFactory) {
SessionFactoryUtils.releaseSession(session, sessionFactory);
}

}


Faces-config.xml registration





After rendering the session will be closed, if you try to retrieve any object from the EntityManager it will give you lazy initialization exception.

If you would like to maintain a single session then you may use the following code snippet to solve your issue











package com.project.util;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.hibernate.FlushMode;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.dao.DataAccessResourceFailureException;

import org.springframework.orm.hibernate3.SessionFactoryUtils;

import org.springframework.orm.hibernate3.support.OpenSessionInViewFilter;

public class SessionFilter extends OpenSessionInViewFilter {

protected final Log logger = LogFactory.getLog(SessionFilter.class);

protected Session getSession(SessionFactory sessionFactory)

throws DataAccessResourceFailureException {

Session session = SessionFactoryUtils.getSession(sessionFactory, true);

session.setFlushMode(FlushMode.AUTO);

logger.info("open session");

return session;

}

protected void closeSession(Session session, SessionFactory factory) {

logger.info("close session");

session.flush();

super.closeSession(session, factory);

}

}



package com.project.util;

import javax.faces.context.FacesContext;

import javax.faces.event.PhaseEvent;

import javax.faces.event.PhaseId;

import javax.faces.event.PhaseListener;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.orm.hibernate3.SessionHolder;

import org.springframework.transaction.support.TransactionSynchronizationManager;

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.jsf.FacesContextUtils;

public class SessionListner extends SessionFilter implements PhaseListener {

private static final long serialVersionUID = -2080231862377196879L;

private static Log log = LogFactory

.getLog("com.project.util.SessionListner");

public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME = "sessionFactory";

public void beforePhase(PhaseEvent pe) {

if (pe.getPhaseId() == PhaseId.RESTORE_VIEW) {

SessionFactory sessionFactory = lookupSessionFactory(pe

.getFacesContext());

log

.info("Opening single Hibernate Session in SessionListner");

Session session = getSession(sessionFactory);

TransactionSynchronizationManager.bindResource(sessionFactory,

new SessionHolder(session));

}

}

public void afterPhase(PhaseEvent pe) {

SessionFactory sessionFactory = lookupSessionFactory(pe

.getFacesContext());

if (pe.getPhaseId() == PhaseId.RENDER_RESPONSE) {

SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager

.unbindResource(sessionFactory);

log

.info("Closing single Hibernate Session in SessionListner");

closeSession(sessionHolder.getSession(), sessionFactory);

}

}

protected SessionFactory lookupSessionFactory(FacesContext facesContext) {

WebApplicationContext wac = FacesContextUtils

.getRequiredWebApplicationContext(facesContext);

return (SessionFactory) wac.getBean(DEFAULT_SESSION_FACTORY_BEAN_NAME,

SessionFactory.class);

}

public PhaseId getPhaseId() {

return PhaseId.ANY_PHASE;

}

}


Register this listener in your web.xml file



Another work around is




Also we can manage by configuring the hibernate properties in the applicationContext.xml





The solution which I adopted is OpenSessionInViewPhaseListener, it worked for me.


Monday, January 5, 2009

How to display dynamic image from blob data in icefaces ?

To display ice graphic image from the blob content, add icefaces-comps.jar and icefaces.jar.
These jar files contains improved ice graphic image component.
Click here to download the jar files.
This component supports byte[] and url to file.

Sample code of hibernate pojo and icefaces jsp file.
Hibernate POJO Code:
private byte[] content;
@Column(name = "Content")
public byte[] getContent() {
return this.content;
}
public void setContent(byte[] content) {
this.content = content;
}
JSP Page Code:
< ice:graphicImage height="50" width="50" value="#{image.content}"><\ice:graphicImage>