Friday, November 1, 2013

A Perfect Plan

A very eminent maxim by Napoleon Bonaparte, “Give me good mothers and i shall give you a great nation!” It's not only legendary but spot-on indeed. If we cogitates it as veracity then apparently the vice-versa case will be for the wickedest nation too. But, before getting into that impeccable plan I would like to recap everyone about a childhood anecdote, "The Pied Piper of Hamelin". Almost everyone heard about this story in which a piper was involved in the departure or death of a great number of children from the town of Hamelin. So, the staple notion will undoubtedly be around these two topics and in the end you will be able to grasp that how these both things are interlocked to each other.

I was just bearing in mind few past events that have transpired in my country and as always media promote those on a red-carpet to collect more TRP. But, the resultant of those events is "I am Malala". Well, being a Pakistani I should be gratified as she has inscribed a book in just a fledgling age, which is indeed a great triumph and got a nomination for noble prize too. What if, after few noble prizes I have a doubt on the credibility of noble prize but although she got so I can't take step back in escalating her.


But, let’s just give it a thought that why Malala? A name which we never caught before by the media if she was doing such a valor act in Northern Areas of Pakistan then why not media tried to capture her before? Probably they had no interest in that. And answer of Why Malala? That she was a girl; and a girl can be a mother. The Pied Piper is encapsulated in this article but the Magical Flute is Malala. Media launched Malala as a national hero, who were directly intermingling with masses and touching youth’s heart, specifically rousing girls of the whole country. 


So now the children has started following the Magical flute; but few verses that even I received from that magical flute were:


"I wanted to speak up for my rights,"Means freedom of speech, probably everyone is aware of freedom of speech what does it mean? Secondly, she mentioned in her book about freedom of speech by promoting the work of salman rushdie.


"And also I didn't want my future to be just sitting in a room and be imprisoned in my four walls and just cooking and giving birth to children. I didn't want to see my life in that way." Now men should get ready to give birth to children, anyway this is not my area of curiosity but now every girl who was created to be a mother will probably think about Malala and will try to skip nuptials and stuff and try to restructure the society which will end up in muddle. 


So, here it's quite vibrant that by using Malala some bodies are trying to seed the minds of girls which will nurture with respect to time. Trees are helpful but somehow trees affect the light sources too, so the resultant trees of these seeds will darken the whole nation. And after few years the generations that will hoist probably have a different perception of not their own; but an imposed perception of the pied piper. The perfect plan will transform the mothers which will later on transmute a whole  nation into a worst nation.

Tuesday, September 17, 2013

Hopelessness

In Pakistan one word was enough for me to stay ‘HOPE’. But, for past few months I am in a transition state and on daily basis have a duel with my thoughts. And the reason behind this combat is still the word ‘HOPE’ because I lost hope in the future over here.

This land has given me a lot and in return transformed my ‘HOPE’ into ‘HOPELESSNESS’ because these days, I am rebellion to my own thoughts because of this bad governance, insecurity, and had a 20% trust over the law but it’s vein too because of ‘Sorry Sorry’ game that often played by the Law.

But, I got another question to raise a survey to clarify myself that either I am the only one who is having issues or others are suffering from it too. In this case I have just moved one word to all my friends and would like to share the reply that I got.

Question was ‘What HOPELESSNESS is for you?’
  • Police
  • Law Enforcement Agencies
  • Bad Governance
  • Security
  • Media
  • Taxes
  • Wannabes
  • CJ
  • Justice
  • Transformed Culture


I have changed the redundant answers and tried to only mention the actual meanings from those answers. But, after that I realized that my decision is good and I think those who are living probably have hopes or may not be able to fly away or may be those who are feudal or in power. 

Tuesday, September 10, 2013

Behind the City of Lights

As everyone knows that Karachi is a city of light but these days lights have more than one source. Initially the city sparkled by the KESC but these days bullet sparks are also helping the cause. But, this is what everyone must be aware of but, what people are not aware of can be easily understood by this reading.

I don’t read newspaper because of the depressing news into it, but yes if something informative than I must go through. And in my case ‘informative’ means anything which can help me out.  So, I was just reading news that was shared by one of my colleague which was related to statistics of express crime in Karachi on monthly basis. And it’s around 130 registered crimes and around 500 unregistered crimes because no one goes for FIR of such crimes and in many cases Police don’t even lodge an FIR.

