About Me

My photo
Talk to me... you will know
Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Wednesday, December 14, 2011

Custom login interceptor


The login in a struts page needs a proper interceptor to handle all possible cases of login... Have tried to make one that works :)


package com.interceptor;


import java.util.List;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.StrutsStatics;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;






import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.user.User_Info;


public class LoginInterceptor extends AbstractInterceptor implements StrutsStatics
{


private static final long serialVersionUID = 1L;
HttpSession session;
HttpServletRequest request;
HttpServletResponse response;
String t;

@Override
public String intercept(ActionInvocation actin) throws Exception
{
//System.out.println("call interceptor");
ActionContext ctx=actin.getInvocationContext();
request=(HttpServletRequest)ctx.get(HTTP_REQUEST) ;
response=(HttpServletResponse) ctx.get(HTTP_RESPONSE);
session =  request.getSession (true);
Object user = session.getAttribute ("user");
   if (user == null)
   {
    //System.out.println("inside near user=null");
    String trylog = request.getParameter("user");
       if (! StringUtils.isBlank (trylog) )
       {
        //System.out.println("try");
        String usern=request.getParameter("user").toString();
   
        String pass=request.getParameter("pass").toString();
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        //System.out.println("enter id");
        User_Info u=new User_Info();
        try
        {
        List l = ses.createQuery("select password from com.user.User_Info e where e.user_id="+"'"+usern+"'").list();
        for(Object o:l)
        {
        t=(String) o;
       
        }


        }
        catch (HibernateException e)
        {
        e.printStackTrace();
        }
        if(pass.equals(t.toString()))
        {
        //System.out.println("ho gaya");
        session.setAttribute("user", usern);
        //request.setAttribute("page", "dummy.jsp");//Following line of code is for a concern of a project for using a master page to include other pages by calling the page required to be included from session
        return "success";
        }
        /*else
        {
        System.out.println("cookie");
        Cookie c[]=request.getCookies();
        if(c==null)
{
       
        int counter = 1;
        Cookie cnt = new Cookie("count",new Integer(counter).toString());
        cnt.setMaxAge(65000);
        System.out.println(cnt);
        response.addCookie(cnt);
        }
        else
{
        for(int i=0;i<c.length;i++)
{
        if(c[i].getName().equals("count"))
        {
        int count = Integer.parseInt(c[i].getValue());
         if(count<3)
 {
          count++;
          //System.out.println("now="+count);
          c[i].setValue(new Integer(count).toString());
          response.addCookie(c[i]);
          return "login";
         }
         else
         {
         count++;
         c[i].setValue(new Integer(count).toString());
         response.addCookie(c[i]);
 return "change";
         }
        }
        }
}
       
     
        ses.close();
        System.out.println(u);
        }*/
    return "login";
       
       }


       else
{
           
         Object action = actin.getAction ();
     if (action instanceof com.opensymphony.xwork2.ValidationAware)
 {
    ((com.opensymphony.xwork2.ValidationAware) action).addActionError ("Username / password / code incorrect!");
     }
   
       }
       return "login";
   }
else
    {
    return actin.invoke();
    }
    }
}

Tuesday, September 06, 2011

Sample Application using the frameworks of struts2, hibernate, spring and log4j


//User.java

package com.action;
import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.Action;


public class User implements Action,ServletRequestAware
{
static Logger l=Logger.getLogger("com.action.User");
HttpServletRequest request;
int id;
String userName, passWord;

public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
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 toString()
{
BasicConfigurator.configure();
l.info("Return the values as a string");
return "Username : "+userName+" , Password : "+passWord;

}
@Override
public String execute() throws Exception
{
BasicConfigurator.configure();
boolean userVal=request.getParameter("userName").toString().equals("");
if(userVal)
{
l.info("Guest User logging");

}
else if(!userVal&&request.getParameter("passWord").toString().equals(""))
{
l.error("User trying to log without password");
return INPUT;
}

l.info("successful login");
return SUCCESS;
}
@Override
public void setServletRequest(HttpServletRequest arg0)
{
request=arg0;

}
}


//applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--Bean 1-->
<bean id="user" class="com.action.User">
<property name="id" value="1"/>
<property name="userName" value="Guest"/>
<property name="passWord" value="No Password Required"/>
</bean>
</beans>



//home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="s" uri="/struts-tags"%>
    <%@ page import="org.springframework.context.support.ClassPathXmlApplicationContext,org.springframework.beans.factory.BeanFactory,org.apache.log4j.BasicConfigurator,com.action.*,org.apache.log4j.Logger" %>
    <%@page import="org.hibernate.cfg.Configuration,org.hibernate.Transaction,org.hibernate.SessionFactory,org.hibernate.Session" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<%@page import="org.apache.struts2.interceptor.SessionAware"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Logger Home</title>
</head>
<body>
<%
Logger l=Logger.getLogger("com.action.User");
BeanFactory beanfactory = new ClassPathXmlApplicationContext("applicationContext.xml");
User u=(User)beanfactory.getBean("user");
BasicConfigurator.configure();
boolean flag=request.getParameter("userName").toString().equals("");
if(flag==false)
{
l.info("setting new username and password");
u.setUserName(request.getParameter("userName").toString());
u.setPassWord(request.getParameter("passWord").toString());
}
else
{
l.info("guest logged in");
/*u.setUserName(request.getAttribute("userName").toString());
u.setPassWord("No password required");*/
}
SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session ses= sf.openSession();
Transaction tr= ses.beginTransaction();
ses.save(u);
tr.commit();
out.println(u.toString());

%>
</body>
</html>


//login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="s"  uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyLogger</title>
</head>
<body>
<s:form action="log" >
<s:textfield name="userName" label="Username:"/>
<s:password name= "passWord" label="Password"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>

//struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd ">
<struts>
<package name="logger" extends="struts-default">
<action name="log" class="com.action.User">
<result name="input">login.jsp</result>
<result>home.jsp</result>
</action>
</package>
</struts>


//user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//hibernate/hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.action.User" table="Logger">
<id name="id" column="ID">
<generator class="increment" />
</id>
<property name="userName" column="UserName"/>
<property name="passWord" column ="PassWord"/>
</class>

</hibernate-mapping>


//hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//hibernate/hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.action.User" table="Logger">
<id name="id" column="ID">
<generator class="increment" />
</id>
<property name="userName" column="UserName"/>
<property name="passWord" column ="PassWord"/>
</class>

</hibernate-mapping>

//log4j.properties

log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.User=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=C:/appl.log
log4j.appender.rollingFile.MaxFileSize=2MB
log4j.appender.rollingFile.MaxBackupIndex=2
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=*Calling from line no %L* on Date: [%d] with Priority:(%p) Filename: %F At Thread: %t Using Class : %c from Method: {%M}- giving Message : %m%n
log4j.appender.User.File=C:/Userlog.log
log4j.appender.User.MaxFileSize=2MB
log4j.appender.User.MaxBackupIndex=2
log4j.appender.User.layout = org.apache.log4j.PatternLayout
log4j.appender.User.layout.ConversionPattern=*Calling from line no %L* on Date: [%d] with Priority:(%p) Filename: %F At Thread: %t Using Class : %c from Method: {%M}- giving Message : %m%n
log4j.category.com.action.User = INFO, User
log4j.rootLogger = INFO, rollingFile

Monday, September 05, 2011

hibernate class mappings


One table per class:
        primary to primary
        mapping using column
        data in all tables for class as designed


One table per Class hierarchy
        one table overall
        value selection based on discriminator
        unnormalised form of data

One table per concrete class with abstract
        abstract table implemented as empty
        concrete implementing classes have common fields
        set abstract as ttue to prevent any data entry to the class
        polymorphism as implicit to make the mapping through hibernate layer
        data access through abstract object

One to many
        use of foreign primary keys
        key column sets relation
        one to many relation to be specified
        makes auto mapping

