Java Collection Framework Matrix



Interfaces Implementations Allows
Duplicates
Key Value
Pair
Ordered Sorted
List ArrayList Yes No By Index No
Vector Yes No By Index No
LinkedList Yes No By Index No
set HashSet No No No No
LikedHashSet No No By Insertion Order No
TreeSet No No Sorted By natural order or custom comparison order
Map HashMap Not in key Yes No No
HashTable Not in key Yes No No
LinkedHashMap Not in key Yes By Insertion Order No
TreeMap Not in key Yes Sorted By natural order or custom comparison order
Queue PriorityQueue No No Sorted By to do order

Maven Resources Plugin Use


How to Copy Parent Maven Project Resources to its Sub Modules ?


1) We need to register plugin in parent project pom.xml as below :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <version>2.6</version>
</plugin>

2) We need to entry as below in pom.xml of sub module project.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <executions>
        <execution>
            <id>copy-parent-resources</id>
            <phase>process-sources</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/${project.artifactId}/WEB-INF</outputDirectory>
                <resources>
                    <resource>
                        <directory>${project.parent.basedir}/src/main/resources</directory>
                        <filtering>true</filtering>
                        <!-- <includes> <include>**/*.xml</include> </includes> -->
                        <!-- <excludes> <exclude>**/*.properties</exclude> </excludes> -->
                    </resource>
                </resources>
            </configuration>
        </execution>
    </executions>
</plugin>

Note
<outputDirectory> value will be your target directory where resources need to copied.
<directory> value will be your parent project directory, from where resources to be copied.
You can also include or exclude particular file types for copying files.
 

Maven Web Project Using Eclipse


Tutorial for creating and running maven web project using eclipse.

Required Software :

1) Eclipse Indigo - It has better support for m2e plugin
2) Apache Maven 3.0.4
3) Apache Tomcat 7.0.28

Please check that you have properly configured MAVEN_HOME,JAVA_HOME and %MAVEN_HOME%/bin in PATH environment variables.


Step 1 : Install eclipse m2e plugin in Eclipse

Open eclipse Go to Install New Software -> Add -> Write below Details and install this plugin.

Name : Maven Integration for Eclipse Update Site
Location : http://download.eclipse.org/technology/m2e/releases/1.2/1.2.0.20120903-1050
Note : Make Sure that you select Maven Integration for WTP extension.

Step 2 : Create Maven Web Project
Create new Maven Project from eclipse.



Click Next




















Select Artifact Id : maven-archtype-webapp

















Click Next.

Enter Group Id and Artifact Id details.



















Click Finish.

Step-3 Configure The Tomcat Server

For running maven project in tomcat you require maven tomcat plugin.


Your Final pom.xml as below

<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>com.hardik4u</groupId>
    <artifactId>mavendemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>mavendemo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>mavendemo</finalName>
        <!-- Maven Tomcat Plugin -->
        <plugins>

            <!-- Maven Tomcat Plugin -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <server>local-tomcat</server>
                    <path>/mavendemo</path>
                </configuration>
            </plugin>
            <!-- Maven compiler plugin -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>



 You also need to register tomcat server with the maven configuration.
Open %MAVEN_HOME%/conf/settings.xml
Find <servers> tag,you need to append server credentials between <servers> tag as below

<!-- Tomcat Admin credentials -->
    <server>
      <id>local-tomcat</id>
      <username>tomcat</username>
      <password>tomcat</password>
    </server>


    
 
If you have not tomcat user with admin credentials then you can add it from the <TOMCAT_HOME>/conf/tomcat-users.xml as below


<tomcat-users>
    <role rolename="tomcat"/>
    <role rolename="admin-gui"/>
    <role rolename="admin-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-status"/>
    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <role rolename="manager-status"/>
  <user username="tomcat" password="tomcat" roles="tomcat,admin-gui,admin-script,manager-jmx,manager-status,manager-gui,manager-script,manager-status"/>
</tomcat-users>



Step 4 : Deploy on the tomcat sever
Start the Tomcat and go to the project root(location of pom.xml) from the command prompt.

Run the below command

mvn tomcat:deploy


it will deploy the project war file into the tomcat.

Hit the URL http://localhost:8080/mavendemo/

Referance :

http://mojo.codehaus.org/tomcat-maven-plugin/plugin-info.html

Struts2 With Spring




1.Project Structure

Struts - 2.3.4 - MVC layer
Spring - 3.0.7 - Dependacy Injection (Service Layer,DAO layer)
Hibernate -  3.6 - Persistance Layer
Snap shows the eclipse project folder structure for this POC.


2.Required Libs


antlr-2.7.6.jar
aopalliance-1.0.jar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
classworlds-1.1.jar
commons-beanutils-1.8.0.jar
commons-chain-1.2.jar
commons-collections-3.1.jar
commons-digester-2.0.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-logging-api-1.1.jar
commons-validator-1.3.1.jar
dom4j-1.6.1.jar
dwr-1.1.1.jar
ezmorph-1.0.6.jar
freemarker-2.3.19.jar
google-collections-1.0.jar
google-gxp-0.2.4-beta.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
javassist-3.11.0.GA.jar
json-lib-2.3-jdk15.jar
jta-1.1.jar
juli-6.0.18.jar
mysql-connector-java-5.1.18.jar
ognl-3.0.5.jar
org.apache.felix.bundlerepository-1.2.1.jar
org.apache.felix.framework-1.4.1.jar
org.apache.felix.main-1.4.1.jar
org.apache.felix.shell-1.0.2.jar
org.apache.felix.shell.tui-1.0.2.jar
org.springframework.asm-3.0.7.RELEASE.jar
org.springframework.beans-3.0.7.RELEASE.jar
org.springframework.context-3.0.7.RELEASE.jar
org.springframework.context.support-3.0.7.RELEASE.jar
org.springframework.core-3.0.7.RELEASE.jar
org.springframework.expression-3.0.7.RELEASE.jar
org.springframework.jdbc-3.0.7.RELEASE.jar
org.springframework.orm-3.0.7.RELEASE.jar
org.springframework.test-3.0.7.RELEASE.jar
org.springframework.transaction-3.0.7.RELEASE.jar
org.springframework.web-3.0.7.RELEASE.jar
oro-2.0.8.jar
oval-1.31.jar
plexus-container-default-1.0-alpha-10.jar
plexus-utils-1.2.jar
sitemesh-2.4.2.jar
slf4j-api-1.6.1.jar
spring-aop-3.0.5.RELEASE.jar
spring-asm-3.0.5.RELEASE.jar
spring-beans-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar
spring-core-3.0.5.RELEASE.jar
spring-expression-3.0.5.RELEASE.jar
spring-test-3.0.5.RELEASE.jar
spring-web-3.0.5.RELEASE.jar
struts2-core-2.3.4.1.jar
struts2-spring-plugin-2.3.4.1.jar
testng-5.1-jdk15.jar
tiles-api-2.0.6.jar
tiles-core-2.0.6.jar
tiles-jsp-2.0.6.jar
velocity-1.6.3.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.2.jar
xwork-core-2.3.4.1.jar

3.Configuration


File : web.xml
We need to implement filter for struts2 and listner for spring3 integration.

<?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">

    <display-name>S2 Spring3 Integration-EIS</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

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


File : applicationContext.xml
We need to define action as a bean in spring context file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Hibernate Configuration -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springexp1" />
        <property name="username" value="hardik4u" />
        <property name="password" value="hardik4u" />
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>

            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.hardik4u.model.Employee</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- DAO layer -->
    <bean id="employeeDAO" class="com.hardik4u.dao.EmployeeDAOImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Service layer -->
    <bean id="empService" class="com.hardik4u.service.EmpServiceImpl">
        <property name="employeeDAO" ref="employeeDAO" />
    </bean>

    <!-- Web layer -->
    <bean id="empList" class="com.hardik4u.web.EmployeeAction">
        <property name="empService" ref="empService" />
    </bean>

</beans>



File : struts.xml
This file used to define struts2 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="true" />

    <package name="default" namespace="/" extends="struts-default">

        <action name="empList" class="com.hardik4u.web.EmployeeAction"
            method="list">
            <result name="success">employee/list.jsp</result>
        </action>
            <action name="empAdd" class="com.hardik4u.web.EmployeeAction"
            method="add">
            <result type="redirectAction">
                <param name="actionName">empList</param>
            </result>
        </action>
    </package>
</struts>


4.Model Class


File : Employee.java

package com.hardik4u.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="employee")
        
public class Employee implements Serializable {

    @Id
    @GeneratedValue
    private Long Id;

    @Column(name="username",unique=true,nullable=false)
    private String username;
    
    @Column(name="password")
    private String password;
    
    @Column(name="empcode")
    private String empCode;
    
    @Column(name="name")
    private String name;
    
    @Column(name="grade")
    private String grade;

    
    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        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 getEmpCode() {
        return empCode;
    }

    public void setEmpCode(String empCode) {
        this.empCode = empCode;
    }

    public String getName() {
        return name;
    }

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

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

        
}



5.DAO layer


File : EmployeeDAO.java

package com.hardik4u.dao;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.hardik4u.model.Employee;

@Transactional
public interface EmployeeDAO {

    public List getAllEmployees();
    public void addEmployee(Employee emp);
}
File : EmployeeDAOImpl.java
package com.hardik4u.dao;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.hardik4u.model.Employee;

public class EmployeeDAOImpl implements EmployeeDAO {

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public List getAllEmployees() {
        List returnValue = getSessionFactory().getCurrentSession()
                .createQuery("from Employee emp").list();
        return returnValue;
    }

    public void addEmployee(Employee emp) {
        getSessionFactory().getCurrentSession().save(emp);

    }
}

6.Service layer


File : EmpService.java

package com.hardik4u.service;

import java.util.List;
import com.hardik4u.model.Employee;

public interface EmpService {

    public List getAllEmployees();
    public void addEmployee(Employee emp);
}
File : EmpServiceImpl.java
package com.hardik4u.service;

import java.util.List;
import java.util.Map;

import com.hardik4u.dao.EmployeeDAO;
import com.hardik4u.model.Employee;

public class EmpServiceImpl implements EmpService {

    public Map<String, Employee> empList;
    private EmployeeDAO employeeDAO;

    public void setEmployeeDAO(EmployeeDAO employeeDAO) {
        this.employeeDAO = employeeDAO;
    }

    public List getAllEmployees() {
        return employeeDAO.getAllEmployees();
    }

    public void addEmployee(Employee emp) {
        employeeDAO.addEmployee(emp);
    }

}


7. Struts Actions


File : EmployeeAction.java

package com.hardik4u.web;

import java.util.List;

import com.hardik4u.model.Employee;
import com.hardik4u.service.EmpService;
import com.opensymphony.xwork2.ActionSupport;

public class EmployeeAction extends ActionSupport {

    /* This method for listing employee */

    public String list() throws Exception {

        empList = empService.getAllEmployees();
        System.out.println(empList.size());
        return SUCCESS;
    }

    /* This method for adding employee */
    public String add() throws Exception {

        empService.addEmployee(emp);
        return SUCCESS;
    }

    private Employee emp;

    public Employee getEmp() {
        return emp;
    }

    public void setEmp(Employee emp) {
        this.emp = emp;
    }

    private List empList;

    /* This method will push the object in ActionContext for accessing it in JSP */
    public List getEmpList() {
        return empList;
    }

    /* It will be initialized through Spring factory */
    private EmpService empService;

    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }

}

8. View layer