So, here few questions rise:
How they target us?
Why Police don’t lodge an FIR?

If anyone of us thinks that they are not organized then it must be our thoughts, because they are quite organized even far away from our thoughts. They are tracking our phone calls, our daily activity using foursquare, our lifestyle using Facebook, and our job using linked-in.

So, how to prevent from such things, try to be a hard target for them by avoid sharing your personal stuff over the net. Don’t talk about transaction details over the cell phone, specifically if it’s registered on your name.  Block all those unnecessary people who are following you at foursquare or twitter. And, in case of linked in you can’t help it. Even they are getting the accounts information from the banking system that how much amount do you have in your account. Recently, a bank manager kidnapped and it was probably to fetch information about his clients. So, this thing shows how they can fetch information easily of those who have quite healthy bank statements.

Few days back two snatchers shot on my car because I tried to escape and saved to become victimized. But, I was amazed to see the precision in the shot they have made as by the grace of Almighty Allah I was saved from only 4 inches while my car was moving fast and in zig-zag order, else it could blow my head.
But, that depression was less than the depression I faced while I went for lodging an FIR against it. It happened near Tipu Sultan road while I was heading towards Dunkin Donuts from Balooch Colony. So the nearest station I got was in M.A.C.H.S, the officer said it’s not under their jurisdiction, left for the station in PECHS Bl-6, I went there but the officer there was really funny. First question he asked was; where were you coming from? I replied Airport then he said the FIR should be lodged at Airport not here. I said but the incident held at Tipu Sultan Rd. His next question; was the car moving? I replied yes. Then jurisdiction cannot be finalized you can’t lodge an FIR, just drop me an application and we will look into it.

So, here I realized he is not at all willing to lodge an FIR, but there was a genuine reason behind it. As no one can risk the life of his family for just few thousands of salary; because these groups must have threatened them not for their lives but for the lives of their family and that could be a reason for not to take any kind of action against these people. 

In my opinion if we know that police can't save us then the best option is to find own way to secure ourselves and second best option is to escape from this city or country to get a better peacefull life where atleast being a third degree citizen you will have rights.Sad reminder of the ground reality in Pakistan today. Anybody can just kill you like a dog and get away with it, specially when he belongs from political elite family. 



Friday, August 2, 2013

Merge Multiple Rows in SQL Server

I was just going through a problem in database which was related to querying data from two tables but all the uncommon columns should be merged to a single row even comma separated.

Primary Table
ID
Value_1
Value_2
1
ABC
DEF
2
GEH
IJK


Foreign Table
ID
FK_ID
Value_1
1
1
LMK
2
1
IJKK
3
2
ZZZ
4
2
YYY

 Expected Result
PK.ID
FK_ID
PK.Value_1
FK_Value_1
PK.Value_2
1
1122,2122
ABC
LMK,IJKK
LKM
2
3122,4122
GEH
ZZZ,YYY
NOP

Query
Select PK.ID,PK.Value_1, PK.Value_2,
      (SELECT STUFF( (SELECT ', ' +  CONVERT(varchar(25), FK.ID, 1) 
            FROM FOREIGN_TABLE FK  WHERE FK.ID=PK.ID
                  FOR XML PATH ('')) , 1, 2, ''))   AS FK_ID ,
      (SELECT STUFF( (SELECT ', ' +  CONVERT(varchar(25), FK2.Value_1, 1)
             FROM FOREIGN_TABLE FK2 WHERE FK2.ID=PK.ID 
                  FOR XML PATH ('')) , 1, 2, ''))   AS FK_Value_1 
FROM PRIMARY_TABLE PK 

This query will be performance wise slow but, in SQL Server we don't have group concat like MySQL so, we will have to bear the pain.

Sunday, July 28, 2013

A Shameful Transmission

Pakistan came into sight on the world map in 1947 and became the first Islamic ideological state  of that time probably it may have some conflicts with my own ideologies but currently going on facts not on my own views and opinions. And since our childhood I have noticed so many transformations; as from radio to television, television to flat screens, Atari to Xbox, bicycle to SUV, and unfortunate but yes from PTV to GEO.
Well it can be easily evidence by anyone that if you ever scroll from one channel to another and in between you will have any news channel then you will hear a word that will be synonym to crime i.e. Murder, Snatching, Killing or etc. Well, here I am not at all pointing on GEO but all the channels that we see on televisions. Because I have this thing in my mind that once Indra Gandhi said:

India will wage a media war”

My point is that are the channels that we watch on daily basis are the result of these statements or something else. Anyway till now probably everyone just got confused that what I am trying to portrait as these things doesn’t have any link but now I think I should better gel up these things together.  Pakistan is the First Islamic State which had some different meanings of Religion till that statement and just after few years of Indra Gandhi’s statement we got more then 100+ channels on televisions which leave impressions on our mind about what they want us to think. Similarly these days we have experiencing a transformed religion which can’t be our religion at all as this religion has added attractions of Diwali, Halloween, Basant, Holi, Christmas and other spices in it.
But, it’s not only their fault as no one can enforce anyone to do so they can just guide you rest of the things are completely depends upon our own willingness. Since few days everyone at my office was discussing about Amir Liaquat’s show. So I never say anything till the time I properly investigate it, in this case I finally traced that from where they are transmitting this show and got to know “Regent Plaza, Karachi, Pakistan”. So, this weekend visited Regent Plaza and took a room there my room was on 6th Floor as almost all the rooms were booked by Amaan Ramzan program team on 3rd and 6th floor. But before getting into hotel saw a huge chaos as some accident happened there but that gathering was just waiting for Aamir Liaquat, a person who was hosting a religious program for Geo tv.
But, my problem was not these people because they were there for some gifts or some temporary happiness by getting exposure to media. The main concern who actually calls them, once in a Sehri I woke up and was heading towards a complementary sehri offered by the hotel and then suddenly got a voice of a girl from a room who was crying “Aamir Bhai please….”. I am not going to quote the whole thing but suddenly got clicked that Aamir Liaquat must be in sehri transmission then whom she must be talking to. But when I tuned into Geo Tv similar voice of a caller I heard on transmission.
So, I got my answer that this is all fake because I know if they will get the calls directly then everyone will abuse them as they do on social media. Each caller is a paid professional who is staying in hotel too. Now, I got an answer to my first question that who the callers are but now second question still need an answer that are they really that religious as everyone is falling towards them. But, it can be easily evidence there when someone is saying “MashAllah” on a song in his live transmission. And too many person who were called at his show were talking to girls and saying no to pictures with them but was giving autograph by holding the hands and signing on them. Holding tasbih whole day long just to get into the character but, ordering lunches in their room by room service while every Muslim was fasting.
So, now I think it’s the most shameful act by media when they just give a price tag to religion. A wonderful saying I would like to quote here.

“Walking nude at home doesn’t bother anyone but it does when you don’t live alone or you have transparent walls”


This time media in Pakistan is playing the same role by portraying this religion all over the world which is not at all Islam, but the Islam they want to be. Stop this transmission which makes us abash in all over the world and stop doing things which hurts a lot of Muslim. And an answer to Aamir Liaquat that yes if you just want to spread happiness then you must not need to tell the whole world that you want to spread some happiness.


Wednesday, July 24, 2013

Maven + Struts2 + Spring + Hibernate + Struts2-Convention-Plugin

After spending so many days and nights and days again I finally be able to achieve the basic Architecture. Well, the basic architecture was quite simple and you will be able to get a lot of tutorials online about it but, probably they have few things missing (i.e. Maven or sometimes Struts2-Convention-Plugin).
Reason behind choosing this structure is to make an easy expandable application structure with an isolation in between layers.

Reason Behind:
Maven is just used for dependency management of libraries and easy deployment.
Struts2 is used for UI.
Spring for service layer, as we all know we can easily change implementation which will be helpful for us to entertain the change request.
Hibernate for ORM that will play with the database.


Directory Structure:

Don't worry about such a big directory tree. One by one I will tell you each and everything about it. Before starting everything we will start telling you about the pom that will be required to setup the artifacts of your project.

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>TestWar</groupId>
       <artifactId>TestWar</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <name />
       <description />
       <dependencies>
              <!-- Struts 2 -->
              <dependency>
                     <groupId>org.apache.struts</groupId>
                     <artifactId>struts2-core</artifactId>
                     <version>2.1.8.1</version>
              </dependency>
              <!-- Struts 2 End-->
              <!-- Struts 2 + Spring plugins -->
              <dependency>
                     <groupId>org.apache.struts</groupId>
                     <artifactId>struts2-spring-plugin</artifactId>
                     <version>2.1.8.1</version>
              </dependency>

              <!-- MySQL database driver -->
              <dependency>
                     <groupId>mysql</groupId>
                     <artifactId>mysql-connector-java</artifactId>
                     <version>5.1.9</version>
              </dependency>
              <!-- Spring framework -->
              <dependency>
                     <groupId>org.springframework</groupId>
                     <artifactId>spring</artifactId>
                     <version>2.5.6</version>
              </dependency>
              <dependency>
                     <groupId>org.springframework</groupId>
                     <artifactId>spring-web</artifactId>
                     <version>2.5.6</version>
              </dependency>
              <!-- Hibernate core -->
              <dependency>
                     <groupId>asm</groupId>
                     <artifactId>asm-all</artifactId>
                     <version>3.3</version>
              </dependency>
              <dependency>
                     <groupId>asm</groupId>
                     <artifactId>asm</artifactId>
                     <version>3.3</version>
              </dependency>
              <dependency>
                     <groupId>org.hibernate</groupId>
                     <artifactId>hibernate-core</artifactId>
                     <version>3.6.7.Final</version>
              </dependency>

              <!-- Hibernate core library dependency start -->
              <dependency>
                     <groupId>org.apache.struts</groupId>
                     <artifactId>struts2-convention-plugin</artifactId>
                     <version>2.1.8.1</version>
              </dependency>
              <dependency>
                     <groupId>javax.servlet</groupId>
                     <artifactId>javax.servlet-api</artifactId>
                     <version>3.0.1</version>
                     <scope>provided</scope>
              </dependency>
              <dependency>
                     <groupId>log4j</groupId>
                     <artifactId>log4j</artifactId>
                     <version>1.2.15</version>
              </dependency>
      
       </dependencies>
       <build>
              <sourceDirectory>${basedir}/src</sourceDirectory>
              <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
              <resources>
                     <resource>
                           <directory>${basedir}/src</directory>
                           <excludes>
                                  <exclude>**/*.java</exclude>
                           </excludes>
                     </resource>
              </resources>
              <plugins>
                     <plugin>
                           <artifactId>maven-war-plugin</artifactId>
                           <configuration>
                                  <webappDirectory>${basedir}/WebRoot</webappDirectory>
                                     <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
                           </configuration>
                     </plugin>
                     <plugin>
                           <artifactId>maven-compiler-plugin</artifactId>
                           <configuration>
                                  <source>1.5</source>
                                  <target>1.5</target>
                           </configuration>
                     </plugin>
              </plugins>
       </build>
</project>


In above pom file we have basically two main tags that will be helpful for you one is plugins and second one is dependencies. Well dependencies deal with the libraries that are required for the project, and plugins help for compilation and war creation.

Note: One can easily change the artifact version of the library but make sure the other libraries that are interacting with that library must belong to the same artifacts.

Now, lets proceed towards the deployment descriptor.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <filter>
            <filter-name>struts2</filter-name>
            <filter-class>
       org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
            </filter-class>

            <init-param>
                  <param-name>config</param-name>
                  <param-value>
                      struts-default.xml,struts-plugin.xml, struts.xml 
                  </param-value>
            </init-param>
      </filter>
      <filter>
            <filter-name>AuthenticationFilter</filter-name>
            <filter-class>com.test.lab.filter.AuthenticationFilter</filter-class>
            <init-param>
                  <param-name>insecurePages</param-name>
                  <param-value> /login.action </param-value>
            </init-param>
      </filter>

      <filter-mapping>
            <filter-name>AuthenticationFilter</filter-name>
            <url-pattern>*.action</url-pattern>
      </filter-mapping>
      <filter-mapping>

            <filter-name>struts2</filter-name>
            <url-pattern>*.action</url-pattern>
      </filter-mapping>
      <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/resources/config/SpringBeans.xml</param-value>
      </context-param>
     

      <listener>
            <listener-class>
              org.springframework.web.context.ContextLoaderListener
            </listener-class>
      </listener>
</web-app>





We have defined one custom filter that we will use to handle each and every request that will be coming to our application. Secondly other then the struts built-in filter also using a ContextLoaderListener that will load
all the beans of Spring at the time of initialization.

In StrutsPrepareAndExecuteFilter, we have mentioned a config param that will be showing that these files will only be loaded for struts configuration. Here people will get a bit confuse that why we are using configuration while Struts2 offer us a complete annotation based project setup (A.K.A Zero Configuration). Yes we are not going to use configuration for action classes but for interceptors we must need a configuration file that will initiate our interceptors at the time of context-loading.

This is our struts.xml which will be used to declare the interceptors that will be used in our actions.

<?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>
      <constant name="struts.devMode" value="false" />
      <constant name="struts.convention.package.locators.basePackage"
            value="com.test.lab" />
      <constant name="struts.convention.exclude.packages"
            value="org.apache.struts.*,org.apache.struts2.*,
org.springframework.web.struts.*,
org.springframework.web.struts2.*,
org.hibernate.*,WarFileName.*" />
      <constant name="struts.convention.action.checkImplementsAction"
            value="false" />

      <constant name="struts.convention.package.locators" value="action,actions,struts,struts2" />
      <package name="interceptions" extends="struts-default"
            namespace="/">
            <interceptors>
                  <interceptor name="mylogging"
                        class="com.test.lab.interceptor.LoggingInterceptor">
                  </interceptor>
                  <interceptor-stack name="loggingStack">
                        <interceptor-ref name="mylogging" />

                        <interceptor-ref name="defaultStack" />
                  </interceptor-stack>
            </interceptors>
      </package>
</struts>



In above xml we have mentioned few properties that will be used to bound our application to use struts2-convention-plugin and interceptors. We are just declaring our interceptors here that will be initialized at the time of application startup and will be executed whenever we will use it in our action class by using Annotations.

Now, let's move towards our first action class and how we are going to use annotation in that.

@ParentPackage("interceptions")
@InterceptorRefs({ 
    @InterceptorRef("mylogging"
})
public class LoginAction  implements ModelDriven{



Before getting into the depth of this class we must need to tell that what we need to put in @ParanetPackage() in @ParentPackage we need to use the same name that we have used in our struts.xml to represent the package in which our interceptor lies. Then finally use the name of interceptor in InterceptorRef.

We are not extending this class with ActionSupport becuase we have used annotations but implementing ModelDriven that will help use to get a bean entity to be used in our action class to delegate operations to Spring Layer.

UpUser user = new UpUser();
UserBo userBo;   
      public Object getModel(){
            return user;
      }
      public void setUserBo(UserBo userBo) {
            this.userBo= userBo;
      }


This is where we are getting the model by implementing the method of our interface ModelDriven.

Finally here our action comes which will be used for mapping of our action to JSPs

@Action(value="/login",results={@Result(name="success",location="/jsp/successPage.jsp"),
                  @Result(name="login",location="/jsp/userLogin.jsp")})
      public String execute() {
            if(user.getUserScreenName()==null)
                  return "login";
            System.out.println(userBo.verifyUser(user));
            return "success";
      }




Note: As we have used Struts2-Convention-Plugin so we must need to end our action class with  "Action" Because it will only compile all those classes which will have action and defined in action package.

From struts.xml:

<constant name="struts.convention.package.locators.basePackage"
            value="com.test.lab" />



Now, i'll not go into much detail of the classes because it's basic java which you must be aware of that how we can do transformation from one class to another and delegate a class to call the method.

UserBo which we have used in our Action is a BusinessObject which will act as a middle layer that will manage the transformation from Struts->Hibernate


package com.test.lab.bo;

import java.util.List;

import com.test.lab.model.UpUser;

public interface UserBo {
      Boolean verifyUser(UpUser user) ;
}




As UserBo is an interface so here it's an implementation for it where we actually will do Dependency Injection a feature offered by Spring. 


package com.test.lab.bo.impl;

import java.util.List;


import com.test.lab.bo.UserBo;
import com.test.lab.dao.UserDAO;
import com.test.lab.model.UpUser;

public class UserBoImpl implements UserBo{
      UserDAO userDAO;
      //DI
      public void setUserDAO(UserDAO userDAO){
            this.userDAO = userDAO;
      }
      public Boolean verifyUser(UpUser user) {
            // TODO Auto-generated method stub
            return userDAO.verifyUser(user);
           
      }

}



Now we are going to dig UserDAO what exactly it will do. As from the name it's quite clear that it will act as a data layer for us

package com.test.lab.dao;

import java.util.List;

import com.test.lab.model.UpUser;

public interface UserDAO {
     
       Boolean verifyUser(UpUser user);
}


Once again we have created an interface of UserDAO. So, we must need to provide an implementation:

package com.test.lab.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.test.lab.dao.UserDAO;
import com.test.lab.model.UpUser;

public class UserDAOImpl extends HibernateDaoSupport
implements UserDAO{

     
      public Boolean verifyUser(UpUser user) {
            // TODO Auto-generated method stub
            Boolean result = false;
            DetachedCriteria criteria = DetachedCriteria.forClass(
                  UpUser.class);
          criteria.add(Restrictions.eq("userScreenName", user.getUserScreenName()));
          criteria.add(Restrictions.eq("userPassword", user.getUserPassword()));
         
             List<UpUser> list = getHibernateTemplate().findByCriteria(criteria);
             if(list.size()>0)
                   result = true;
             return result;
      }
}


Entity of UpUser:


package com.test.lab.model;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * UpUser entity. @author MyEclipse Persistence Tools
 */

