Monday, September 10, 2012

Working with Spring 3.

Hi All,
Staring with Spring 3, The Spring API needs to included in the project, please download Spring 3 Framework libraries and add to the referenced libraries of project.


Create JAVA project with following structure,



In Spring, spring configuration file acts as a controller of the application,
here we created the "Spring3HelloWorld.xml" as a spring controller, which include the bean tag followed by root tag which might be contains multiple bean references, for example now we are including only tow beans as a refernce,
Here the same bean id associated with the bean class.

Spring3HelloWorld.xml
Spring3HelloWorld.xml

Now we created two beans,

Spring3HelloWorld.java
package spring.com;

public class Spring3HelloWorld {
   
    public void sayHello(){
        System.out.println("Hello Spring 3.0");
    }
}

and

Spring3GoingToHell.java
package spring.com;

public class Spring3GoingToHell {
    public void sayHello1(){
        System.out.println("Going To Hell");
    }
}

Now we have the Main class calling the beans through spring framework using application context,

Spring3HelloWorldTest.java
package spring.com;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class Spring3HelloWorldTest {

    public static void main(String[] args) {

        //way 1
        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("Spring3HelloWorld.xml"));

        //way 2
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring3HelloWorld.xml");

        //way 3
        ApplicationContext context1 = new GenericXmlApplicationContext("Spring3HelloWorld.xml");
       
       
       
        Spring3HelloWorld myBean0 = (Spring3HelloWorld)beanFactory.getBean("Spring3HelloWorldBean");
        myBean0.sayHello();
       
        Spring3GoingToHell myBean1 = (Spring3GoingToHell) context.getBean("Spring3GoingToHellBean");
        myBean1.sayHello1();
       
        Spring3HelloWorld myBean2 = (Spring3HelloWorld) context1.getBean("Spring3HelloWorldBean");
        myBean2.sayHello();
  
    }
}     

Here are three ways to get a bean object from the Spring configuration xml file, Just get the object of bean from application context and then invoke the bean related operations.

For more details or any queries please mail me at
amol.phasale@gmail.com 

Thank you.

Creating PieChart Using JFreeCharts

To create Pie charts using JFreeChart API you need to include following API jars to you project.
1. jcommon-1.0.16.jar
2. jfreechart-1.0.13.jar

Create a project structure as shown below,






















Create a PieChart.java class having pie chart implementation. As shown below,

PieChart.java

package com.jfreechart.pie;

import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.util.Rotation;


@SuppressWarnings("serial")
public class PieChart extends JFrame {

  public PieChart(String applicationTitle, String chartTitle) {
        super(applicationTitle);
        

      // This will create the dataset
        PieDataset dataset = createDataset();
 

        // based on the dataset we create the chart
        JFreeChart chart = createChart(dataset, chartTitle);
        

       // we put the chart into a panel
        ChartPanel chartPanel = new ChartPanel(chart);
       

      // default size
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        

      // add it to our application
        setContentPane(chartPanel);

    }
   
    //Here is the dataset creation which is used for the information which we want to show in piechart.
    private  PieDataset createDataset() {
        DefaultPieDataset result = new DefaultPieDataset();
        result.setValue("INDIA", 29);
        result.setValue("UK", 20);
        result.setValue("USA", 51);
        return result;
       
    }
   
   
    private JFreeChart createChart(PieDataset dataset, String title) {
        //Here we are creating the 3D pie chart with dataset(created above) and with legend.
        JFreeChart chart = ChartFactory.createPieChart3D(title,  // chart title
            dataset,                // data
            true,                   // include legend
            true,
            false);

        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(290);
        plot.setDirection(Rotation.CLOCKWISE);
        plot.setForegroundAlpha(0.5f);
        return chart;
       
    }
}



Then create Main class which have the call to createing piechart method. As shown below,
Main.java
package com.jfreechart.pie;

public class Main {
   public static void main(String[] args) {
          PieChart demo = new PieChart("Comparison", "Which operating system are you using?");
          demo.pack();
          demo.setVisible(true);
      }
}


Run the Main class as a JAVA application, you will get a output as JFrame showing the piecharts.

Output:


For more information or any queries please mail me at
amol.phasale@gmail.com

Thank you.

Friday, September 7, 2012

Struts 2 ,Spring 3, Hibernate 4

Starting with Demo create the project structure as shown below,


before starting please add all required jars for Struts2, Spring3 and Hibernate4,






































Here goes the index page which has the action form has to be submit to struts.xml to perform struts action and validations.
Index.jsp
index.jsp
Hello Struts 2
from index.jsp request goes to the web.xml and from there through DispatureFilter it submitted to struts.xml(Struts-Config.xml)

web.xml 
web.xml
  
Here is the the struts configuration file(Controller of application) having actions and validations inside.

struts.xml
struts.xml
     
struts.xml has a tag called action which is mapped with the jsp form action and then load the class defined in the class attribute and call method defined in method attribute in this case "struts2.web.com.StrutsAction" class and "authenticateEmployee" method. if we dint specified any method then bydefault calls "execute" method.