One to one
        indirect transform by specifying unique constraint
        linked linking for updation
        resolved simplicity


go to following link to access hibernate docs

Monday, August 29, 2011

Hibernate



The required jar files are
  • asm.jar
  • commons-collections-2.1.1.jar
  • commons-logging-1.0.4.jar
  • cglib-2.1.3.jar
  • dom4j-1.6.1.jar
  • ehcache-1.6.0-beta1.jar
  • hibernate3.jar
  • jta.jar

Put all the xml files in the source folder outside the created package.

Mention the class and default values properly

in the configuration to create session factory add the xml in case it is not detected directly.


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


 Also checkout the following example


Happy hibernating:)
//DataEntry.java
/*****************************************************************************
 * In this program we are trying to applying the one-to-many relationship in
 * both the ways.
 *     Concept:
 *     Trinaers can take multiple technologies
 *     A technology can be taken by multiple Trainers
 *
 * Through this application you can check how the logic works for one-to-many
 * in both ways but its not suitable for actual implementation because this
 * application creats two tables only - TRAINER and TECHNOLOGY.
 *
 *  After running this application you will found that there is problem with
 *  inserting of new record next time.
 *  To resolve this problem you can convert this application to many-to-many.
 *
 */


package ajo.hib;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;


import org.hibernate.*;
import org.hibernate.cfg.Configuration;


public class DataEntry {
    public static void main(String[] args)throws IOException {
        int i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("2.insert 3.delete 1.update\n Enter your choice: ");
        i=Integer.parseInt(br.readLine());
        Employee e= new Employee(); e.setEmpId("E102");
       
          EmployeeDAO ed= new EmployeeDAO();
       
        switch(i)
        {
      
        case 1:
          //for update
          ed.update(e);
          break;
       
        case 2:
        // for insert operation
        //Employee e = new Employee();
        e.setEmpId("E102");
        e.setEmpName("Mahesh");


        //EmployeeDAO ed = new EmployeeDAO();


        ed.insert(e);
        break;
        case 3:
            //for delete
         e.setEmpId("E102");
       
          EmployeeDAO eDAO= new EmployeeDAO();
       
          eDAO.delete(e);
         break;
         default:
             System.out.println("Invalid");
             break;
        }
    }
}

//EmployeeDAO.java
package ajo.hib;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class EmployeeDAO implements IEmployeeDAO {


    public void insert(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
      
        ses.save(e);
        //e.setEmpName("rajeev"); // update statement gets fired for this
        tr.commit();


    }
  
    public void update(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
        e=(Employee) ses.load("ajo.hib.Employee", e.getEmpId());
      
        e.setEmpName("Ajo");
      
        System.out.println(e);
      
        ses.save(e);
        //ses.refresh(e);
        tr.commit();
        System.out.println(e);
    }
    public void delete(Employee e)
    {
        SessionFactory sf=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session ses= sf.openSession();
        Transaction tr= ses.beginTransaction();
      
        e=(Employee) ses.load("ajo.hib.Employee", e.getEmpId());
        System.out.println(e);
        ses.delete(e);
        tr.commit();
        System.out.println(e);
    }
  
}
//IEmployeeDAO.java

package ajo.hib;


public interface IEmployeeDAO {


    public void update(Employee e);
    public void insert(Employee e);
    public void delete(Employee e);
}

//Employee.java

package ajo.hib;


public class Employee
{
    String empName;
    String empId;
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public String getEmpId() {
        return empId;
    }
    public void setEmpId(String empId) {
        this.empId = empId;
    }
  
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return " Employee ID : "+empId + " Name : "+empName;
    }
}

//employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//hibernate/hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="ajo.hib.Employee" table="empl">
        <id name="empId" column="EMPLOYEE_ID">
            <generator class="assigned"/>
        </id>
        <property name="empName"/>
    </class>
</hibernate-mapping>

//hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//hibernate/hibernate Configuration DTD//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.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">admin1234</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>