public class UpUser implements java.io.Serializable {

      // Fields

      private Integer userId;
     
      private String userScreenName;
      private String userPassword;
            // Constructors

      /** default constructor */
      public UpUser() {
      }

      /** minimal constructor */
      public UpUser(String userScreenName,String userPassword) {
            this.userScreenName = userScreenName;
            this.userPassword = userPassword;
            }

     
      // Property accessors

      public Integer getUserId() {
            return this.userId;
      }

      public void setUserId(Integer userId) {
            this.userId = userId;
      }
      public String getUserScreenName() {
            return this.userScreenName;
      }
      public void setUserScreenName(String userScreenName) {
            this.userScreenName = userScreenName;
      }
      public String getUserPassword() {
            return this.userPassword;
      }
      public void setUserPassword(String userPassword) {
            this.userPassword = userPassword;
      }
}


Hibernate mapping file that we need to keep in the same folder where our hibernate entity will be.

<?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">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.test.lab.model.UpUser" table="up_user" catalog="test_db">
        <id name="userId" type="java.lang.Integer">
            <column name="user_id" />
            <generator class="identity" />
        </id>
    
        <property name="userScreenName" type="java.lang.String">
            <column name="user_screen_name" length="150" not-null="true" />
        </property>
       
        <property name="userPassword" type="java.lang.String">
            <column name="user_password" length="25" not-null="true" />
        </property>
            </class>
