Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg
Showing posts with label ZK Spring. Show all posts
Showing posts with label ZK Spring. Show all posts

Friday, 19 April 2013

ZK MVVM Form Binding CRUD with Spring and Hibernate

Posted on 02:56 by Unknown

In this series of articles, we will see examples for various concept of ZK Framework.

About the application
This is a small application to store the users information such as first name, last name, email, login id , password, etc. We will have the listing screen which will display all the users in the database. And from this listing screen, we will be able to add new users and edit the existing users in the database.

MySQL table structure.

CREATE TABLE `userprofile` (
`id` bigint(20) NOT NULL auto_increment,
`firstname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`middlename` varchar(2) default NULL,
`userAccountNumber` varchar(50) NOT NULL,
`DOB` date default NULL,
`SSN` varchar(50) default NULL,
`address1` varchar(200) NOT NULL,
`address2` varchar(200) default NULL,
`city` varchar(100) NOT NULL,
`state` varchar(2) NOT NULL,
`zipcode` varchar(12) NOT NULL,
`email` varchar(100) NOT NULL,
`userloginid` varchar(20) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Insert some records in the database for the above table

Technologies Used
    1. ZK 6.5.2 CE Version
    3. Hibernate Core Version 4.1.10 Final
    4. Spring ORM Version 3.2.0
    5. MySQL version 5
    6. Maven 3

First let us setup the development environment. Download this document and follow the step by step instruction to install the necessary software’s.

Part 1: This post explain how to create ZK Maven project in eclipse IDE as step by step.
Part 2: This post talks about creating Domain, DAO and Service Layer.
Part 3: Spring Integration with Hibernate
Part 4: Presentation Layer
Part 5: Change the look and feel.
Part 6: Spring security 3 integration with hibernate 4
Part 7: More features such as Data filter, etc..
Part 8: ZK Theme customization for each user
Part 9: Bug Fixing Cycle :)
Part 10: jQuery integration with ZK Framework
Part 11: Store image in the database.
Part 12 : Validation using Hibernate Validator
Part 13 : More Validation using Hibernate Validator


You can download the source here


For online demo, click here.

Use the following user id and password to check out different theme for each user
a) For blue theme, user id : lee and password : lee.
b) For brown theme, user id : wing and password : wing
c) for Green theme, user id : dennis and password : dennis
d) For purple theme, user id : senthil and password : senthil
e) For red theme, user id : zkoss and password : zkoss



Screen shots

image



image



image

Read More
Posted in ZK MVVM, ZK MVVM CRUD, ZK Spring | No comments

Tuesday, 9 April 2013

ZK + Spring Security Custom Login form

Posted on 22:55 by Unknown

In this example, we will see step by step how to integrate ZK and Spring security

If you are new to spring security,   please read the following post

1. Spring Security hello world example
2. Spring Security Form Login Example

Now let us see how we can integrate ZK with spring security.

Part 1: In this post, we will see how to create a custom login form using ZK and ask Spring Security to use it for login authentication.
Part 2: In this post, we will see how to Implement custom UserDetailsService for spring security.
Part 3: In this post, we will see how to login with static users into the application.
Part 4: In this post, we will see how to add extra login parameters in the spring security.
Part 5: Real world Example for spring security using ZK MVC + CRUD + Hibernate + JPA + Mysql 

Read More
Posted in ZK Spring | No comments

ZK + Spring Security Login form–Part 5

Posted on 10:43 by Unknown

Connect with database and check user exists or not.

In this post, let us how we can secure ZK Application using custom spring security login form designed in ZK Framework.

So what we are going to do ?

1. We will login page and spring authentication to access the secured pages.
2. After successful authentication, we will re direct to user lists page and from which we can add/edit/delete users.
3. We will also have logout method in the listing page. On Click , it will redirect to login page again.

 

Step 1:
Follow this post and complete all the steps. At the end of the exercise, we will be able add users/edit/delete users. Now we will secure this application using ZK Login page.

Step 2:
First let us update the POM.xml as follows

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>zkloginexample5</groupId>
<artifactId>zkloginexample5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<zk.version>6.5.1</zk.version>
<commons-io>1.3.1</commons-io>
<maven.build.timestamp.format>yyyy-MM-dd</maven.build.timestamp.format>
<packname>-${project.version}-FL-${maven.build.timestamp}</packname>
</properties>
<packaging>war</packaging>
<name>The zkloginexample5 Project</name>
<description>The zkloginexample5 Project</description>
<licenses>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/lgpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<repositories>
<repository>
<id>ZK CE</id>
<name>ZK CE Repository</name>
<url>http://mavensync.zkoss.org/maven2</url>
</repository>
<repository>
<id>ZK EVAL</id>
<name>ZK Evaluation Repository</name>
<url>http://mavensync.zkoss.org/eval</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>zkmaven</id>
<name>ZK Maven Plugin Repository</name>
<url>http://mavensync.zkoss.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>${zk.version}</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

<!-- AOP dependency -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>

<!-- Persistence Management -->
<dependency> <!-- Apache BasicDataSource -->
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>

<!-- ZK 5 breeze theme <dependency> <groupId>org.zkoss.theme</groupId>
<artifactId>breeze</artifactId> <version>${zk.version}</version> <optional>true</optional>
</dependency> -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Run with Jetty -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>5</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Compile java -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<!-- Build war -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version>
</plugin>
<!-- Pack zips -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>webapp</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>zkloginexample5${packname}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>assembly/webapp.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>


Step 3:
Next we will create our login.zul. Select the webapp folder, right click, select New –>Other->zul file and enter the zul file name as login.zul
image

image
Here is the login.zul code


<?page id="loginPage" title="Digital medical sheet - Login page" onLoad="win.doOverlapped();"?>
<window id="win" title="LOGIN" border="normal" width="300px"
position="center">

<!-- this form-login-page form is also used as the
form-error-page to ask for a login again. -->
<html style="color:red" if="${not empty param.login_error}">


<![CDATA[ Your login attempt was not successful, try
again.<br/><br/> Reason:
${SPRING_SECURITY_LAST_EXCEPTION.message} ]]>


</html>

<groupbox>
<caption>Login</caption>
<h:form id="f" name="f" action="j_spring_security_check"
method="POST" xmlns:h="http://www.w3.org/1999/xhtml">
<grid>
<columns sizable="false">
<column width="50%" />
<column width="50%" />
</columns>
<rows>
<row>
<label value="User:" />
<textbox id="u" name="j_username" />
</row>
<row>
<label value="Password:" />
<textbox id="p" type="password"
name="j_password" />
</row>
<row spans="2">
<div align="center">
<h:input type="submit" value="login" />
<h:input type="reset" value="Reset" />
</div>
</row>
</rows>
</grid>
</h:form>
</groupbox>
</window>


Step 4:
Next we will update web.xml file. You can copy the content here.

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<description><![CDATA[My ZK Application]]></description>
<display-name>zkloginexample5</display-name>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Loads the Spring web application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<!-- A servlet filter capturing every user requests and sending them to
the configured security filters to make sure access is authorized. -->
<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>

<!-- Spring filter -->
<filter>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- //// -->

<!-- //// -->
<!-- ZK -->
<listener>
<description>ZK listener for session cleanup</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<description>ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>

<!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet). It
must be the same as <url-pattern> for the update engine. -->
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<!-- Optional. Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if you configure
a filter to post-processing the output, you might have to disable it. Default:
true <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> -->
<!-- [Optional] Specifies the default log level: OFF, ERROR, WARNING, INFO,
DEBUG and FINER. If not specified, the system default is used. <init-param>
<param-name>log-level</param-name> <param-value>OFF</param-value> </init-param> -->
<load-on-startup>1</load-on-startup><!-- Must -->
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<!-- [Optional] Uncomment it if you want to use richlets. <servlet-mapping>
<servlet-name>zkLoader</servlet-name> <url-pattern>/zk/*</url-pattern> </servlet-mapping> -->
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>

<!-- [Optional] Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if your server
will do the compression, you might have to disable it. Default: true <init-param>
<param-name>compress</param-name> <param-value>true</param-value> </init-param> -->
<!-- [Optional] Specifies the AU extension for particular prefix. <init-param>
<param-name>extension0</param-name> <param-value>/upload=com.my.MyUploader</param-value>
</init-param> -->
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>

<!-- [Optional] Uncomment if you want to use the ZK filter to post process
the HTML output generated by other technology, such as JSP and velocity.
<filter> <filter-name>zkFilter</filter-name> <filter-class>org.zkoss.zk.ui.http.DHtmlLayoutFilter</filter-class>
<init-param> <param-name>extension</param-name> <param-value>html</param-value>
</init-param> <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> </filter> <filter-mapping> <filter-name>zkFilter</filter-name>
<url-pattern>your URI pattern</url-pattern> </filter-mapping> -->
<!-- //// -->

<!-- ///////////// -->
<!-- DSP (optional) Uncomment it if you want to use DSP However, it is turned
on since zksandbox uses DSP to generate CSS. <servlet> <servlet-name>dspLoader</servlet-name>
<servlet-class>org.zkoss.web.servlet.dsp.InterpreterServlet</servlet-class>
<init-param> <param-name>class-resource</param-name> <param-value>true</param-value>
</init-param> </servlet> <servlet-mapping> <servlet-name>dspLoader</servlet-name>
<url-pattern>*.dsp</url-pattern> </servlet-mapping> -->

<!-- /////////// -->
<!-- [Optional] Session timeout -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>

<!-- [Optional] MIME mapping -->
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpeg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>text/javascript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xls</extension>
<mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xml</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zul</extension>
<mime-type>text/html</mime-type>
</mime-mapping>

<welcome-file-list>
<welcome-file>UserList.zul</welcome-file>
<welcome-file>index.zhtml</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

Step 5:
Next we will create spring-security.xml in the webapp\web-INF folder. Select the webapp folder, right click, Select New->Other->xml file and enter the file name as “spring-security.xml”

image

image
You can copy the code from here.


<!-- Spring namespace-based configuration -->

<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<!-- ====================================================== -->
<!-- For catching the @Secured annotation methods -->
<!-- Tells the Spring Security engine that we will use Spring Security's -->
<!-- pre and post invocation Java annotations (@PreFilter, @PreAuthorize, -->
<!-- @PostFilter, -->
<!-- @PostAuthorize) to secure service layer methods.. -->
<!-- Look in GFCBaseCtrl.java onEvent() method. -->
<!-- ====================================================== -->

<!-- Enable the @Secured annotation to secure service layer methods -->
<global-method-security secured-annotations="enabled" />

<http auto-config="true">

<!-- ====================================================== -->
<!-- If we have our own LoginPage. So we must -->
<!-- tell Spring the name and the place. -->
<!-- In our case we take the same page -->
<!-- for a error message by a failure. -->
<!-- Further the page after a successfully login. -->
<!-- ====================================================== -->
<form-login login-page="/login.zul"
authentication-failure-url="/login.zul?login_error=1"
default-target-url="/UserList.zul" always-use-default-target="true" />
<intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/*.zul" access="IS_AUTHENTICATED_REMEMBERED" />
</http>

<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService">

</authentication-provider>
</authentication-manager>

<beans:bean id="myUserDetailsService" class="crudexample.service.MyUserDetailsService" />


</beans:beans>



Step 6:
Next we will update applicationContext.xml file. You can copy the content here.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


<!-- The LocalEntityManagerFactoryBean creates an EntityManagerFactory suitable for environments which solely use JPA for data access.
The factory bean will use the JPA PersistenceProvider autodetection mechanism (according to JPA's Java SE bootstrapping) and,
in most cases, requires only the persistence unit name to be specified:
-->

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ZKExamples" />
</bean>


<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!-- tell spring to use annotation based congfigurations -->
<!-- It allow us to use @Autowire, @Required and @Qualifier annotations. -->

<context:annotation-config />

<!-- tell spring where to find the beans -->
<!-- tells Spring to scan the code for injectable beans under the package (and all its subpackages) specified. -->
<!-- It allow @Component, @Service, @Controller, etc.. annotations. -->
<context:component-scan base-package="crudexample" />

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

<!-- This will ensure that hibernate or jpa exceptions are automatically
translated into Spring's generic DataAccessException hierarchy for those
classes annotated with Repository -->

<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean id="CRUDService" class="crudexample.service.CRUDServiceImpl" />

</beans>

Step 7:
Next we will need to update our dao and service layer by adding one more method to execute namedquery.
CRUDDao.java


package crudexample.dao;

import java.util.List;

public interface CRUDDao {

<T> List<T> getAll(Class<T> klass);

<T> T save(T t);

<T> T GetUniqueEntityByNamedQuery(String query, Object... params);

<T> void delete(T t);
}
CRUDDaoImpl.java

package crudexample.dao;

import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

@Repository
public class CRUDDaoImpl implements CRUDDao {

@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager em;

public EntityManager getEm() {
return em;
}

public void setEm(EntityManager em) {
this.em = em;
}

@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> klass) {
return em.createQuery("Select t from " + klass.getSimpleName() + " t")
.getResultList();
}

public <T> T save(T t) {
T newRecord = null;
newRecord = em.merge(t);
return newRecord;
}

public <T> void delete(T t) {
em.remove(em.merge(t));
em.flush();
}

@SuppressWarnings("unchecked")
public <T> T GetUniqueEntityByNamedQuery(String query, Object... params) {

System.out.println("results is ");
Query q = this.em.createNamedQuery(query);
int i = 1;

for (Object o : params) {
q.setParameter(i, o);
}

List<T> results = q.getResultList();
System.out.println("results is "+ results.size());
T foundentity = null;
if (!results.isEmpty()) {
// ignores multiple results
foundentity = results.get(0);
}
return foundentity;
}
}


CRUDService.java

package crudexample.service;

import java.util.List;

public interface CRUDService {
<T> List<T> getAll(Class<T> klass);

<T> T save(T t);

<T> T GetUniqueEntityByNamedQuery(String query, Object... params);

<T> void delete(T t);


}


CRUDServiceImpl.java

package crudexample.service;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import crudexample.dao.CRUDDao;


@Service
public class CRUDServiceImpl implements CRUDService {


@Autowired
private CRUDDao CRUDDao;

@Transactional(readOnly = true)
public <T> List<T> getAll(Class<T> klass) {
return CRUDDao.getAll(klass);
}


@Transactional
public <T> T save(T t) {
T newRecord = null;
newRecord = CRUDDao.save(t);
return newRecord;
}

@Transactional
public <T> void delete(T t) {
CRUDDao.delete(t);
}

@Transactional
public <T> T GetUniqueEntityByNamedQuery(String query, Object... params) {
return CRUDDao.GetUniqueEntityByNamedQuery(query, params);
}
}
Step 8:
Next we will create our custom authentication by extending spring UserDetailsService interface. Select the “service” package, right click, select new->Other->Class and enter the class name as “MyUserDetailsService”.

package crudexample.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import crudexample.domain.Appusers;

public class MyUserDetailsService implements UserDetailsService {

@Autowired
private CRUDService CRUDService;

/*
* You just have to make sure that the user-by-username-query returns three
* fields. 1) the userName 2) the password 3) boolean for is the user
* active. If you don't have an active field, make your query always return
* true for that third field.
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {

// Declare a null Spring User
UserDetails user = null;

try {

// Search database for a user that matches the specified username
// You can provide a custom DAO to access your persistence layer
// Or use JDBC to access your database
// DbUser is our custom domain user. This is not the same as
// Spring's User

Appusers dbUser = CRUDService.GetUniqueEntityByNamedQuery(
"Appusers.findUserByUserID", username);

// Populate the Spring User object with details from the dbUser
// Here we just pass the username, password, and access level
// getAuthorities() will translate the access level to the correct
// role type

user = new User(dbUser.getUserID(), dbUser.getPassword()
.toLowerCase(), true, true, true, true,
getAuthorities());

} catch (Exception e) {
throw new UsernameNotFoundException("Error in retrieving user");
}

// Return user to Spring for processing.
// Take note we're not the one evaluating whether this user is
// authenticated or valid
// We just merely retrieve a user that matches the specified username

return user;
}

/**
* Retrieves the correct ROLE type depending on the access level, where
* access level is an Integer. Basically, this interprets the access value
* whether it's for a regular user or admin.
*
* @param access
* an integer value representing the access of the user
* @return collection of granted authorities
*/
public Collection<GrantedAuthority> getAuthorities() {
// Create a list of grants for this user
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

// All users are granted with ROLE_USER access
// Therefore this user gets a ROLE_USER by default
authList.add(new GrantedAuthorityImpl("ROLE_USER"));
// User has admin access
authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

// Return list of granted authorities
return authList;
}
}

Step 9:
Next we will add logout option in the userlist.zul file as follows. Just add one more button next add new button

	<div style="float:right">
<button label="Add New" mold="trendy" id="btnNew"
sclass="mybutton button blue small" />
<button label="Logout" mold="trendy" id="btnlogout"
sclass="mybutton button blue small" />

</div>


And also, add the following code in the controller.


	public void onClick$btnlogout(Event event)
{
Executions.sendRedirect("/j_spring_security_logout");
}

Now you select the Project and Run using tomcat server.
You can download the source
here

Read More
Posted in ZK Spring | No comments

Monday, 8 April 2013

ZK MVC CRUD With Spring 3 + JPA + Hibernate 4 Entity Manager

Posted on 11:45 by Unknown

A simple CRUD Application based on JPA.

Overview
This article will explain you step by step how to create simple CRUD application using ZK as Presentation layer with Spring 3 and JPA (Hibernate vendor).

What is JPA and why JPA
The Java Persistence API, referred as JPA is a object-relational mapping solution to enterprise Java applications.
JPA is a spec and not an implementation, so if you choose JPA, you still have to pick an implementation. You can pick Hibernate, Top link, and any other ORM that implements JPA.

Using JPA does not tie you to any particular ORM Like hibernate, toplink, etc. EntityManager provides vendor independent access to persistence. Portability across application servers and persistence products (avoids vendor lock-in).

Developers can choose the best ORM implementation according to the application requirement. For example, production can be started from the free versions of ORM implementation and when the needs arise it can be switched to the commercial version of the ORM framework. You can switch the persistence provides without changing the code. So, ORM framework independence is another another big benefit of JPA

Hibernate ORM
In this example, we are going to choose Hibernate as ORM vendor to build the simple CRUD Application.

Spring and Hibernate ORM Framework Integration.
There are lot of articles on the net about this topic. I recommend to the read following articles on this subject.

1. http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/
2. http://static.springsource.org/spring/docs/2.5.x/reference/orm.html
3. http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/
4. http://javaprogrammingtips4u.blogspot.in/2010/04/spring-integration-with-hibernate_23.html

Technologies used in this example:

1. ZK 6.5.1 CE Version.
2. Hibernate-entitymanager 4.1.9 Final
3. Spring-orm 3.2.0 Release
4. Spring-web 3.2.0 Release
5. Java mysql connector 5.1.22

In mysql, create the following table

image
Part 1: First let us setup the development environment. Download this document and follow the step by step instruction to install the necessary software’s.

Part 2: This post explain how to create ZK Maven project in eclipse IDE as step by step.
Part 3: This post explain how to configure database, user name, password, etc using persistence.xml file
Part 4: This post explain how to integrate Spring and Hibernate.
Part 5: This post explain how to create DAO and service layer for the CRUD operation.
Part 6: This post explain how to create Presentation layer using ZK Framework.


Output before with ZK Default CSS Style

image

image

Output after defining our own CSS for each component.

image

image

Video demo:
http://screencast.com/t/DFRiwmpNHq

You can download the source code here

MVVM Version of this tutorial is available here

Read More
Posted in ZK Hibernate, ZK MVC CRUD Examples, ZK Spring | No comments

Saturday, 23 March 2013

ZK + Spring Security Login form– Additional Login Parameters - Part 4

Posted on 21:02 by Unknown

Extra Spring Login Parameters.

In the last article, we have seen the complete implementation of Spring security Login without Database connection.  In this post, we will see how we can pass additional parameters from the login screen to validate. For example, in the bigger application, apart from user name and password, you may also need to get domain or company name or Client ID, etc..

So our Login screen will look like this

image

Thanks to the following post from which I frame this example
Two-Factor Authentication and Spring Security 3

Technologies used in this example:

1. ZK 6.5.1 CE Version.
2. Spring-security-core 3.0.5

Step 1:
Download this document and setup the development environment.

Step 2:
Let us create ZK Maven Project. Follow the below instruction.
In the Eclipse IDE, Select File –> New-> Other-> Maven Project as shown here.
image_thumb_thumb1_thumb5

Click Next.
image_thumb1_thumb1_thumb1
Uncheck the option “Create a simple Project(skip archetype selection) and Click next.
image_thumb2_thumb1_thumb2
Select “ZK” in the catalog and select “ZK-archetype-webapp 6.0” as shown here."
image_thumb31_thumb1_thumb1
Click Next after selecting the ZK Archetype.
image
Enter “zkloginexample4” for Group ID, Artifact id and Package. And important, please select “ZK-Version-since” from the bottom list and then select finish.
Now, the following folder structure will be created.
image

Step 3:
Next we will include the spring dependency in the POM File.
Double click the POM.XML file in the project navigator.
image_thumb7_thumb_thumb

Click on the POM.XML tab. The following modification has been done.
1. Change the ZK Version to latest CE Version.
2. Remove the Maven ZK EE Version Repository.
3. Add the spring security dependency.
Here is the modified POM.XML file.

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>zkloginexample4</groupId>
<artifactId>zkloginexample4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<zk.version>6.5.1</zk.version>
<commons-io>1.3.1</commons-io>
<maven.build.timestamp.format>yyyy-MM-dd</maven.build.timestamp.format>
<packname>-${project.version}-FL-${maven.build.timestamp}</packname>
</properties>
<packaging>war</packaging>
<name>The zkloginexample4 Project</name>
<description>The zkloginexample4 Project</description>
<licenses>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/lgpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<repositories>
<repository>
<id>ZK CE</id>
<name>ZK CE Repository</name>
<url>http://mavensync.zkoss.org/maven2</url>
</repository>
<repository>
<id>ZK EVAL</id>
<name>ZK Evaluation Repository</name>
<url>http://mavensync.zkoss.org/eval</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>zkmaven</id>
<name>ZK Maven Plugin Repository</name>
<url>http://mavensync.zkoss.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>${zk.version}</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>${zk.version}</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

<!-- ZK 5 breeze theme <dependency> <groupId>org.zkoss.theme</groupId>
<artifactId>breeze</artifactId> <version>${zk.version}</version> <optional>true</optional>
</dependency> -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Run with Jetty -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>5</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Compile java -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<!-- Build war -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version>
</plugin>
<!-- Pack zips -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<id>webapp</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>zkloginexample4${packname}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>assembly/webapp.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>


Step 4:
Next step we will update web.xml to take care spring filter.
Here is the updated web.xml file.


<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<description><![CDATA[My ZK Application]]></description>
<display-name>zkloginexample4</display-name>

<!-- ====================================================== -->
<!-- CONFIGURATION FILES -->
<!-- ====================================================== -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>

<!-- ====================================================== -->
<!-- SPRING CONTEXT LOADER -->
<!-- ====================================================== -->

<!-- The org.springframework.web.context.ContextLoaderListener class uses
a context parameter called contextConfigLocation to determine the location
of the Spring configuration file. The context parameter is configured using
the context-parameter element. The context-param element has two children
that specify parameters and their values. The param-name element specifies
the parameter's name. The param-value element specifies the parameter's value -->

<listener>
<display-name>Spring Context Loader</display-name>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Spring Security -->
<!-- A servlet filter capturing every user requests and sending them to
the configured security filters to make sure access is authorized. -->
<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>


<!-- //// -->
<!-- ZK -->
<listener>
<description>ZK listener for session cleanup</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<description>ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>

<!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet). It
must be the same as <url-pattern> for the update engine. -->
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<!-- Optional. Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if you configure
a filter to post-processing the output, you might have to disable it. Default:
true <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> -->
<!-- [Optional] Specifies the default log level: OFF, ERROR, WARNING, INFO,
DEBUG and FINER. If not specified, the system default is used. <init-param>
<param-name>log-level</param-name> <param-value>OFF</param-value> </init-param> -->
<load-on-startup>1</load-on-startup><!-- Must -->
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<!-- [Optional] Uncomment it if you want to use richlets. <servlet-mapping>
<servlet-name>zkLoader</servlet-name> <url-pattern>/zk/*</url-pattern> </servlet-mapping> -->
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>

<!-- [Optional] Specifies whether to compress the output of the ZK loader.
It speeds up the transmission over slow Internet. However, if your server
will do the compression, you might have to disable it. Default: true <init-param>
<param-name>compress</param-name> <param-value>true</param-value> </init-param> -->
<!-- [Optional] Specifies the AU extension for particular prefix. <init-param>
<param-name>extension0</param-name> <param-value>/upload=com.my.MyUploader</param-value>
</init-param> -->
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>

<!-- [Optional] Uncomment if you want to use the ZK filter to post process
the HTML output generated by other technology, such as JSP and velocity.
<filter> <filter-name>zkFilter</filter-name> <filter-class>org.zkoss.zk.ui.http.DHtmlLayoutFilter</filter-class>
<init-param> <param-name>extension</param-name> <param-value>html</param-value>
</init-param> <init-param> <param-name>compress</param-name> <param-value>true</param-value>
</init-param> </filter> <filter-mapping> <filter-name>zkFilter</filter-name>
<url-pattern>your URI pattern</url-pattern> </filter-mapping> -->
<!-- //// -->

<!-- ///////////// -->
<!-- DSP (optional) Uncomment it if you want to use DSP However, it is turned
on since zksandbox uses DSP to generate CSS. <servlet> <servlet-name>dspLoader</servlet-name>
<servlet-class>org.zkoss.web.servlet.dsp.InterpreterServlet</servlet-class>
<init-param> <param-name>class-resource</param-name> <param-value>true</param-value>
</init-param> </servlet> <servlet-mapping> <servlet-name>dspLoader</servlet-name>
<url-pattern>*.dsp</url-pattern> </servlet-mapping> -->

<!-- /////////// -->
<!-- [Optional] Session timeout -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>

<!-- [Optional] MIME mapping -->
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpeg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>text/javascript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xls</extension>
<mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xml</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zul</extension>
<mime-type>text/html</mime-type>
</mime-mapping>

<welcome-file-list>
<welcome-file>index.zul</welcome-file>
<welcome-file>index.zhtml</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

Step 5:
As you can see in the web.xml file, we are loading new xml file configuration named as “spring-security.xml”.
Select the Folder “WEB-INF”, right click, Select New->Other-XML File and give the file name as “spring-security.xml”

image
Paste the following content

<!-- Spring namespace-based configuration -->

<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<!-- ====================================================== -->
<!-- For catching the @Secured annotation methods -->
<!-- Tells the Spring Security engine that we will use Spring Security's -->
<!-- pre and post invocation Java annotations (@PreFilter, @PreAuthorize, -->
<!-- @PostFilter, -->
<!-- @PostAuthorize) to secure service layer methods.. -->
<!-- Look in GFCBaseCtrl.java onEvent() method. -->
<!-- ====================================================== -->

<!-- Enable the @Secured annotation to secure service layer methods -->
<global-method-security secured-annotations="enabled" />


<beans:bean id="languageFilter"
class="zkloginexample4.ExUsernamePasswordAuthenticationFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationFailureHandler"
ref="failureHandler" />
</beans:bean>


<http entry-point-ref="loginUrlAuthenticationEntryPoint">
<intercept-url pattern="/login.zul" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/*.zul" access="IS_AUTHENTICATED_REMEMBERED" />
<intercept-url pattern="/zk/*" access="IS_AUTHENTICATED_REMEMBERED" />
<custom-filter position="FORM_LOGIN_FILTER" ref="languageFilter" />
<logout />
</http>


<beans:bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:property name="loginFormUrl" value="/login.zul" />
</beans:bean>


<beans:bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<beans:property name="defaultFailureUrl" value="/login.zul?login_error=1" />
</beans:bean>

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>

<beans:bean id="myUserDetailsService" class="zkloginexample4.MyUserDetailsService" />


</beans:beans>



You can see here, we have setup our own Entry point
The first thing we need to do is extend the UsernamePasswordAuthenticationFilter class so that it can handle a second input field.
So we will create a class under the default package zkloginexample4. Here is the class definition

package zkloginexample4;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class ExUsernamePasswordAuthenticationFilter extends
UsernamePasswordAuthenticationFilter {

private String extraParameter = "Company";
private String delimiter = ":";

@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
String dbValue = request.getParameter("Company");

System.out.println("Value is " + dbValue);
request.getSession().setAttribute("dbValue", dbValue);
return super.attemptAuthentication(request, response);
}

@Override
protected String obtainUsername(HttpServletRequest request) {
String username = request.getParameter(getUsernameParameter());
String extraInput = request.getParameter(getExtraParameter());

String combinedUsername = username + getDelimiter() + extraInput;

System.out.println("Combined username = " + combinedUsername);
return combinedUsername;
}

/**
* @return The parameter name which will be used to obtain the extra input
* from the login request
*/
public String getExtraParameter() {
return this.extraParameter;
}

/**
* @param extraParameter
* The parameter name which will be used to obtain the extra
* input from the login request
*/
public void setExtraParameter(String extraParameter) {
this.extraParameter = extraParameter;
}

/**
* @return The delimiter string used to separate the username and extra
* input values in the string returned by
* <code>obtainUsername()</code>
*/
public String getDelimiter() {
return this.delimiter;
}

/**
* @param delimiter
* The delimiter string used to separate the username and extra
* input values in the string returned by
* <code>obtainUsername()</code>
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
}


As you can see, we have created additional two java classes such as DbUser.java and UserDAO.java. So let us create this two classes in the package zkloginexample4 as shown.

image
Here is the code for DBUser.Java


package zkloginexample4;

public class DbUser {

/**
* The username
*/
private String username;

/**
* The password as an MD5 value
*/
private String password;

/**
* Access level of the user. 1 = Admin user 2 = Regular user
*/
private Integer access;

/**
* The company Name
*/
private String companyName;

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 Integer getAccess() {
return access;
}

public void setAccess(Integer access) {
this.access = access;
}

public String getCompanyName() {
return companyName;
}

public void setCompanyName(String companyName) {
this.companyName = companyName;
}

}



Here is the code for UserDAO.java



package zkloginexample4;

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

public class UserDAO {

/**
* Simulates retrieval of data from a database.
* http://krams915.blogspot.in/2010/12/spring-security-mvc-integration_18.html
*/
public DbUser searchDatabase(String username, String companyName) {
// Retrieve all users from the database
List<DbUser> users = internalDatabase();

// Search user based on the parameters
for (DbUser dbUser : users) {
if (dbUser.getUsername().equals(username) == true && dbUser.getCompanyName().equals(companyName) == true) {
// return matching user
return dbUser;
}
}
System.out.println("Not Exists");
throw new RuntimeException("User does not exist!");
}

/**
* Our fake database. Here we populate an ArrayList with a dummy list of
* users.
*/
private List<DbUser> internalDatabase() {
// Dummy database

// Create a dummy array list
List<DbUser> users = new ArrayList<DbUser>();
DbUser user = null;

// Create a new dummy user
user = new DbUser();
user.setUsername("rod");
// Actual password: admin
user.setPassword("a564de63c2d0da68cf47586ee05984d7");
// Admin user
user.setAccess(1);
user.setCompanyName("abc");

// Add to array list
users.add(user);

// Create a new dummy user
user = new DbUser();
user.setUsername("dianne");
// Actual password: user
user.setPassword("65d15fe9156f9c4bbffd98085992a44e");
// Regular user
user.setAccess(2);
user.setCompanyName("abc");

// Add to array list
users.add(user);

// Create a new dummy user
user = new DbUser();
user.setUsername("scott");
// Actual password: user
user.setPassword("2b58af6dddbd072ed27ffc86725d7d3a");
// Regular user
user.setAccess(2);
user.setCompanyName("abc");

// Add to array list
users.add(user);

// Create a new dummy user
user = new DbUser();
user.setUsername("scott");
// Actual password: user
user.setPassword("22b5c9accc6e1ba628cedc63a72d57f8");
// Regular user
user.setAccess(2);
user.setCompanyName("xyz");

// Add to array list
users.add(user);

return users;
}
}





Step 6:
Next step is to add the login.zul. Select the folder “webapp”. Right click, Select New->Other->Zul file. Enter the file name as login.zul
Here is the file content.


<?page id="loginPage" title="Digital medical sheet - Login page" onLoad="win.doOverlapped();"?>
<window id="win" title="LOGIN" border="normal" width="300px"
position="center">

<!-- this form-login-page form is also used as the
form-error-page to ask for a login again. -->
<html style="color:red" if="${not empty param.login_error}">


<![CDATA[ Your login attempt was not successful, try
again.<br/><br/> Reason:
${SPRING_SECURITY_LAST_EXCEPTION.message} ]]>


</html>

<groupbox>
<caption>Login</caption>
<h:form id="f" name="f" action="j_spring_security_check"
method="POST" xmlns:h="http://www.w3.org/1999/xhtml">
<grid>
<columns sizable="false">
<column width="50%" />
<column width="50%" />
</columns>
<rows>
<row>
<label value="User:" />
<textbox id="u" name="j_username" />
</row>
<row>
<label value="Password:" />
<textbox id="p" type="password"
name="j_password" />
</row>

<row>
<label value="Company Name" />
<textbox id="pa" name="Company" />
</row>



<row spans="2">
<div align="center">
<h:input type="submit" value="login" />
<h:input type="reset" value="Reset" />
</div>
</row>
</rows>
</grid>
</h:form>
</groupbox>
</window>

Step 7:
Now the let us change the index.zul file content which is created by default.

<zk>
<window >
Welcome to ZK Secured Page
<button label="Logout" href="/j_spring_security_logout"/>
</window>
</zk>


Step 8:
Now you can select the Project “zkloginexample4”, right click-> Run as –> Run on Server
image_thumb4_thumb_thumb
Select the tomcat server and Click finish button

image
Now you can enter any valid username/passwords as follows


rod/koala/abc
dianne/emu/abc
scott/wombat/abc
scott/wombat/xyz



You can download the source here

Reference
1.
Introduction to Spring Security Concepts.
2. Getting Started Spring Security
3. Understanding Spring Security
4. Configuring spring security
5. Spring Security 3 - MVC Integration Tutorial (Part 2)

Read More
Posted in ZK Spring | No comments
Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • EDI 270–5010 Documentation - ISA – Interchange Control Header
    ISA – Interchange Control Header ISA – Interchange Control Header   The ISA is a fixed record length segment and all positions within ea...
  • Understanding EDI Structure
    EDI Structure Primary Levels are 1. Interchange Envelops 2. Functional Group 3. Transaction set Data Element A data element is equival...
  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • EDI Instructions
    HIPAA Compliant Codes All the Health care EDI Transaction set should use only the following HIPAA Compliant Codes Physicians Current Pro...
  • ZK ListBox
    Let us first design a simple  static list box with crud Buttons as last column. Here is the code <?page title="Practice List" c...
  • Types of Reimbursement
    Fee-For-Service Fee-for-service is a method of payment where the provider is paid a fee for each procedure performed and billed.Most payer ...
  • List Item Connected with Hibernate and Search Parameter
      Summary This example contains one list box with First name and Last Name as search Field. If the user do not give any values for first n...
  • EDI 270 - 5010 Health Care Eligibility/Benefit Inquiry
    If you are new to Medical Billing, then please read this article first . If you are new to EDI, then  read the following articles 1. What i...
  • EDI Transactions
    The HIPAA transactions and code set standards are rules that standardize the electronic exchange of health-related administrative informati...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ▼  2013 (105)
    • ▼  December (3)
      • EDI Instructions
      • Understanding EDI Structure
      • What is an EDI ?
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ►  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ►  August (26)
    • ►  July (6)
    • ►  June (37)
    • ►  May (30)
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile