Wednesday, March 6, 2013

Detect Home folder using java

import java.io.*;
import javax.swing.filechooser.*;
public class DriveTypeInfo {

    public static void main(String[] args)
    {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        System.out.println("Home directory: " + fsv.getHomeDirectory());
        File[] f = File.listRoots();
        for (File aF : f) {
                System.out.println("Drive: " + aF);
                System.out.println("Display name: " + fsv.getSystemDisplayName(aF));
        }
    }
}

Sunday, October 30, 2011

Calling EJB mehod from java class

public class TestEJBClient {
 

public static void main(String[] args) throws NamingException, CreateException, RemoteException {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");//put correct server host and port
p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Context jndiContext = new javax.naming.InitialContext(p);

SessionHome home = (SessionHome) jndiContext.lookup("example1/PublicSession");
Session bean = home.create();
//calling EJB bean method
bean.echo("Hello");
}


}

Monday, March 28, 2011

putting object to MQ and read objects from EJB Messaging Bean

Object putting java code

========================

QueueConnection queueConnection = null;

QueueSession jmsSession = null;



try {

Hashtable hashtable=new Hashtable();

hashtable.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");

hashtable.put("java.naming.provider.url","jnp://localhost:1099");



QueueConnection queueConnection =MessagingServiceMDBUtil.getQueueConnection(hashtable);


jmsSession = queueConnection.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);

QueueSender sender = jmsSession.createSender(MessagingServiceMDBUtil.getQueue(LookupUtil.lookupMessagingConfig().getJndiProperties()));

// create the message

ObjectMessage message = jmsSession.createObjectMessage();

ArrayList msgList = new ArrayList();

//Object

Student studentObj=new Student();

studentObj.setFristName("Gayan");

studentObj.setLastName("Dissanayake");

msgList.add(studentObj);

message.setObject(msgList);



//send the message

sender.send(message);

sender.close();

log.debug("Message is written to jms queue");

} catch (JMSException e) {

log.error("Sending message via jms failed", e);

} catch (NamingException e) {

log.error("Sending message via jms failed", e);

} catch(ModuleException moduleException) {

log.error("Sending message via jms failed", moduleException);

} finally {

if (queueConnection != null){

try {

queueConnection.close();

log.debug("Closed jms queue connection");

} catch (JMSException e) {

log.error("Closing jms queue connection failed", e);

}

}

if (jmsSession != null){

try {

jmsSession.close();

if (log.isDebugEnabled()) log.debug("Closed jms session");

} catch (JMSException e) {

if (log.isDebugEnabled()) log.error("Closing jms session failed", e);

}

}

}


EJB Messaging Bean

===================


public class MessagingServiceMDB implements MessageDrivenBean, MessageListener {

private static final long serialVersionUID = -6583759698965963589L;

private final Log logger = LogFactory.getLog(getClass());



public void onMessage(Message message){

try {

logger.debug("Entered MessagingServiceMDB.onMessage()");

ObjectMessage objMessage = (ObjectMessage)message;

ArrayList msgProfiles = (ArrayList)objMessage.getObject();

//do business logic here using MQ object

logger.debug("Entered MessagingServiceMDB.onMessage()");

} catch (JMSException jmsException) {

logger.error("Exception in MessagingServiceMDB:onMessage() " + jmsException.getMessage(), jmsException);

} catch (Exception exception) {

logger.error("Exception in MessagingServiceMDB:onMessage() " + exception.getMessage(), exception);

}

}


public void setMessageDrivenContext(MessageDrivenContext cxt) throws EJBException {}

public void ejbRemove() throws EJBException {}

public void ejbCreate() throws EJBException {}

}


add following to ejb-jar.xml

============================


<message-driven >

<description><![CDATA[MessagingServiceMDB Message Driven Bean]]></description>

<display-name>MessagingServiceMDB</display-name>


<ejb-name>MessagingServiceMDB</ejb-name>


<ejb-class>com.isa.holidays.messaging.service.MessagingServiceMDB</ejb-class>


<transaction-type>Container</transaction-type>

<acknowledge-mode>Auto-acknowledge</acknowledge-mode>

<message-driven-destination>

<destination-type>javax.jms.Queue</destination-type>

</message-driven-destination>


<resource-ref >

<res-ref-name>jms/QCF</res-ref-name>

<res-type>javax.jms.QueueConnectionFactory</res-type>

<res-auth>Container</res-auth>

</resource-ref>


</message-driven>

Read/Write excel files using Apache POI - (the Java API for Microsoft Documents)

needed Lib
==========
poi-2.5.1.jar

Sample Code
===========


import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ReadExcelFile
{

public ReadExcelFile()
{
}

public static void main(String args[])
{
String fileName = "C:\\Sample.xls";
Vector dataHolder = ReadCSV(fileName);
printCellDataToConsole(dataHolder);
}

public static synchronized Vector ReadCSV(String fileName)
{
Vector cellVectorHolder = new Vector();
try
{
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int noOfsheets = myWorkBook.getNumberOfSheets();
for(int i = 0; i < noOfsheets; i++)
{
HSSFSheet mySheet = myWorkBook.getSheetAt(i);
Vector cellStoreVector;
for(Iterator rowIter = mySheet.rowIterator(); rowIter.hasNext(); cellVectorHolder.addElement(cellStoreVector))
{
HSSFRow myRow = (HSSFRow)rowIter.next();
Iterator cellIter = myRow.cellIterator();
cellStoreVector = new Vector();
HSSFCell myCell;
for(; cellIter.hasNext(); cellStoreVector.addElement(myCell))
myCell = (HSSFCell)cellIter.next();

}

}

}
catch(Exception e)
{
e.printStackTrace();
}
return cellVectorHolder;
}

private static synchronized void printCellDataToConsole(Vector dataHolder)
{
for(int i = 0; i < dataHolder.size(); i++)
{
Vector cellStoreVector = (Vector)dataHolder.elementAt(i);
System.out.println("Start getting rows");
for(int j = 0; j < cellStoreVector.size(); j++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
System.out.println((new StringBuilder()).append("reading column no -").append(myCell.getCellNum()).toString());
String stringCellValue = "";
if(myCell.getCellNum() == 0)//1st column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 1)//2nd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 2)//3rd column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 3)//4th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
if(myCell.getCellNum() == 4)//5th column is Number based cell
stringCellValue = String.valueOf(myCell.getNumericCellValue());
if(myCell.getCellNum() == 5)//6th column is string based cell
stringCellValue = String.valueOf(myCell.getStringCellValue());
System.out.println((new StringBuilder()).append(stringCellValue).append("\t").toString());
}

System.out.println("end getting rows");
}

}
}

File Upload to server by Servlet(or JSP)

HTML Form
========

<FORM id="upform" name="upform" ENCTYPE='multipart/form-data' action="<URL>" method='POST'>

<INPUT type='file' name='uploadfile'>

<INPUT type='submit' value='upload'>

</FORM>


Needed Lib

===========

commons-fileupload-1.2.2.jar

commons-io-1.4.jar


Needed imports

===============

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


Sample Code Segment

===================

//String fileSavePath="/var/uploaded/"; linux

String fileSavePath="c:\uploaded";

if(ServletFileUpload.isMultipartContent(request))

{

ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

List fileItemsList = null;

try

{

fileItemsList = servletFileUpload.parseRequest(request);

}

catch(FileUploadException e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while parsing Exception is [").append(e.getMessage()).append("]").toString());

}

Iterator iterator = fileItemsList.iterator();

FileItem fi = (FileItem)iterator.next();

String fileName = fi.getName();

fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

String saveFile = (new StringBuilder()).append(fileSavePath).append(fileName).toString();

if("".equalsIgnoreCase(fileName))

throw new Exception("Please choose file to upload");

try

{

fi.write(new File(saveFile));

}

catch(Exception e)

{

System.err.println((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

throw new Exception((new StringBuilder()).append("inside uploadUpdateACtion while writing the uploded file Exception is [").append(e.getMessage()).append("]").toString());

}




}

Sunday, November 7, 2010

load sub tables data without using hibernate lazy="false"

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class StudentDaoHibernateImpl extends HibernateDaoSupport implements StudentDao {

public Student getStudent(long studentId) thows StudentRetrieveException {
try {
//get hibernate session
Criteria crit = getSession().createCriteria(Student.class);
//join sub table
crit.setFetchMode("Subject", FetchMode.JOIN);
//filter student
crit.add(Restrictions.eq("studentId", studentId));
//create alias
crit.createAlias("Subject","sub");
//order by subject ID
crit.addOrder(Order.asc("sub.subjectId"));
//return result
return (Student) crit.uniqueResult();
} catch (HibernateException e) {
throw new StudentRetrieveException("Student Retrieve Problem",e);
}
}

}

Thursday, May 13, 2010

Simple Spring & Hibernate Example

Needed lib
==========

hibernate3.jar
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
hibernate3.jar
jstl.jar
jta.jar
log4j-1.2.11.jar
mysql-connector-java-3.0.9-stable-bin.jar
spring.jar
standard.jar
spring.tld



1. Configure 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">



<display-name>Test</display-name>

<description>Spring Base Application</description>



<context-param>

<param-name>contextConfigLocations</param-name>

<param-value>

/WEB-INF/applicationContext.xml

</param-value>

</context-param>



<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>



<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>



<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>*.htm</url-pattern>

</servlet-mapping>





<welcome-file-list>

<welcome-file>

index.html

</welcome-file>

</welcome-file-list>



</web-app>







 



2.Configure Spring-Servlet XML

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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">



<beans>



<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">

<property name="order" value="1"/>

</bean>



<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="configLocation" value="classpath:hibernate.cfg.xml" />

</bean>




<bean name="/userLogin.htm" class="web.controllers.UserLoginController">

<property name="managerService" ref="managerService"/>

</bean>





<bean id="saveUserValidator" class="web.validators.SaveUserValidator"/>





<bean id="addUserController" class="web.controllers.AddUserController">

<property name="sessionForm" value="false"/>

<property name="bindOnNewForm" value="false"/>

<property name="commandName" value="user"/>

<property name="commandClass" value="domain.User"/>

<property name="validator" ref="saveUserValidator"/>

<property name="formView" value="AddUser"/>

<property name="managerService" ref="managerService"/>

<property name="sessionFactory" ref="sessionFactory"/>

</bean>



<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

<property name="basename" value="messages"/>

</bean>



<bean id="signonInterceptor" class="web.controllers.SignonInterceptor"/>





<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

<property name="exceptionMappings">

<props>



<prop
key="org.springframework.dao.DataIntegrityViolationException">dberror</prop>

<prop key="org.hibernate.HibernateException">dberror</prop>

<prop key="java.lang.RuntimeException">dberror</prop>

<prop key="org.apache.jasper.JasperException">dberror</prop>

<prop key="javax.servlet.ServletException">dberror</prop>



</props>

</property>

</bean>



<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="order" value="2"/>



<property name="interceptors">

<list>

<ref bean="signonInterceptor"/>

</list>

</property>



<property name="mappings">

<props>





<prop key="/AddUser.htm">addUserController</prop>







</props>

</property>

</bean>



<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">

<property name="basename" value="views"/>

</bean>

</beans>

 



3.Configure AppicationContext XML


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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">



<beans>



<!-- ========================= GENERAL DEFINITIONS ========================= -->



<!-- Transactional proxy for the primary business objects -->

<bean id="managerService" class="org.springframework.aop.framework.ProxyFactoryBean">

<property name="target">

<ref local="managerServiceTarget"/>

</property>

<property name="proxyTargetClass" value="false"/>

<property name="proxyInterfaces">

<list>

<value>service.ManagerService</value>

</list>

</property>

</bean>



<!-- DAO -->

<bean id="userDao" class="dao.hibernate.UserDaoHibernateImpl"/>





<!-- Business Objects -->

<bean id="managerServiceTarget" class="service.ManagerServiceImpl">



<property name="userDao" ref="userDao"/>





</bean>



















</beans>

 




4. Hibernate Configuration

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

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

<property name="connection.datasource">java:PostgresDS</property>


 <!--<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>-->

<!--<property name="connection.url">jdbc:oracle:thin:@serverip:port:sid</property>-->

<!--<property name="connection.username">xxxx</property>-->

<!--<property name="connection.password">xxxx</property>-->




<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

<property name="hibernate.c3p0.max_size">20</property>

<property name="hibernate.c3p0.min_size">5</property>

<property name="hibernate.c3p0.timeout">300</property>

<property name="hibernate.c3p0.max_statements">50</property>

<property name="hibernate.c3p0.idle_test_period">3000</property>



<!-- print SQL to stdout -->

<property name="show_sql">false</property>

<property name="format_sql">false</property>





<mapping resource="domain/user.hbm.xml"/>





</session-factory>

</hibernate-configuration>





5.AddUser.jsp

<%@ taglib prefix="spring" uri="spring.tld" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>



<head><link rel="stylesheet" href="pop_style.css"></link>

<title>Welcome to Clinic Portal</title>



<style type="text/css">

</style>







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

</head>

<body onload="document.my.username.focus();" onkeydown="" leftmargin="0"
topmargin="0" rightmargin="0" bottommargin="0" class="optionsTop">



<table width="100%" height="0" border="0" style="border-collapse: collapse"
cellpadding="0" cellspacing="0">



<tr>

<td width="1%" height="30" align="left" background="Images/titleMiddle.gif"
class="titles">

<img src="Images/titleCorner.gif" width="30" height="30" border="0"></td>

<td valign="middle" background="Images/titleMiddle.gif" class="titles">

<p style="margin-right:10">

<strong><font face="Times New Roman, Times, serif" color="#000099">Add
User</font></strong></p></td>

</tr>





<br>

<form name="my" id="my" method="post" >

<table border="0" width="59%" height="100" align="center" class="bodyTable">

<tr>

<td height="10" valign="top"> <div align="center">

<spring:hasBindErrors name="user"><font color="red">

<b><fmt:message key="addUser.error.heading"/></b></font>

</spring:hasBindErrors>

<br>

</div>

</td>

</tr>

<tr>

<td class="rowgrey">

<spring:bind path="user.username">User Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="username" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.firstName">First Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="firstName" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.lastName">Last Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td>

<td width="477" align="left" class="rowgrey"><input size="40" type="text"
value="${status.value}" name="lastName" >

<font color="red">${status.errorMessage}</font>

</spring:bind>

</td>

</tr>



<tr>

<td class="rowgrey"><spring:bind path="user.userpwd">Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td><td width="477" align="left" class="rowgrey">

<input type="password" value="${status.value}" size="40" id="userpwd"
name="userpwd" >

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.userpwd">Confirm
Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
:</td><td width="477" align="left" class="rowgrey">

<input type="password" value="${status.value}" id="pwd" size="40" name="pwd" >

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>

<tr>

<td class="rowgrey"><spring:bind path="user.usertype"> User
Type&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp; :</td>

<td width="477" align="left" class="rowgrey">

<select name="usertype" >

<option value="A">Administrator</option>

<option value="U">User</option>

</select>

<font color="red">${status.errorMessage}</font>

</spring:bind> </td>

</tr>







<tr>

<td
class="rowgrey">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</td>

<td width="477" align="left" class="rowgrey">

<input type="submit" id="submit" name="submit" class="buttons" value="Add User">

</td>

</tr>









</table>



</form>



<p><b>&nbsp;</b></p>







</body>



<script type="text/javascript" language="JavaScript1.2"
src="pop_events.js"></script>

</html>




6.Configure views.properties file

Home.class=org.springframework.web.servlet.view.JstlView
Home.url=/WEB-INF/jsp/home.jsp

AddUser.class=org.springframework.web.servlet.view.JstlView
AddUser.url=/WEB-INF/jsp/AddUser.jsp

7.configure messages.properties File

addUser.title=Add User page
addUser.error.heading=Please fix all the errors!
addUser.error.username.missing=The User Name field is missing
addUser.error.userpwd.missing=The password field is missing
addUser.error.usertype.missing=The Usertype is missing

8.DAO Class





package dao.hibernate;





import java.util.List;

import java.util.ArrayList;



import org.apache.log4j.Logger;

import org.apache.log4j.Level;

import org.hibernate.*;

import org.hibernate.criterion.Restrictions;

import org.hibernate.criterion.Expression;





import domain.User;

import dao.UserDao;





public class UserDaoHibernateImpl implements UserDao

{

public void saveUser(User user)throws HibernateException {

Session session = null;

Transaction tx = null;



try {

// Open a new session or get the current session

session = SessionProvider.currentSession();

// Begin the transaction

tx = session.beginTransaction();

session.saveOrUpdate(user);

//SessionProvider.closeSession();

// Commit the transaction

tx.commit();

SessionProvider.closeSession();

tx = null;



} catch( HibernateException e ) {

try{

tx.rollback();



} catch (HibernateException cannotRollback) {



// log this error

}



throw e;

//e.printStackTrace();



} finally {



// Close the session

if (session != null) SessionProvider.closeSession();



}





}





public void updateUser(User user1)throws HibernateException {

Session session = null;

Transaction tx = null;



try {

// Open a new session or get the current session

session = SessionProvider.currentSession();

// Begin the transaction

tx = session.beginTransaction();



User loaduser = (User) session.load(User.class, user1.getUserId(),
LockMode.UPGRADE);

loaduser.setUserId( user1.getUserId() );

loaduser.setStatus(user1.getStatus());

//loaduser.setUsername();

loaduser.setUserpwd(user1.getUserpwd());

loaduser.setUsertype(user1.getUsertype());

loaduser.setFirstName(user1.getFirstName());

loaduser.setLastName(user1.getLastName());

session.update(loaduser);

tx.commit();

SessionProvider.closeSession();



// Commit the transaction



tx = null;



} catch( HibernateException e ) {

try{

tx.rollback();



} catch (HibernateException cannotRollback) {



// log this error

}



throw e;

// e.printStackTrace();



} finally {



if (session != null) SessionProvider.closeSession();



}



}



public User getUser(String userName) throws HibernateException {

// Open a new session or get the current session

Session session = SessionProvider.currentSession();

User loaduser = new User();



try{

//loaduser = (user) session.get(user.class, userName);

Criteria crit = session.createCriteria(User.class);

crit.add(Restrictions.eq("username",userName));

crit.setMaxResults(1);

loaduser=(User) crit.uniqueResult();





} catch(HibernateException unexpected){



throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return loaduser;

}





public List getAllUser() throws HibernateException {

// Open a new session or get the current session

Session session = SessionProvider.currentSession();

List results =new ArrayList();



try{



Criteria crit = session.createCriteria(User.class);

results=crit.list();



} catch(HibernateException unexpected){

throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return results;



}



public void deleteUser(int jobid) throws HibernateException {



Session session = SessionProvider.currentSession();

try{

Transaction tx = session.beginTransaction();

User mm = loaduser(jobid);

session.delete( mm );

tx.commit();

}catch (Exception e){

e.printStackTrace();

}finally{

if (session != null) SessionProvider.closeSession();

}



}



public User loaduser( int id )throws HibernateException {

Session session = SessionProvider.currentSession();

User loaduser=new User();

try{

loaduser= (User) session.load(User.class, id );

}catch (Exception e){

e.printStackTrace();

}finally{

if (session != null) SessionProvider.closeSession();

}

return loaduser;

}



public List searchUser(String userName){

Session session = SessionProvider.currentSession();

List results = null;



try{



Criteria crit = session.createCriteria(User.class);

crit.add(Expression.like( "username","%"+userName.toUpperCase()+"%" ) );

results=crit.list();







} catch(HibernateException unexpected){

throw unexpected;



} finally{



if (session != null) SessionProvider.closeSession();

}



return results;



}



}



 



9. SessionProvider.class


package dao.hibernate;



import org.hibernate.cfg.Configuration;

import org.hibernate.SessionFactory;

import org.hibernate.Session;

import org.hibernate.FlushMode;

import org.hibernate.HibernateException;







public class SessionProvider

{

private static final SessionFactory sessionFactory;

public static final ThreadLocal session = new ThreadLocal();

private static int dbSessionCount;







static

{

try

{





sessionFactory = new
Configuration().configure("hibernate.cfg.xml").buildSessionFactory();



}

catch (HibernateException ex)

{

ex.printStackTrace();

throw new RuntimeException("Exception building SessionFactory: " +

ex.getMessage(), ex);

}

}





public static Session currentSession() throws HibernateException

{

Session s = (Session) session.get();

//System.out.println("--------------CurrentSession------------"+dbSessionCount);





if (s == null)

{

dbSessionCount++;

s = sessionFactory.openSession();



System.out.println("--------------OpenSession------------"+dbSessionCount);

s.setFlushMode(FlushMode.COMMIT);

session.set(s);





}

return s;

}



public static void closeSession() throws HibernateException

{

Session s = (Session) session.get();

session.set(null);



if (s != null)

{

dbSessionCount--;

s.close();



System.out.println("--------------ClosedSession------------"+dbSessionCount);



}

}

}



 



10.ManagerServiceImpl.java

/*

* JStockManager Project

*/

package service;



import java.util.List;

//

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

//

//



import dao.*;

import domain.*;





public class ManagerServiceImpl implements ManagerService {



private Log logger = LogFactory.getLog(this.getClass());







private UserDao userDao;







public void setUserDao(UserDao UserDao) {

this.userDao = UserDao;

}









// insert
-----------------------------------------------------------------------------------------------







public void saveUser(User user) throws Exception {

this.logger.info("entering method saveUser");



try {

userDao.saveUser(user);





} catch (Exception e) {

String msg = "Could not saveUser " + e.toString();

this.logger.error(msg, e);

throw e;



}

}







// update
-----------------------------------------------------------------------------------------------







public void updateUser(User user) throws Exception {

this.logger.info("entering method updateUser");



try {

this.userDao.updateUser(user);

} catch (Exception e) {

String msg = "Could not updateUser";

this.logger.error(msg, e);

throw e;



}

}





// delete
-----------------------------------------------------------------------------------------------







public void deleteUser(int userid) {

this.logger.info("entering method deleteUser");



try {

this.userDao.deleteUser(userid);

} catch (Exception e) {

String msg = "Could not deleteUser";

this.logger.error(msg, e);





}

}





// get
-----------------------------------------------------------------------------------------









public User getUser(String userName) {

this.logger.info("entering method getUser");

try {

return this.userDao.getUser(userName);

} catch (Exception e) {

String msg = "Could not getUser for id of " + userName;

this.logger.error(msg, e);

return null;



}

}







// get
all----------------------------------------------------------------------------------









public List getAllUser() {

this.logger.info("entering method getAllUser");

try {

return this.userDao.getAllUser();

} catch (Exception e) {

String msg = "Could not getAllUser products";

this.logger.error(msg, e);

return null;



}

}







//search-----------------------------------------------------------------------





public List searchUser(String userName){

this.logger.info("entering method searchUser");

try {

return this.userDao.searchUser(userName);

} catch (Exception e) {

String msg = "Could not searchSuplier products";

this.logger.error(msg, e);

return null;



}



}





//-----------------------------------------------------------



}





 



11.SaveUserValidator.java

package web.validators;



import org.springframework.validation.Errors;

import org.springframework.validation.Validator;

import domain.User;





public class SaveUserValidator implements Validator

{

public boolean supports(Class checkMe)

{

return checkMe.equals(User.class);

}



public void validate(Object object, Errors errors)

{

User user1 = (User) object;



if (user1 == null)

{

errors.rejectValue("user", "SaveUser.error.novalue",

"Value required.");

}



String name= "";

String pwd = "";

String type="";

String firstName="";

String lastName="";



if(user1!=null){

name= user1.getUsername();

pwd = user1.getUserpwd();

type=user1.getUserType();

firstName=user1.getFirstName();

lastName=user1.getLastName();

}







if ((name == null) || (name.length() < 1))

{

errors.rejectValue("username", "SaveUser.error.name.missing",

"name is missing.");

}

if ((firstName == null) || (firstName.length() < 1))

{

errors.rejectValue("firstName", "SaveUser.error.name.missing",

"first Name is missing.");

}

if ((lastName == null) || (lastName.length() < 1))

{

errors.rejectValue("lastName", "SaveUser.error.name.missing",

"last Name is missing.");

}

if ((pwd == null) || (pwd.length() < 1))

{

errors.rejectValue("userpwd", "SaveUser.error.name.missing",

"pwd is missing.");

}

if ((type== null) || (type.length() < 1))

{

errors.rejectValue("usertype", "SaveUser.error.name.missing",

"type is missing.");

}









}

}







 



12.AddUserController.java

package web.controllers;



import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;



import java.util.HashMap;

import java.util.Map;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;





import service.ManagerService;

import domain.User;





public class AddUserController extends SimpleFormController

{



private ManagerService ManagerService;

private String name;

private String ip;

private String serverMsg="";



public void setManagerService(ManagerService ManagerService) {

this.ManagerService = ManagerService;

}







public ModelAndView onSubmit(Object object) {

try{

User user1 = (User)object;

user1.setStatus(1);

user1.setUserpwd(user1.getUserpwd());



ManagerService.saveUser(user1);



}

catch(Exception e)

{



e.printStackTrace();

serverMsg=e.getCause().getMessage();

}



return new ModelAndView("Home");



}





protected Map referenceData(HttpServletRequest request)

throws ServletException

{

Map refData = new HashMap();

try{





UserSession user = (UserSession)
request.getSession(true).getAttribute("userSession");

name = user.getName();

ip = user.getIp();



}

catch(Exception e)

{

e.printStackTrace();

}

return refData;

}



}







 



13.SignonInterceptor.java

package web.controllers;



import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.apache.log4j.BasicConfigurator;



import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.ModelAndViewDefiningException;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import org.springframework.web.util.WebUtils;



public class SignonInterceptor extends HandlerInterceptorAdapter {



public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler)

throws Exception {





UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");



if (userSession == null) {





request.setAttribute("exception","User has LogOut Please Login!");

response.sendRedirect("errorPage.jsp");

return false;

}

else {



return true;

}

}



}









 



14.UserLoginController.java





package web.controllers;



import domain.User;





import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.apache.log4j.Level;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

import service.ManagerService;

import Utility.Constants;





public class UserLoginController

implements Controller {



private ManagerService ManagerService;

Logger logger;



public UserLoginController() {



}



public void setManagerService(ManagerService managerService) {

this.ManagerService = managerService;

logger = Logger.getLogger("web/controllers/UserLoginController");

logger.setLevel(Level.ALL);

}



public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {





String username = "gayan";

String password = "123";

String utype = "A";

int state = 0;

String name = "";

String place = "";

String type_ = "";

String dbPassword = "";

String ip = request.getRemoteAddr().trim();

System.out.println("---------------Attempt to login---------" + utype);

UserSession userSession = new UserSession();

userSession.setName(name);

userSession.setPlace(place);

userSession.setType_(type_);

userSession.setIp(ip);

userSession.setPwd(dbPassword);

request.getSession(true).setAttribute("userSession", userSession);

// ManagerService.getUser(username);

System.out.println("---------------Succesfull login---------" + utype);





return new ModelAndView("Home");

}



}











 




15.UserSession.java


package web.controllers;







public class UserSession {



private String name;

private String ip;

private String place; // user's place

private String type_; // to identify the what kind of user is trying to login

private String pwd;



public String getPwd() {

return pwd;

}



public void setPwd(String pwd) {

this.pwd = pwd;

}









public void setName(String name) {

this.name = name;

}



public void setIp(String ip) {

this.ip = ip;

}



public void setPlace(String place) {

this.place = place;

}



public void setType_(String type_) {

this.type_ = type_;

}





public UserSession() {



}



public String getName() {

return name;

}

public String getType_() {

return type_;

}

public String getPlace() {

return place;

}

public String getIp() {

return ip;

}





}













 



16.User.java



package domain;



import java.io.Serializable;



/**

* Category business object.

*

* @author <a href="mailto:gayand@ceit.pdn.ac.lk">Gayan Dissanayake</a>

*/

public class User implements Serializable {



private int userId;

private String username;

private String userpwd;

private int status;

private String usertype;

private String firstName;

private String lastName;



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;

}







public int getUserId() {

return userId;

}



public void setUserId(int userId) {

this.userId = userId;

}







public String getUserpwd() {

return userpwd;

}



public void setUserpwd(String userpwd) {

this.userpwd = userpwd;

}







public int getStatus() {

return status;

}



public void setStatus(int status) {

this.status = status;

}







public String getUsertype() {

return usertype;

}



public void setUsertype(String usertype) {

this.usertype = usertype;

}





/**

* Default constructor.

*/

public User() {

}









public String getUserType() {

return this.usertype;

}



public void setUserType(String usertype) {

this.usertype = usertype;

}



public String getUsername() {

return this.username;

}



public void setUsername(String newUsername) {

this.username = newUsername;

}





}















 



17.user.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

<class name="domain.User" table="user">

<id name="userId" column="userId" type="int">

<generator class="native"/>

</id>

<property name="username" column="username" type="java.lang.String"/>

<property name="userpwd" column="userpwd" type="java.lang.String"/>

<property name="status" column="status" type="int"/>

<property name="usertype" column="usertype" type="java.lang.String"/>

<property name="firstName" column="firstName" type="java.lang.String"/>

<property name="lastName" column="lastName" type="java.lang.String"/>

</class>

</hibernate-mapping>

















 



18.postgres-ds.xml


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



<!-- ===================================================================== -->

<!-- -->

<!-- JBoss Server Configuration -->

<!-- -->

<!-- ===================================================================== -->



<!-- $Id: postgres-ds.xml,v 1.3 2004/09/15 14:37:40 loubyansky Exp $ -->

<!-- ==================================================================== -->

<!-- Datasource config for Postgres -->

<!-- ==================================================================== -->





<datasources>

<local-tx-datasource>

<jndi-name>PostgresDS</jndi-name>

<connection-url>jdbc:postgresql://localhost/astro</connection-url>

<driver-class>org.postgresql.Driver</driver-class>

<user-name>postgres</user-name>

<password>mysql</password>

<!-- sql to call when connection is created

<new-connection-sql>some arbitrary sql</new-connection-sql>

-->



<!-- sql to call on an existing pooled connection when it is obtained from pool


<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>

-->



<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->

<metadata>

<type-mapping>PostgreSQL 7.2</type-mapping>

</metadata>

</local-tx-datasource>



<local-tx-datasource>

<jndi-name>PostgresDS1</jndi-name>

<connection-url>jdbc:postgresql://localhost/starfriends</connection-url>

<driver-class>org.postgresql.Driver</driver-class>

<user-name>postgres</user-name>

<password>mysql</password>

<!-- sql to call when connection is created

<new-connection-sql>some arbitrary sql</new-connection-sql>

-->



<!-- sql to call on an existing pooled connection when it is obtained from pool


<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>

-->



<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->

<metadata>

<type-mapping>PostgreSQL 7.2</type-mapping>

</metadata>

</local-tx-datasource>





</datasources>