Spring And JSF with Hibernate Demo

Spring + Hibernate + JSF

Use following SQL Script to create table:


CREATE TABLE `products` (
`productId` int(8) NOT NULL,
`description` varchar(250) DEFAULT NULL,
`name` varchar(30) DEFAULT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`productId`)
);

Sample Data :

| productId | description | name | price |
| 1 | Operating System for 128 Bit Systems | Mahendra OS 1.1 | 123000 |
| 2 | Office productivity Suite | Mahendra Office 2.0.1 | 63000 |
| 3 | IDE for Developing C,C++ and Java Applications | Mahendra IDE 2.3 | 543000 |

Frameworks Used:

Presentation Tier JSF 2.2
Business Tier Spring 3.1
Data Access Tier Hibernate 3

Dependencies [Actual JAR files]

  1. Hibernate 3

    • annotations-api.jar
    • cglib-2.2.jar
    • commons-collections.jar
    • commons-logging-1.1.1.jar
    • dom4j-1.6.1.jar
    • hibernate-jpa-2.0-api-1.0.0.Final.jar
    • hibernate3.jar
    • javassist-3.12.0.GA.jar
    • jta-1.1.jar
    • slf4j-api-1.6.1.jar
    • slf4j-simple-1.6.1.jar
  2. Spring 3

    • org.springframework.beans-3.1.0.M2.jar
    • org.springframework.context-3.1.0.M2.jar
    • org.springframework.context.support-3.1.0.M2.jar
    • org.springframework.core-3.1.0.M2.jar
    • org.springframework.expression-3.1.0.M2.jar
    • org.springframework.orm-3.1.0.M2.jar
    • org.springframework.transaction-3.1.0.M2.jar
    • org.springframework.web-3.1.0.M2.jar
    • org.springframework.jdbc-3.1.0.M2.jar
  3. Spring declarative Transactions

    • aopalliance-1.0.jar
    • asm-3.1.jar
    • org.springframework.aop-3.1.0.M2.jar
    • org.springframework.asm-3.1.0.M2.jar
  4. JSF 2.1

    • javax.faces-2.1.13.jar
    • jstl-1.2.jar
  5. JDBC Driver

    • mysql-connector-java-5.1.10-bin.jar

Create New Dynamic Web Project using eclipse with Apache Tomcat 6.0

Edit web.xml file to enable Spring

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

Modify faces-config.xml to enable Spring EL inside JSF

<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>

Create hibernate.cfg.xml file inside ‘src’ folder

<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mahendra</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.mahendra.models.Product"/>
</session-factory>
</hibernate-configuration>

Create applicationContext.xml inside ‘WEB-INF’ folder

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:annotation-driven />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="ht" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id=”transactionManager”
class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean>

<bean id=”dao” class=”com.mahendra.springbeans.ProductDAO”>
<property name=”template” ref=”ht” />
</bean>
</beans>

create: Product.java


package com.mahendra.models;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.persistence.*;

@ManagedBean @RequestScoped
@Entity @Table(name=”products”)
public class Product {

@Id private Integer productId;
private String name;
private String description;
private double price;
//generate getters and setters…
}

create : ProductDAO.java


package com.mahendra.springbeans;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mahendra.models.Product;

@Service
public class ProductDAO {

private HibernateTemplate template;
private static Logger log = Logger.getLogger(ProductDAO.class.getName());
public HibernateTemplate getTemplate() {
return template;
}

public void setTemplate(HibernateTemplate template) {
this.template = template;
}

@Transactional
public void save(Product p){
log.info(“Preparing to save product “+p.getName());
template.save(p);

log.info(“Product “+p.getName()+ ” saved”);
}

@Transactional(readOnly=true)
public List findAll(){
List pl = null;
log.info(“Reading products from database”);
pl = template.loadAll(Product.class);
return pl;
}
}

Create ProductBean.java


package com.mahendra.jsfbeans;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import com.mahendra.models.Product;
import com.mahendra.springbeans.ProductDAO;
import java.util.logging.*;