</hibernate-mapping>


Hibernate In the above file user_id, user_password and user_screen_name are the fields that we have in our database and now mapping here with the userId, userPassword and userScreenName in our UpUser.java file.

Here we are going to discuss main Spring file that will manage almost all the interaction between UI and Data layer.

This file need to be placed at: resources/com/test/lab/spring/UpUserBean.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-2.5.xsd">

<bean id="loginAction" class="com.test.lab.actions.LoginAction">
<property name="userBo" ref="userBo" />  
</bean>

<bean id="userBo" class="com.test.lab.bo.impl.UserBoImpl" >
<property name="userDAO" ref="userDAO" />
</bean>

<bean id="userDAO" class="com.test.lab.dao.impl.UserDAOImpl" >
<property name="sessionFactory" ref="sessionFactory" />
</bean>

</beans>


Few more configuration:

resources/config/database/properties/database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/legal_erp
jdbc.username=root
jdbc.password=root



resource/config/spring/DataSource.xml
<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-2.5.xsd">

 <bean
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
     <value>WEB-INF/classes/resources/config/database/properties/database.properties</value>
   </property>
</bean>

  <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="${jdbc.driverClassName}" />
      <property name="url" value="${jdbc.url}" />
      <property name="username" value="${jdbc.username}" />
      <property name="password" value="${jdbc.password}" />
  </bean>

</beans>


 resources/config/spring/HibernateSessionFactory.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-2.5.xsd">