File : index.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>Welcome to EIS</title>
</head>
<body>
<a href="<s:url action='empList'/>">Employee List</a>
</body>
</html>


File : employee/list.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>Employee List</title>
</head>
<body>

    <s:form action="empAdd">
            <s:textfield name="emp.empCode"  label="Employee Code"/>
            <s:textfield name="emp.username" label="UserName"/>
        <s:textfield name="emp.name"  label="Name"/>
        <s:password name="emp.password" label="Password" />
        <s:textfield name="emp.grade" label="Grade"/>
        <s:submit value="Save"></s:submit>
        
    </s:form>

    <table width="70%" border="1">
        <thead>
            <tr>
                <td>Emp. Code</td>
                <td>UserName</td>
                <td>Name</td>
                <td>Band</td>
                <td>#</td>
            </tr>
        </thead>
        <tbody>
            <s:iterator var="empList" value="empList">
                <tr>
                    <td><s:property value="empCode" /></td>
                    <td><s:property value="username" /></td>
                    <td><s:property value="name" /></td>
                    <td><s:property value="grade" /></td>
                    <td></td>

                </tr>

            </s:iterator>
        </tbody>
    </table>
</body>
</html>


9. Download eclipse Project


From Here

Please get in touch or comment in case of any issues.

cheers :)

Spring Security Tutorial Part-2 (Using Database)



Spring Security using database

In this part, we will implement Spring security authentication via database.

We will apply change to files or add new files on top of  the first part of tutorial.

First we will create tables and fill basic data via below SQL script. It will be used in our example

CREATE TABLE  employee (
  `Id` bigint(20) NOT NULL AUTO_INCREMENT,
  `password` varchar(255) DEFAULT NULL,
  `username` varchar(255) NOT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `username` (`username`)
);
CREATE TABLE  roles (
  `Id` bigint(20) NOT NULL AUTO_INCREMENT,
  `role` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `role` (`role`)
);
DROP TABLE IF EXISTS `springexp`.`employee_roles`;
CREATE TABLE  `springexp`.`employee_roles` (
  `employee_Id` bigint(20) NOT NULL,
  `roles_Id` bigint(20) NOT NULL,
  PRIMARY KEY (`employee_Id`,`roles_Id`),
  KEY `fk_r_id` (`roles_Id`),
  KEY `fk_e_id` (`employee_Id`),
  CONSTRAINT `fk_e_id` FOREIGN KEY (`employee_Id`) REFERENCES `employee` (`Id`),
  CONSTRAINT `fk_r_id` FOREIGN KEY (`roles_Id`) REFERENCES `roles` (`Id`)
);
insert into employee values (1,"hardik","hardik");
insert into employee values (2,"vihan","vihan");

insert into roles values(1,"ROLE_USER");
insert into roles values(2,"ROLE_ADMIN");

insert into employee_roles values (1,1);
insert into employee_roles values (1,2);
insert into employee_roles values (2,1);
commit;


Configuration

File : application-hibernate.xml (New)
location : /WEB-INF

This file contains datasource,hibernate properties and DAO and service layer related beans definition.


<?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-3.0.xsd">


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springexp" />
        <property name="username" value="root" />
        <property name="password" value="test@123" />
    </bean>


    <!-- Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <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.hbm2ddl.auto">update</prop>

            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.hardik4u.model.Employee</value>
                <value>com.hardik4u.model.EmpRoles</value>
            </list>

        </property>
    </bean>

    <!-- DAO support -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="employeeDAO" class="com.hardik4u.dao.EmployeeDAO">
        <property name="hibernateTemplate" ref="hibernateTemplate" />
    </bean>

    <!-- Service layer -->
       <bean id="empService" class="com.hardik4u.service.EmpServiceImpl">
           <property name="employeeDAO" ref="employeeDAO" />
       </bean>


</beans>



File : web.xml (Changed)
location : /WEB-INF