@ManagedBean @ApplicationScoped
public class ProductBean {
private Product product;
private static Logger log = Logger.getLogger(ProductBean.class.getName());

private List productList;

@ManagedProperty(value=”#{dao}”)
private ProductDAO dao;

public Product getProduct() {
return product;
}

public void saveAction(){
log.info(“Saving product”);
dao.save(product);
listAction();
}

@PostConstruct
public void listAction(){
log.info(“Getting all products”);
setProductList(dao.findAll());
}

public void setProduct(Product product) {
this.product = product;
}

public List getProductList() {
return productList;
}

public void setProductList(List productList) {
this.productList = productList;
}

public ProductDAO getDao() {
return dao;
}

public void setDao(ProductDAO dao) {
this.dao = dao;
}
}

Create / Modify index.xhtml

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221;
xmlns:ui=”http://java.sun.com/jsf/facelets&#8221;
xmlns:h=”http://java.sun.com/jsf/html&#8221;
xmlns:f=”http://java.sun.com/jsf/core”&gt;
<head>
<title>Mahendra’s Spring + Hibernate + JSF Demo</title>
</head>
<body>
<h:form>
<h2>Add new product</h2>
<h:panelGrid columns=”2″>
<h:outputLabel value=”Product ID” for=”pid”/>
<h:inputText id=”pid” value=”#{product.productId}”/>
<h:outputLabel value=”Product Name” for=”pn”/>
<h:inputText id=”pn” value=”#{product.name}”/>
<h:outputLabel value=”Description” for=”pd”/>
<h:inputTextarea cols=”25″ rows=”3″ id=”pd” value=”#{product.description}”/>
<h:outputLabel value=”Price” for=”pc”/>
<h:inputText id=”pc” value=”#{product.price}”/>
<h:commandButton value=”Save” action=”#{productBean.saveAction}” >
<f:setPropertyActionListener value=”#{product}” target=”#{productBean.product}”/>
</h:commandButton>
</h:panelGrid>
</h:form>
<h2>List of Existing Products</h2>
<h:form>
<h:dataTable var=”p” value=”#{productBean.productList}”>
<h:column>
<f:facet name=”header”>Product ID</f:facet>
<h:outputText value=”#{p.productId}”/>
</h:column>
<h:column>
<f:facet name=”header”>Name</f:facet>
<h:outputText value=”#{p.name}”/>
</h:column>
<h:column>
<f:facet name=”header”>Description</f:facet>
<h:outputText value=”#{p.description}”/>
</h:column>
<h:column>
<f:facet name=”header”>Price</f:facet>
<h:outputText value=”#{p.price}”/>
</h:column>
</h:dataTable>
</h:form>
</body>
</html>

Advertisements

Simple Expense Manager (Console App for Java)

The theme of this app is “Maintaining records of personal expenses.

User can record all his/her daily expenses and his/her money in wallet.

this is very small app just to test JAVA as programming language.

The entire app is divided into few components (classes)

com.mahendra.Wallet:   class to encapsule user info (name and balance)

package com.mahendra;

public class Wallet implements java.io.Serializable {
private String userName;
private float amount;
public Wallet(String userName, float amount) {
super();
this.userName = userName;
this.amount = amount;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
@Override
public String toString() {
return userName+" you have Rs. "+amount+" in your wallet";
}
}

com.mahendra.Expense: model component (entity) to encapsulate details of single transaction(expense).

package com.mahendra;
public class Expense {
    private String date;
    private String details;
    private float amount;

    public String getDetails() {
        return details;
    }
    public void setDetails(String details) {
        this.details = details;
    }
    public float getAmount() {
        return amount;
    }
    public void setAmount(float amount) {
        this.amount = amount;
    }
    public Expense(String date,String details, float amount) {
        super();        
        this.date = date;
        this.details = details;
        this.amount = amount;
    }        
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String toString(){
        return date+";"+details+";"+amount;
    }
}

com.mahendra.DataManager:  class to handle data storing and retrieval

package com.mahendra;

import java.io.*;
import java.util.LinkedList;

public class DataManager {
    private String wpath = "d:/data/wallet.dat";
    private String tpath = "d:/data/trans.dat";
    private Wallet w;

    public DataManager(Wallet w) throws ApplicationException {
        this.w = w;
        verifyFolder();
    }