Here goes the action class,
StrutsAction.java
package struts2.web.com;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import spring.hibernate.EmployeeDao;
import MyDemo.hibernate.Employee;

public class StrutsAction {

    private String message;
    private String userName;
    private String passWord;
    private String passWord1;
   
    private String name;
    private int age;
    private double salary;
   
   
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public StrutsAction() {
    }

    public String authenticateEmployee() {
        /*Resource resource = new FileSystemResource("./src/spring-hibernate.xml");
        BeanFactory factory = new XmlBeanFactory(resource);*/
       
        ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");

       
        EmployeeDao employeeDao = (EmployeeDao)factory.getBean("employeeDao");
       
        Employee empResult = employeeDao.getEmployee(getUserName());
        if(empResult!=null && empResult.getPassword().equalsIgnoreCase(getPassWord())){
            setMessage("Hello " + empResult.getName());
            return "SUCCESS";
        }
        return "ERROR";
    }
   
    public String RegisterEmployee() {
        /*Resource resource = new FileSystemResource("./src/spring-hibernate.xml");
        BeanFactory factory = new XmlBeanFactory(resource);*/
       
        ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");
       
        Employee employee = new Employee();
        employee.setUserID(getUserName());
        employee.setName(getName());
        employee.setAge(getAge());
        employee.setSalary(getSalary());

        EmployeeDao employeeDao = (EmployeeDao)factory.getBean("employeeDao");
       
        Employee empResult = employeeDao.saveOrUpdate(employee);
       
        if(empResult!=null){
            setMessage("Hello " + empResult.getName());
            return "SUCCESS";
        }
        return "ERROR";
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPassWord1() {
        return passWord1;
    }

    public void setPassWord1(String passWord1) {
        this.passWord1 = passWord1;
    }
}

In the authenticateEmployee method we have code call like, which is actually spring configuration calls the spring configuration.
BeanFactory factory = new XmlBeanFactory(resource);
ApplicationContext factory = new ClassPathXmlApplicationContext("spring-hibernate.xml");

spring-hibernate.xml
spring-hibernate.xml



HibernateSessionFactory.xml

HibernateSessionFactory.xml

DataSource.xml
DataSource.xml
  
Here we are using "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" which is to map key-variable in .properties file. for that perpose you need to do this entry into the .classpath file. Given below,


database.properties
jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;databaseName=HibernateDemo
jdbc.username=sa
jdbc.password=sa

This is upto the configuration,
now for application we are adding one hibernate entity mapping (*.hbm.xml) file


employee.hbm.xml
   
employee.hbm.xml


related entity to this mapping file is,

Employee.java
 package MyDemo.hibernate;

public class Employee {

    private String userID;
    private String password;
    private String name;
    private int age;
    private double salary;

    public Employee() {
    }

    public String getUserID(){
        return userID;
    }

    public void setUserID(String userID){
        this.userID = userID;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public int getAge(){
        return age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public double getSalary(){
        return salary;
    }

    public void setSalary(double salary){
        this.salary = salary;
    }

    public String toString(){
        return "Id = " + userID + ", Name = " + name + ", Age = "
            + age + ", Salary = " + salary;
    }
}

Now create one DAO for the accessing this entity through spring,

EmployeeDao.java
package spring.hibernate;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;


import MyDemo.hibernate.Employee;

public class EmployeeDao {

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(HibernateTemplate
                             hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    public HibernateTemplate getHibernateTemplate(){
        return hibernateTemplate;
    }

    public Employee getEmployee(final String userID){
        HibernateCallback callback = new HibernateCallback() {
            public Object doInHibernate(Session session)
                throws HibernateException,SQLException {
                 Query query = session.createQuery("from Employee");
                List  employees =  query.list();
                //employees.contains(id);
                Iterator iterator = employees.iterator();
                while(iterator.hasNext()){
                    Employee employee = iterator.next();
                    if(employee.getUserID().equalsIgnoreCase(userID)){
                        return employee;
                    }
                }
                return null;
            }
        };
        return (Employee) hibernateTemplate.execute(callback);
    }

    public Employee saveOrUpdate(final Employee employee){
        HibernateCallback callback = new HibernateCallback() {
            public Object doInHibernate(Session session)
                throws HibernateException,SQLException {
                session.saveOrUpdate(employee);
                return  session.load(Employee.class, employee.getUserID());
            }
        };
        return (Employee)hibernateTemplate.execute(callback);
    }
}



Now,  if the struts.xml action tag we have specified the action class in that we are verifying the details with data base through the spring-hibernate configuration, and if we get an "SUCCESS" as a output from the StrutsAction then we redirecting the same request to the success page or if we get an "ERROR" in logging in we forward the same request to the registration.jsp which is registration form for employee. on save of registration we are again saving this information to the database through spring hibernate configuration.


registration.jsp
registration.jsp
Through "gotoStrutsRegistration" we submit this form to struts.xml to registration function defined in the StrutsAction.java

The last one success.jsp, no need to explain more about this one.
success.jsp
success.jsp


Welcome to Struts2
   
       
   
Thank you for the visiting here, for more help or in case of any query please mail me at amol.phasale@gmail.com

Thank you.
 Amol Fasale


   

Pavus...!!!