<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">

    <display-name>Spring Security 3 Tutorial</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
              /WEB-INF/application-security.xml
              /WEB-INF/application-hibernate.xml
        </param-value>
    </context-param>
    <!--  Filter for the Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- - Provides core MVC application controller. See eis-servlet.xml. -->
    <servlet>
        <servlet-name>eis</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>eis</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>




  Java Source

File : Employee.java (changed)


package com.hardik4u.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Table(name="employee")
        
public class Employee implements UserDetails,Serializable {

    @Id
    @GeneratedValue
    private Long Id;
    
    @Column(name="username",unique=true,nullable=false)
    private String username;
    
    @Column(name="password")
    private String password;
    
    @OneToMany(fetch = FetchType.EAGER)
    @Column(name="roles",unique=false)
    private Set<EmpRoles> roles;

    public Employee()
    {
        
    }
    public Employee(String username, String password, Set<EmpRoles> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public Set<EmpRoles> getRoles() {
        return roles;
    }

    public void setRoles(Set<EmpRoles> roles) {
        this.roles = roles;
    }

    public boolean isEnabled() {
        return true;
    }

    public boolean isAccountNonExpired() {
        return true;
    }

    public boolean isCredentialsNonExpired() {
        return true;
    }

    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {

        List<GrantedAuthority> l1 = new ArrayList();

        for (EmpRoles emplRole : roles) {
            l1.add(new GrantedAuthorityImpl(emplRole.getRole()));
        }
        return l1;
    }

    
    @Override
    public String getPassword() {
        return username;
    }

    @Override
    public String getUsername() {
        return password;
    }


}

File : EmpRoles.java (Changed)

package com.hardik4u.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="roles")
public class EmpRoles implements Serializable{

    @Id
    @GeneratedValue
    private Long Id;
        
    private String role;
    
    @Column(name="role",unique=true,nullable=false)
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
    
        
}


File : CustomerUserDetailService.java (Changed)

package com.hardik4u.security;

import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.ContextLoader;
import com.hardik4u.model.Employee;
import com.hardik4u.service.EmpServiceImpl;

public class CustomUserDetailService implements UserDetailsService{

    
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        
        ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();  
        EmpServiceImpl empServiceImpl =(EmpServiceImpl)ctx.getBean("empService");  
        Employee localEmp = empServiceImpl.getEmployeeByUsername(username);
        return localEmp;
        
    }
    
}


File : EmployeeDAO.java(New File)

package com.hardik4u.dao;

import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.hardik4u.model.Employee;
public class EmployeeDAO {

    private HibernateTemplate hibernateTemplate;

     public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
      this.hibernateTemplate = hibernateTemplate;
     } 
    
     public Employee findSampleByCity(String username) {
         List<Employee> results = hibernateTemplate.find("from Employee"+
           " where username = ?",new Object[] {username});
          return results.size() > 0 ? (Employee) results.get(0) : null;
        } 
    
}



you can download source code from the below location.

Download File (eclipse Project)





Hope this will help you my friends. you can get in touch in case of any queries or help.

Cheers :)

Spring Security Tutorial Part-1



>>Second Part

Please find below complete example of the spring security 3.we will create employee information system for this example.

In the second part we will implement hibernate and spring security will check credentials from the DB.

If you require source for this example, please get in touch!





Configuration Part

We require below list of jar files for spring security,Spring MVC example.There are several addition jars but it has been added it for future reference.