    public DataManager() throws ApplicationException {
        verifyFolder();
    }

    private void verifyFolder() throws ApplicationException {
        File file0 = new File("D:/data");
        if (!file0.exists())
            file0.mkdir();
        File file1 = new File(wpath);
        if (file1.exists())
            w = getWallet();

    }

    public void addExpense(String details, float amt)
            throws ApplicationException {
        Expense e = new Expense(new java.util.Date().toString(), details, amt);
        PrintStream pw = null;
        try {
            pw = new PrintStream(new FileOutputStream(tpath, true));
            withdrawFromWallet(amt);
            pw.println(e);
        } catch (IOException e1) {
            throw new ApplicationException("unable to write transactions");
        } finally {
            pw.close();
        }
    }

    public LinkedList<Expense> listExpenses() throws ApplicationException {
        LinkedList<Expense> expenses = new LinkedList<Expense>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(tpath));
            String line = br.readLine();
            while (line != null) {
                String[] fields = line.split(";");
                Expense e = new Expense(fields[0], fields[1],
                        Float.parseFloat(fields[2]));
                expenses.add(e);
                line = br.readLine();
            }
        } catch (IOException ex) {
            throw new ApplicationException("Unable to read transactions: "
                    + ex.getMessage());
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {
            }
        }
        return expenses;
    }

    public Wallet getWallet() throws ApplicationException {
        try {
            ObjectInputStream op = new ObjectInputStream(new FileInputStream(
                    wpath));
            Object obj = op.readObject();
            Wallet w = (Wallet) obj;
            this.w = w;
            op.close();
            return w;
        } catch (FileNotFoundException fe) {
            throw new ApplicationException(
                    "Data file not found/No datafile created yet!");
        } catch (IOException ex) {
            throw new ApplicationException("Error while reading file: "
                    + ex.getMessage());
        } catch (ClassNotFoundException cx) {
            throw new ApplicationException(
                    "Invalid datafile/data inside file is modified!");
        }
    }

    public void addMoneyToWallet(float amt) throws ApplicationException {
        updateWallet(w.getUserName(), w.getAmount() + amt);
    }

    public void withdrawFromWallet(float amt) throws ApplicationException {
        float t = w.getAmount() - amt;
        if (t < 0)
            throw new ApplicationException(
                    "No enough cash available in your wallet!!!");
        updateWallet(w.getUserName(), w.getAmount() - amt);
    }

    public void updateWallet(String name, float a) throws ApplicationException {
        try {
            ObjectOutputStream op = new ObjectOutputStream(
                    new FileOutputStream(wpath));
            w = new Wallet(name, a);
            op.writeObject(w);
            op.close();
            File file = new File(tpath);
            file.delete();
        } catch (FileNotFoundException e) {
            throw new ApplicationException(
                    "Data file not found/Data file may be DELETED!");
        } catch (IOException e) {
            throw new ApplicationException("Error while writing datafile : "
                    + e.getMessage());
        }
    }
}

com.mahendra.UserIO:  class to perform all user input/output operations

package com.mahendra;

import java.io.*;
import java.util.LinkedList;

public class UserIO {
    private DataManager man = null;
    private BufferedReader br = null;

    public UserIO()throws ApplicationException
    {
        br = new BufferedReader(new InputStreamReader(System.in));
        man = new DataManager();
    }

