About Me

My photo
Talk to me... you will know

Tuesday, September 27, 2011

JCaptcha




Lots of guys asked me help in integrating a simple jCaptcha module to their struts application.Was a bit busy with my work so am making this entry late. hope this is helpful
JCaptcha stands for Java Completely Automated Public Test to tell Computers and Humans Apart. Four years since the inception, the 1.0 release is the first declared as stable, available on the central Maven repository or on Sourceforge. The 1.0 release keep the JDK3 backward compatibility, next one 2.0-alpha1 will be built with JDK6 and provide compatibility with JDK5. The JCaptcha project is designed to ease extension, integration and configuration.
jCaptcha has the objective of checking the authenticity of the user trying to perform some action on the page. It allows providing a check on the page by verifying the user’s value with the image value generated to access the functionality of user. It can be used to determine the validity of registration in a page.
Prerequisites:
The user should be using java version 1.6 or higher.
The jar files required are:
·         jcaptcha-all.jar
·         commons-collection-3.2




JCaptcha tries to strictly respect the Inversion of Control pattern, to ease creation of components for concrete applications. An application using JCaptcha should only manipulate a CaptchaService instance.
Step 1:
 For maven users the simple procedure is to include the specific jar dependency to the pom.xml file instance as follows:
<dependency>
     <groupId>com.octo.captcha</groupId>
     <artifactId>jcaptcha</artifactId>
     <version>1.0</version>
</dependency>

For those who don’t use maven the simple procedure is to add the jcaptcha-all.jar and commons-collection-3.2 or greater to the application class path, ie in the WEB-INF/lib folder.


Step 2:
Provide the reference of the new servlet in the web.xml file to instantiate and allow access to the servlet as:

<servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>com.octo.captcha.servlet.image.SimpleImageCaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>jcaptcha</servlet-name>
        <url-pattern>/jcaptcha.jpg</url-pattern>
</servlet-mapping>

Step 3:
Add an image tag to the form you want to protect, by referring to the servlet call which asks the SimpleImageCaptchaServlet to generate a fresh new captcha.
<img src="jcaptcha.jpg" /> <input type="text" name="jcaptcha" value="" />

Step 4:
In the action file that validates the previous form’s action validate the input of the user with respect to the captcha value.
String userCaptchaResponse =request.getParameter ("jcaptcha");
boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request,userCaptchaResponse);
if(captchaPassed)
{
// proceed to submit action
}
Else
{
// return error to user
}

Monday, September 12, 2011

jQuery Basics


A-> Attribute
B-> Element
C-> Element
D-> Class
I-> Id
V-> Value


Selector Description
-------------------------------------------------------------------------------------
* Matches any element


B Matches all element with tag name B


B C Matches all element with tag name C that are descendants of B


B>C Matches all C that are direct children of B


B+C Match all C immediately preceded by sibling 
B


B~C Match all C preceded by any B


B:has(C) Match all B that has at least 1 descendant C


B.D Match all B with class D


.D Match all class D.             (*.D)


B#I Match all B with id I


#I Match all id I         (*#I)


B[A] Match all B with attribute A of any value


B[A=V] Match all B with attribute A  and value V


B[A^=V] Match all B with attribute A and value beginning with V


B[A$=V] Match all B with attribute A and value ending with V


B[A*=V] Match all B with attribute A and value containing V
..........................................................................................
:first First match of the page


:last Last match of the page


:first-child First child element


:last-child Last child element


:only-child All element without siblings


:nth-child(n) nth child element


:nth-child(even|odd) Even or odd children


:nth-child(Xn+Y) Element computed by the supplied formula


:even|:odd Even|Odd matching elements page wide


:eq(n) nth matching element


:gt(n) matching elements after n and excluding the 
nth


:lt(n) matching elements before n and excluding the nth
-----------------------------------------------------------------------------------------





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

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