<!-- Hibernate session factory -->
      <bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
       
            <property name="dataSource">
                  <ref bean="dataSource"/>
            </property>
       
            <property name="hibernateProperties">
                  <props>
                        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                        <prop key="hibernate.show_sql">true</prop>
                        <prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull
                        </prop>
                  </props>
            </property>
       
            <property name="mappingResources">
                  <list>
                 
<value>com/test/lab/model/UpUser.hbm.xml</value>
                  </list>
            </property>
     
      </bean>
</beans>

  resources/config/SpringBeans.xml
<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-2.5.xsd">

<!-- Database Configuration -->
<import resource="spring/DataSource.xml"/>
<import resource="spring/HibernateSessionFactory.xml"/>

<!-- Beans Declaration -->
<import resource="../com/test/lab/spring/UpUserBean.xml"/>

</beans>


 Now wrapping up everything with an AuthenticationFilter and how to write a custom filter that we have just mentioned in our web.xml

AuthenticationFilter.java

package com.test.lab.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


public class AuthenticationFilter implements Filter
{
    private static Logger logger = Logger.getLogger( AuthenticationFilter.class );
    private HashSet<String> insecurePages = null;

    public void init( FilterConfig config ) throws ServletException
    {
      System.out.println( "PUBLIC Authentication Fileter Started." );
         logger.info( "PUBLIC Authentication Fileter Started." );
        String strInsecurePages = config.getInitParameter( "insecurePages" );
        StringTokenizer tokenizer = new StringTokenizer( strInsecurePages, ",", false );
        insecurePages = new HashSet<String>( tokenizer.countTokens() );

        while ( tokenizer.hasMoreTokens() )
        {
            insecurePages.add( tokenizer.nextToken().trim() );
        }
        logger.info( "PUBLIC Authentication Fileter Started." );
    }

    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
            throws IOException, ServletException
    {
        if ( request instanceof HttpServletRequest )
        {
            System.out.println("Request Servlet Request");
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
           
            logger.info( "Request received: " + req.getRequestURI()
                         + " from user with session id: " + req.getRequestedSessionId() );
           
        }

        chain.doFilter( request, response );
    }

    public void destroy()
    {
        insecurePages = null;
    }

}

 And our basic Interceptor that we have just to calculate the time of our action request.
LoggingInterceptor.java

package com.test.lab.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoggingInterceptor implements Interceptor{

      private static final long serialVersionUID = 1L;

      public String intercept(ActionInvocation invocation) throws Exception {

            String className = invocation.getAction().getClass().getName();
            long startTime = System.currentTimeMillis();
            System.out.println("Before calling action: " + className);

            String result = invocation.invoke();

            long endTime = System.currentTimeMillis();
            System.out.println("After calling action: " + className
                        + " Time taken: " + (endTime - startTime) + " ms");

            return result;
      }

      public void destroy() {
            System.out.println("Destroying MyLoggingInterceptor...");
      }
      public void init() {
            System.out.println("Initializing MyLoggingInterceptor...");
      }
}


LoginAction.java

This is just a dumb action so will not perform a lot of things for you but, it will give you an idea of using it

package com.test.lab.actions;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.test.lab.bo.UserBo;
import com.test.lab.model.UpUser;
@ParentPackage("interceptions")
@InterceptorRefs({ 
    @InterceptorRef("mylogging") 
})
public class LoginAction  implements ModelDriven{
      UpUser user = new UpUser();
      UserBo userBo;
      @Action(value="/login",results={@Result(name="success",location="/jsp/successPage.jsp"),
                  @Result(name="login",location="/jsp/userLogin.jsp")})
      public String execute() {
            if(user.getUserScreenName()==null)
                  return "login";
            System.out.println(userBo.verifyUser(user));
            return "success";
      }
     
      public Object getModel(){
            return user;
      }
      public void setUserBo(UserBo userBo) {
            this.userBo= userBo;
      }
     
      public UpUser getUser() {
            return user;
      }

      public void setUser(UpUser user) {
            this.user = user;
      }
     
}


resources/config/log4j.xml

 So, this is it related to the whole configuration and coding. 

I have intentionally didn't add any jsp file in this code because I think JSP can be simply added by anyone by looking into a lot of example available so don't want to waste my time into that but if, anyone have any issues  in implementing this then they may contact me.