antlr-2.7.6.jar
aopalliance-1.0.jar
commons-beanutils-1.8.3.jar
commons-codec.jar
commons-collections-3.2.1.jar
commons-configuration-1.7.jar
commons-digester-1.8.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-annotations-3.5.6-Final.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.5.6-Final.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate-search192762.jar
hibernate-validator-4.1.0.Final.jar
javassist-3.11.0.GA.jar
jstl-1.2.jar
jta.jar
log4j-1.2.16.jar
mysql-connector-java-5.1.18.jar
org.springframework.orm-3.0.1.RELEASE-A.jar
slf4j-api-1.6.4.jar
spring-aop-3.0.6.RELEASE.jar
spring-asm-3.0.6.RELEASE.jar
spring-beans-3.0.6.RELEASE.jar
spring-context-3.0.6.RELEASE.jar
spring-context-support-3.0.6.RELEASE.jar
spring-core-3.0.6.RELEASE.jar
spring-expression-3.0.6.RELEASE.jar
spring-jdbc-3.0.1.RELEASE.jar
spring-security-acl-3.0.2.RELEASE.jar
spring-security-config-3.0.2.RELEASE.jar
spring-security-core-3.0.2.RELEASE.jar
spring-security-taglibs-3.0.2.RELEASE.jar
spring-security-web-3.0.2.RELEASE.jar
spring-tx-3.0.1.RELEASE.jar
spring-web-3.0.6.RELEASE.jar
spring-webmvc-3.0.6.RELEASE.jar


File : web.xml
<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">

    <display-name>Spring Security 3 Tutorial</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
              /WEB-INF/application-security.xml
        </param-value>
    </context-param>
    <!--  Filter for the Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- - Provides core MVC application controller. See eis-servlet.xml. -->
    <servlet>
        <servlet-name>eis</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>eis</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

File : eis-servlet.xml

This file contains Spring MVC configuration,We will create JSPs and Controllers later on.
<?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-3.0.xsd">

       <bean name="/employee/list.html" class="com.hardik4u.web.EmployeeController">
      </bean>

    <bean name="/admin/home.html" class="com.hardik4u.web.AdminController">
      </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>


File : application-security.xml

This file contains the configuration of Spring Security. Here we have created two custom beans for providing customization for application as below:
  • customEncoder - This bean will implement existing password encoder of spring security
  • customUserService - This bean will implement existing user details service of existing spring security.
This two files will perform vital part for authenticate and authorize user via spring security.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<global-method-security pre-post-annotations="enabled" />

<http use-expressions="true" access-denied-page="/accessDenied.jsp">
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/employee/**" access="isAuthenticated()" />
        <!-- Allow all other requests. In a real application you should adopt a 
            whitelisting approach where access is not allowed by default -->
        <intercept-url pattern="/**" access="permitAll" />
        <form-login />
        
        <logout logout-success-url="/loggedout.jsp" />
        
        <remember-me />
        <!-- Uncomment to enable X509 client authentication support <x509 /> -->
        <!-- Uncomment to limit the number of sessions a user can have -->
        <session-management invalid-session-url="/timeout.jsp">
            <concurrency-control max-sessions="1"
                error-if-maximum-exceeded="true" />
        </session-management>

    </http>
<!-- User service and password encoding configuration -->
    <beans:bean id="customEncoder" class="com.hardik4u.security.CustomPasswordEncoder" />
    <beans:bean id="customUserService"
        class="com.hardik4u.security.CustomUserDetailService" />

    <authentication-manager>
        <authentication-provider user-service-ref="customUserService">
            <password-encoder ref="customEncoder" />
        </authentication-provider>
    </authentication-manager>

</beans:beans>
 View Part



File : index.jsp
Path: /
<%@ page session="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
  <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <link rel="stylesheet" href="<c:url value='/static/css/tutorial.css'/>" type="text/css" />
      <title>Employee Information System - Home</title>
  </head>
<body>
<div id="content">
<h1>Home Page</h1>
<p>
Anyone can view this page.
</p>
<p>
Your principal object is....: <%= request.getUserPrincipal() %>
</p>
<sec:authorize url='/employee/list.html'>
<p>
You can currently access "/employee" URLs.
</p>
</sec:authorize>
<sec:authorize url='/admin/home.html'>
<p>
You can currently access "/admin" URLs.
</p>
</sec:authorize>

<p>
<a href="employee/list.html">Employee List</a></p>
<p><a href="admin/home.html">Admin Home</a></p>
</div>
</body>
</html>
File : accessDenied.jsp
Path: /
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>No Permission</title>
</head>
<body>
<h3>You have no permission to access this page</h3>
<p><a href="../">Home</a></p>
</body>
</html>

File : loggedout.jsp
Path: /
 <%@page session="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <title>Logged Out</title>
  </head>
<body>
<div id="content">
<h2>Logged Out</h2>
<p>
You have been logged out. <a href="<c:url value='/'/>">Start again</a>.
</p>
</div>
</body>
</html>


File : timeout.jsp
Path: /
<%@page session="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <title>Session Timeout</title>
  </head>
<body>
<div id="content">
<h2>Invalid Session</h2>
<p>
Your session appears to have timed out. Please <a href="<c:url value='/'/>">start again</a>.
</p>
</div>
</body>
</html>

File : home.jsp 
Path: /WEB-INF/JSP/admin
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Employee Information System - Admin Home</title>
</head>
<body>
<p>This is Admin Home only ROLE_ADMIN have access to this page.</p>

<p><a href="../">Home</a></p>
<p><a href="../j_spring_security_logout">Logout</a></p>
</body>
</html>

File : list.jsp
Path: /WEB-INF/JSP/employee
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Employee Information System - Employee List</title>
</head>
<body>
This page can be viewed by Authentic Person, either have ROLE_USER,ROLE_ADMIN

<p><a href="../">Home</a></p>
<p><a href="../j_spring_security_logout">Logout</a></p>
</body>
</html>
Java Resources

Model Classes


File : Employee.java
This class is extending the org.springframework.security.core.userdetails.UserDetails class. The reason behind is that Spring's  UserDetailService class has method loadUserbyUsername - which we are using to authenticate and authorized user via spring security. This method returning UserDetails object of Spring Security. So we can return Employee model object in spite of UserDetails from this method and we can use directly object for other business logic.
package com.hardik4u.model;

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

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

public class Employee implements UserDetails {

    private String username;
    private String password;
    private List<emproles> roles;

    public Employee(String username, String password, List<emproles> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    public List<emproles> getRoles() {
        return roles;
    }

    public void setRoles(List<emproles> roles) {
        this.roles = roles;
    }

    public boolean isEnabled() {
        return true;
    }

    public boolean isAccountNonExpired() {
        return true;
    }

    public boolean isCredentialsNonExpired() {
        return true;
    }

    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public Collection getAuthorities() {

        List<grantedauthority> l1 = new ArrayList();

        for (EmpRoles emplRole : roles) {
            l1.add(new GrantedAuthorityImpl(emplRole.getRole()));
        }
        return l1;
    }

    @Override
    public String getPassword() {
        return username;
    }

    @Override
    public String getUsername() {
        return password;
    }

}


File : EmpRoles.java

package com.hardik4u.model;

public class EmpRoles{

 private String role;

 public String getRole() {
  return role;
 }

 public void setRole(String role) {
  this.role = role;
 }
 
}

Spring Security Extended Classes


File : CustomUserDetailService.java
This class is extending UserDetailsService class of Spring Security. We will extend the method loadUserByUsername method to loadUser in SecurityContext
package com.hardik4u.security;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.hardik4u.model.Employee;
import com.hardik4u.service.EmpServiceImpl;

public class CustomUserDetailService implements UserDetailsService{

 @Override
 public UserDetails loadUserByUsername(String username)
   throws UsernameNotFoundException {
  // TODO Auto-generated method stub
  
  EmpServiceImpl empServiceImpl = new EmpServiceImpl();
  empServiceImpl.setEmployeeList();
  Employee localEmp = empServiceImpl.getEmployeeByUsername(username);
  
  return localEmp;
  
 }

}
 
File : CustomPasswordEncoder.java
This class is used to validate password using spring security. Authentication provider require this bean's injection.
package com.hardik4u.security;

import org.springframework.security.authentication.encoding.PasswordEncoder;

public class CustomPasswordEncoder implements PasswordEncoder{

 @Override
 public String encodePassword(String arg0, Object arg1) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public boolean isPasswordValid(String password, String userInput, Object arg2) {
  // TODO Auto-generated method stub
  return password.equals(userInput) ? true : false;
 }

}

Service layer

File : EmpServiceImpl.java
package com.hardik4u.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hardik4u.model.EmpRoles;
import com.hardik4u.model.Employee;

public class EmpServiceImpl {

    public Map<string,employee> empList;
     
    public Employee getEmployeeByUsername(String username) {
         
        return empList.get(username);
    }
     
    public void setEmployeeList()
    {
        /* create Roles */
        EmpRoles empRoles1 = new EmpRoles();
        empRoles1.setRole("ROLE_ADMIN");
         
        EmpRoles empRoles2 = new EmpRoles();
        empRoles2.setRole("ROLE_USER");
         
        empList = new HashMap<string,employee>();
         
        /* create Roles List */
        List roleslist1 = new ArrayList<emproles>();
        roleslist1.add(empRoles1);
        roleslist1.add(empRoles2);
         
        List roleslist2 = new ArrayList<emproles>();
        roleslist2.add(empRoles2);
         
        /* create Employees */
        Employee emp1 = new Employee("hardik","hardik",roleslist1);
        Employee emp2 = new Employee("vihan","vihan",roleslist2);
     
        empList.put(emp1.getUsername(),emp1);
        empList.put(emp2.getUsername(), emp2);
    }

}



