About Me

My photo
Talk to me... you will know

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, November 29, 2011

Distance Calculator using google api distance matrix, and json parsing




Was working on google api for my project to calculate the distance between 2 places.. Google maps has that functionality but i needed a sneak peek into the api for that.. I did a little research for the same and found out that they used json objects in Distance Matrix for the same. So i tried to learn json parsing which is very simple by the way. You will need the json jar file to run this and its quite good at calculating distance between any two places on earth...
Try it out.. Its very simple.


the data from the url for 2 places say noida to delhi will be a json object of the format


You just need to know how to parse through and get thae data. :)

//JSON object :

{
   "destination_addresses" : [ "Bokaro, झारखण्ड, India" ],
   "origin_addresses" : [ "Noida, Delhi, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1,201 km",
                  "value" : 1200769
               },
               "duration" : {
                  "text" : "15 hours 19 mins",
                  "value" : 55119
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


//JSONInterface.java

package com.distanceMatrix;


import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.*;


public class JSONInterface 
{
Integer tem;
Float dist;


private static String readAll(Reader rd) throws IOException 
{
   StringBuilder sb = new StringBuilder();
   int cp;
   while ((cp = rd.read()) != -1) 
   {
     sb.append((char) cp);
   }
   return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException 
{
   InputStream is = new URL(url).openStream();
   try 
   {
     BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
     String jsonText = readAll(rd);
     JSONObject json = new JSONObject(jsonText);
     return json;
   }
   finally 
   {
     is.close();
   }
}


public float calcDistance(StringBuffer beg, StringBuffer end) 
{
JSONObject json=null;
try 
{

json = readJsonFromUrl("https://maps.googleapis.com/maps/api/distancematrix/json?origins="+beg+"&destinations="+end+"&mode=driving&sensor=false");
json.get("rows");
JSONArray arr=null;
arr = json.getJSONArray("rows");
tem=(Integer)arr.getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").getInt("value");
dist=(float)tem/1000;
}
catch (JSONException e) 
{
e.printStackTrace();

catch (IOException e)
{
    e.printStackTrace();
}
return dist;
}
}




//JSONDiatanceCalculator.java


package com.distanceMatrix;


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


public class JSONDiatanceCalculator 
{
static String beg,end;
static StringBuffer start=new StringBuffer(), stop=new StringBuffer();
static float totDistance;
public static void main(String args[])
{
JSONInterface ji=new JSONInterface();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter the source place : ");
beg=br.readLine();
System.out.println("Enter the distance place : ");
end=br.readLine();
start.append(beg);
stop.append(end);
for(int i=0; i<start.length(); i++)
{
if(start.charAt(i)==' ')
{
start.deleteCharAt(i);
start.insert(i, "%20");
}
}
for(int i=0;i<stop.length();i++)
{
if(stop.charAt(i)==' ')
{
stop.deleteCharAt(i);
stop.insert(i, "%20");
}
}
totDistance=ji.calcDistance(start,stop);
System.out.println("The distance between "+beg+" and "+end+" is = "+totDistance);
}
catch(IOException e)
{
System.out.println("Improper place value set..");
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Json type exception");
e.printStackTrace();
}
}
}

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

There was an error in this gadget