About Me

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

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

Sample application for spring with loggingFeatured


many people asked me to help them with a sample of spring to know the basic as well as about logging using log4j


So i have made an application that allows you to get a gist of how both of them work.
Before seeing the code go through the following data:
*********************************************************************
Layout pattern :

%d -> date
%p -> priority
%F -> filename
%t -> thread
%c -> class
%L -> line no
%M -> method
%m -> message
%n -> newline character

*********************************************************************

Steps:
1. create a package my.spring and copy the java files into it
2. paste the applicationContext.xml and the log4j.properties into the source folder but outside the package.
3. Add the requisite jar files as mentioned in the next section.

********************************************************************

Required jar files:
common-logging.jar
log4j-1.2.11.jar
spring-aop.jar
spring-beans.jar
spring-context-support.jar
spring-context.jar
spring-core.jar
spring-jdbc.jar//optional
spring-jms.jarspring-orm.jar//optional
spring-test.jar
spring-tx.jar//optional
spring-web.jar//optional
spring-webmvc-portlet.jar//optional
spring-webmvc-struts.jar//optional
spring-webmvc.jar//optional
spring.jar


The optional jars are to be used in case when the database and web service coding needs to be done
*********************************************************************




//person.java

package my.spring;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Person 
{
static Logger l=Logger.getLogger("my.spring.Person");// creating the logger instance for the the respective class.
String name, address;
// constructor for the sake of constructor injection against setter injection...
public Person()
{
}
public Person(String name, String address)
{
BasicConfigurator.configure();// for writing the logger values to the console.
l.info("Using constructor injection.");//adding the statements to be printed.
this.name=name;
this.address=address;
}
/*Getter and Setter function definition for all the data members of the class.*/
public String getName() 
{
return name;
}

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

public String getAddress()
{
return address;
}

public void setAddress(String address) 
{
this.address = address;
}

}

//Trainee.java


package my.spring;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class Trainee 
{
static Logger l=Logger.getLogger("my.spring.Trainee");// creating the logger instance for the the respective class.
String eid,post ;
Person person;//object reference to the person class as a data member here
/*Getter and Setter function definition for all the data members of the class.*/

public Person getPerson()
{
return person;
}

public void setPerson(Person person)
{
this.person = person;
}

public String getEid() 
{
return eid;
}

public void setEid(String eid) 
{
this.eid = eid;
}

public String getPost()
{
return post;
}

public void setPost(String post) 
{
this.post = post;
}
public String toString()//overriding of the function to print requisite values..
{
BasicConfigurator.configure();// for writing the logger values to the console.
l.info("Using the overridden toString method.");//adding the statements to be printed.
return "Employee id : "+getEid()+", Employee name :"+getPerson().getName()+", Employee Address : "+getPerson().getAddress()+", Post : "+getPost();
}

}

//TestMe.java

package my.spring;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
/*Use below import for ClassPathXmlApplicationContext calling*/
import org.springframework.context.support.ClassPathXmlApplicationContext;
/*Use this import statement for the FileSystemXmlApplicationContext calling..*/
/* import org.springframework.context.support.FileSystemXmlApplicationContext;
*/
public class TestMe 
{
static Logger l=Logger.getLogger("my.spring.TestMe");// creating the logger instance for the the respective class.
public static void main(String args[])
{
BasicConfigurator.configure();// for writing the logger values to the console.
l.info("Started the application");//adding the statements to be printed.
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
BeanFactory beanfactory = new ClassPathXmlApplicationContext("applicationContext.xml");//Loads the file for parsing and initializing
/*
 BeanFactory beanfactory = new FileSystemXmlApplicationContext("C:/Users/Ajo.Koshy/Mage/workspace/SpringTry1/bin/applicationContext.xml");
*/
Trainee t=(Trainee)beanfactory.getBean("trainee");//Lazy loading of the bean required to be called.
try 
{
System.out.println("Enter your name : ");
t.getPerson().setName(br.readLine());
//Add other properties as required to be added to set.
catch (IOException e) 
{
e.printStackTrace();
}
System.out.println(t.toString());
l.info("Exiting the application");
}

}

//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="trainee" class="my.spring.Trainee">
<property name="eid" value="300695"/>
<property name="post" value="Software Engineer"/>
<property name="person" ><ref bean="person"/>
</property>
</bean>
<!--Bean 2 as reference to a value of Bean 1 -->
<bean id="person" class="my.spring.Person">
<!--Uncomment the following for dependency injection-->
<!--<property name="name" value="Ajo Koshy"/>
<property name="address" value="Noida"/>
--><!--This can be used for constructor setting-->
<constructor-arg index="0" value="Ajo Koshy"/>
<constructor-arg index="1" value="Noida"/>
</bean>
</beans>


//log4j.properties



log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.Trainee=org.apache.log4j.RollingFileAppender
log4j.appender.Person=org.apache.log4j.RollingFileAppender
log4j.appender.TestMe=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=C:/mylog.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* [%d] (%p) %F %t %c {%M}- %m%n
log4j.appender.Trainee.File=C:/Traineelog.log
log4j.appender.Trainee.MaxFileSize=2MB
log4j.appender.Trainee.MaxBackupIndex=2
log4j.appender.Trainee.layout = org.apache.log4j.PatternLayout
log4j.appender.Trainee.layout.ConversionPattern=*Calling from line no %L* [%d](%p) %F %t %c {%M}- %m%n
log4j.appender.Person.File=C:/Personlog.log
log4j.appender.Person.MaxFileSize=2MB
log4j.appender.Person.MaxBackupIndex=2
log4j.appender.Person.layout = org.apache.log4j.PatternLayout
log4j.appender.Person.layout.ConversionPattern=*Calling from line no %L* [%d](%p) %F %t %c {%M}- %m%n
log4j.appender.TestMe.File=C:/TestMelog.log
log4j.appender.TestMe.MaxFileSize=2MB
log4j.appender.TestMe.MaxBackupIndex=2
log4j.appender.TestMe.layout = org.apache.log4j.PatternLayout
log4j.appender.TestMe.layout.ConversionPattern=*Calling from line no %L* [%d](%p) %F %t %c {%M}- %m%n
log4j.category.my.spring.TestMe = INFO, TestMe
log4j.category.my.spring.Person = INFO, Person
log4j.category.my.spring.Trainee = INFO, Trainee
log4j.rootLogger = INFO, rollingFile