Controllers

File : AdminController.java

package com.hardik4u.web;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.hardik4u.model.Employee;

public class AdminController implements Controller{

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0,
   HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  ModelAndView mav = new ModelAndView("admin/home");
 
  // Employee emp = (Employee)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
      return mav;
 }

}
File : EmployeeController.java

package com.hardik4u.web;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class EmployeeController implements Controller{

 @Override
 public ModelAndView handleRequest(HttpServletRequest arg0,
   HttpServletResponse arg1) throws Exception {
  // TODO Auto-generated method stub
  ModelAndView mav = new ModelAndView("employee/list");
      return mav;
 }

} 
>>Second Part

How to Sign Jar File



Steps for the Contract Sender

1.       Create a JAR File Containing the Contract, using the jar tool.
2.       Generate Keys (if they don't already exist), using the keytool -genkey command.
Optional Step: Generate a certificate signing request (CSR) for the public key certificate, and import the response from the certification authority. For simplicity and since you are only pretending to be Nirav Bhavsar, this step is omitted. See Generating a Certificate Signing Request (CSR) for a Public Key Certificate for more information.
3.       Sign the JAR File, using the jarsigner tool and the private key generated in step 2.
4.       Export the Public Key Certificate, using the keytool -export command. Then supply the signed JAR file and the certificate to the receiver, Hardik.
  
Create a JAR File Containing the refeJar :

jar cvf refeJar.jar refeJar

This command creates a JAR file named refeJar.jar and places the refeJar file inside it.

Generate Keys :

keytool -genkey -alias signLegal -keystore examplestanstore

Sign the JAR File

jarsigner -keystore examplestanstore -signedjar  srefeJar.jar    refeJar.jar signLegal

Export the Public Key Certificate

keytool -export -keystore examplestanstore -alias signLegal -file NiravBhavsar.cer

Steps for the Contract Receiver

1.       Import the Certificate as a Trusted Certificate, using the keytool -import command.
2.       Verify the JAR File Signature, using the jarsigner tool.

Import the Certificate as a Trusted Certificate

keytool -import -alias nirav -file NiravBhavsar.cer -keystore exampleHardikstore
 
 Verify the JAR File Signature

jarsigner -verify -verbose -keystore exampleHardikstore srefeJar.jar




Tag : ,

- Copyright © Hardik4U - Skyblue - Powered by Blogger - Designed by Johanes Djogan -