    public void createWallet()
    {
        String name;
        float amt;        
        try{
        System.out.println("Enter your name: ");
        name = br.readLine();
        System.out.println("Enter your balance: ");
        amt = Float.parseFloat(br.readLine());
        man.updateWallet(name, amt);
        }catch(IOException ex){    }
        catch(ApplicationException ae){
            System.out.println("Could not create new wallet");
            System.out.println("Error: "+ae.getMessage());
        }
        System.out.println("\n\n\n\n\n\n\n\n\n");
        getKey();
    }
    public void addExpense()
    {
        try{
        System.out.print("\nEnter details of expenses: ");
        String details = br.readLine();
        System.out.print("\nEnter amount: ");
        float amt = Float.parseFloat(br.readLine());        
        man.addExpense(details, amt);
        }catch(IOException ex){}
        catch(ApplicationException ap){
            System.out.println("Error: "+ap.getMessage());
        }
        System.out.println("\n\n\n\n\n\n\n\n\n");
        getKey();
    }
    public void listExpenses(){        
        LinkedList<Expense> exps = null;
        try {
            exps = man.listExpenses();
        } catch (ApplicationException e1) {
            System.out.println("Error: "+e1.getMessage());
        }
        if(exps==null || exps.size()==0)
        {
            System.out.println("No Expenses made so far?");
            return;
        }        
        String h1 = " Date/Time ";
        String h2 = " Details ";
        String h3 = " Amount ";
        System.out.printf("%n%-32s|%-25s|%15s%n",h1,h2,h3);        
        for(Expense e:exps){
            System.out.println("--------------------------------+-------------------------+---------------------");
            System.out.printf("%-31s |%-24s | %12.2f%n",e.getDate(),e.getDetails(),e.getAmount());            
        }
        System.out.println("--------------------------------------------------------------------------------");
        getKey();
    }
    public void displayWallet()
    {
        System.out.println("----- Wallet Info -----------------");
        Wallet w;
        try {
            w = man.getWallet();
            System.out.println("\nName of User : "+w.getUserName());
            System.out.println("\nBalance      : "+w.getAmount());
        } catch (ApplicationException e) {
            System.out.println("\nError: "+e.getMessage());
        }                
        System.out.println("-----------------------------------");
        System.out.println("\n\n\n\n\n\n\n\n\n");
        getKey();
    }

    public void depositCash(){
        System.out.println("Enter amount to be deposited: ");
        try {
            float amt = Float.parseFloat(br.readLine());
            man.addMoneyToWallet(amt);
        } catch (NumberFormatException e) {
                System.out.println("Error: Please enter amount in digits only");
        } catch (IOException e) {}
        catch(ApplicationException ae){
            System.out.println("Error: "+ae.getMessage());
            System.out.println("Amount NOT deposited!");
        }
        getKey();
    }
    public char getOption(){
        String line = null;
            try {
                line=br.readLine();                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            line.toUpperCase();
            return line.charAt(0);            
    }
    private void getKey(){
        try {
            System.out.println("\n\n\n\n\n\n\nPress any key to continue...");
            br.readLine();
        } catch (IOException e) {

        }
    }
}

com.mahendra.ApplicationException:  a User-defined exception that will wrap all built-in exceptions

package com.mahendra;

public class ApplicationException extends Exception {
    public ApplicationException(String message){
        super(message);
    }
}

com.mahendra.MyWallet:   entry point for my application.

package com.mahendra;

public class MyWallet {

    /**
     * @param args
     */
    public static void main(String[] args) {        
        UserIO io = null;
        System.out.println("--------------- Mahendra's Wallet Manager --------------");
        System.out.print("Starting up....");        
        try {
            io = new UserIO();
        } catch (ApplicationException e) {            
            System.out.print("\rError: "+e.getMessage());
            System.out.println("Application is Shutting down...");
            return;
        }
        try {
            Thread.sleep(700);
        } catch (InterruptedException e) {    }        
        System.out.print("\rStarted Successfuly\n");
        while(true){
            System.out.println("   Menu");
            System.out.println("   ----------------------------");
            System.out.println("     Key    Description");
            System.out.println("   ----------------------------");
            System.out.println("     C      Create new Wallet");
            System.out.println("     I      Get Wallet Info");
            System.out.println("     A      Add new expense");
            System.out.println("     L      List all expenses");
            System.out.println("     D      Deposit amount");
            System.out.println("     X      Exit Application");
            System.out.println("\n\n\n\n\n\n\n\n\n\n\n----------------------------");
            System.out.print("   Your option: ");
            char ch = io.getOption();
            switch(ch){
            case 'C':
            case 'c':
                io.createWallet();
                break;
            case 'I':
            case 'i':
                io.displayWallet();
                break;
            case 'A':
            case 'a':
                io.addExpense();
                break;
            case 'D':
            case 'd':
                io.depositCash();
                break;
            case 'L':
            case 'l':
                io.listExpenses();
                break;
            case 'X':
            default:
                return;
            }            
        }
    }
}