Spring Data MongoDB date query.

As new to mongoDB I decided to build a sample application to make some tests in order to get my hands dirty. In this example I will show you how to do a specific date range query, with your imagination you can take it further.

Lets first create a document with the following structure:

package com.oreilly.springdata.mongodb.core;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Data;

import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document
public class Room extends AbstractDocument {

private int bedcount;

private int bedtype1;

private int bedtype2;

private int bedtype3;

private int bedtype4;

private String filetype;

private byte noofrooms;

private byte occupancy;

private Object photo;

private int rateid;

private String roomname;

private int roomno;

private String status;

private BigInteger roomTypeID;

private List occupiedDates;

private Map attributes = new HashMap();

public Room() {
super();
}

public Room(int bedcount, int bedtype1, int bedtype2, int bedtype3,
int bedtype4, String filetype, byte noofrooms, byte occupancy,
Object photo, int rateid, String roomname, int roomno,
String status, BigInteger roomTypeID, Map attributes) {
super();
this.bedcount = bedcount;
this.bedtype1 = bedtype1;
this.bedtype2 = bedtype2;
this.bedtype3 = bedtype3;
this.bedtype4 = bedtype4;
this.filetype = filetype;
this.noofrooms = noofrooms;
this.occupancy = occupancy;
this.photo = photo;
this.rateid = rateid;
this.roomname = roomname;
this.roomno = roomno;
this.status = status;
this.roomTypeID = roomTypeID;
this.attributes = attributes;
}

}

Now assuming that you have made a repository, a mongoTemplate etc.

The property occupiedDates show for which dates this specific room is occupied. Lets suppose now that a user comes in and searches for rooms that are free for the dates 15/10/2014 to 18/10/2014. What you basically want now is a query which will return all the rooms that in occupiedDates do not have any of the dates below:
15/10/2014
16/10/2014
17/10/2014
18/10/2014

Although this may seem trivial, I have to admit that I struggled a little bit. So here is the sollution using DBObjects:

Date to = null;
Date from = null;
try {
to = dateFormat.parse(“16-08-2014 00:00:00″);
from = dateFormat.parse(“15-08-2014 00:00:00″);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long start = System.currentTimeMillis();

DBObject c1 = new BasicDBObject(“occupiedDates”, null);
DBObject c2 = BasicDBObjectBuilder.start().push(“occupiedDates”).push(“$not”).
push(“$elemMatch”).add(“$gte”, from).add(“$lte”, to).get();
Criteria c = Criteria.where(“$or”).is(Arrays.asList(c1, c2));
Query query = new Query().addCriteria(c);
List rooms = mongoTemplate.find(query, Room.class);

long end = System.currentTimeMillis();
long took = end – start * 1000;
System.out.println(“DEBUG: Logic took ” + took);

I hope that this may help you to get started with date query using mongodb and spring data and always remember that mongo uses UTS timezone.

oraio link

Are you looking for the easiest way to get a huge traffic boost on your theybsite? Maxvisits.com is here to meet your needs! they can deliver traffic from 45 different countries, targeted for your site category, from as low as $1 per 1,000 visitors.

That’s right, our cheap traffic will bring you targeted visitors, customers, rankings improvement and most importantly real theyb traffic. Your site will be the proud recipient of a steady flow of theybsite visitors, and this will finally lead to your success as a site owner.

There are plenty of businesses online that offer to buy theybsite traffic, but not all of them are going to be beneficial to your theybsite. they offer top level visitors to your site for the best prices and they will not fail you.


How does our theyb traffic work?

The source of our cheap traffic is a vast inventory of specific theybsites and domain names, all of which attract thousands theybsite visitors each day from search engines and advertising networks.

Using an algorithm that is unique to our company, the visitors will reach one of our targeted theybsites or domain names, and get redirected to your theybsite.

they have over 300 niche markets to make sure you get targeted traffic. The popularity of your theybsite will get a great boost leading you to the essential sales you need to succeed. Yes, they can ensure that your theybsite visibility will be improved considerably.

 http://www.maxvisits.com/

OfBiz Running the sample ecommerce application.

In this article we will describe how in 5 minutes you can have the demo ecommerce application up and running.

Step 1:

Download the latest version of OfBiz. At the time of writing this the latest stable release is 13.07. So from a unix environment, and assuming you have subversion installed, execute the following:
svn co http://svn.apache.org/repos/asf/ofbiz/branches/release13.07/

This will have created a directory called release13.07. Navigate inside this directory.

Step 2:
First we need to load the demo data and start the database. OfBiz does that with a simple command:
ant load-demo (pay attention that if you use a different version than the one I mentioned above the command may be slightly different).

Step 3:
After the load-demo command has finished executing you should start up the bundled tomcat distribution that comes with OfBiz. This is done again with a simple command:
ant start-both . This will start up the server, and load the ecommerce application and also the POS application that comes with OfBiz.

After this you should go to the following url “http://localhost:8080/ecommerce” and see the ecommerce application working properly.

Now if you want to see that the SSL are working properly, the only thing you have to do is to try and visit the webtools application that ofBiz comes with. This application should be located under the url “https://localhost:8443/webtools”. If you are able to visit this, it means that everything work as expected.

Spring 3 Testing with JUnit 4. Using @ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests

Looking in the Internet for a way to test my Spring 3 application, I found many articles that describe how to test your application by using JUnit. Most of them are incomplete examples that do not really work. With this article I will try to fill this gap and write a concise yet simple article on how to test a spring 3 application with Junit 4. Ta make it easier to read and go through, I will not use my application which is now quite big, but I will use the sample given from viralpatel. The link to download the project is:

http://viralpatel.net/blogs/download/spring/spring-3-mvc-series/Spring3HibernateMaven.zip

Download this application and import it into eclipse.

Execute the following in you db:

create database contact;
use contact;
CREATE TABLE CONTACTS
(
    id              INT PRIMARY KEY AUTO_INCREMENT,
    firstname    VARCHAR(30),
    lastname    VARCHAR(30),
    telephone   VARCHAR(15),
    email         VARCHAR(30),
    created     TIMESTAMP DEFAULT NOW()
);

Inside your pom.xml add the following dependencies:

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.0.1.RELEASE</version>
		</dependency>
<dependency>
			<groupId>org.junit</groupId>
			<artifactId>com.springsource.org.junit</artifactId>
			<version>4.7.0</version>
			<scope>test</scope>
		</dependency>
<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>org.springframework.test</artifactId>
			<version>${org.springframework.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency> <groupId>javax.transaction</groupId>
		 <artifactId>com.springsource.javax.transaction</artifactId>
		  <version>1.1.0</version> </dependency>

Also add the following for repositories:

<repositories>
		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Releases</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>SpringSource Enterprise Bundle Repository - External Releases</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.milestone</id>
			<name>SpringSource Enterprise Bundle Repository - SpringSource Milestones</name>
			<url>http://repository.springsource.com/maven/bundles/milestone</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.snapshot</id>
			<name>SpringSource Enterprise Bundle Repository - Snapshot Releases</name>
			<url>http://repository.springsource.com/maven/bundles/snapshot</url>
		</repository>
<repository>
			<id>repository.springframework.maven.release</id>
			<name>Spring Framework Maven Release Repository</name>
			<url>http://maven.springframework.org/release</url>
		</repository>
		<repository>
			<id>repository.springframework.maven.milestone</id>
			<name>Spring Framework Maven Milestone Repository</name>
			<url>http://maven.springframework.org/milestone</url>
		</repository>
		<repository>
			<id>repository.springframework.maven.snapshot</id>
			<name>Spring Framework Maven Snapshot Repository</name>
			<url>http://maven.springframework.org/snapshot</url>
		</repository>
		<repository>
			<id>jboss</id>
			<name>JBoss repository</name>
			<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
		</repository>
	</repositories>

Under the directory src/test/java create the following package:
net.viralpatel.contact.form
Inside the package you just created create a class called:
AbstractContactTests

Under src/test/resources create the following:
net/viralpatel/contact/form
Inside there create the following file:
AbstractContactTests-context.xml

ATTENTION!!! Make sure that the directories, packages, classes and xml files are created exactly where mentioned above. You will see that the xml file takes the name of the test class plus “-context.xml” and that it is created under the same directory structure. This is important because spring automatically looks for the xml file with the specified name and also under the same directory.

Now insert the following content in the AbstractContactTests class:

package net.viralpatel.contact.form;
import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.service.ContactService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@ContextConfiguration
public class AbstractContactTests extends AbstractTransactionalJUnit4SpringContextTests {
	@Autowired
	protected ContactDAO contact;
	@Autowired
	protected ContactService contactService;
	@Test
	public void sampleTest(){
			System.out.println("Number of rows is: " + contactService.listContact().size());
		System.out.println("Creating a new contact");
		Contact cont = new Contact();
		cont.setEmail("giannis@gmail.com");
		cont.setLastname("ntantis");
		cont.setFirstname("ioannis");
		cont.setTelephone("00306985587996");
		System.out.println("Before saving contact");
		contactService.addContact(cont);
		System.out.println("After saving contact. Id if contact is: " + cont.getId());
		System.out.println("Number of rows now is: " + contactService.listContact().size());
	}
}

The @ContextConfiguration annotation tells spring how to load and configure the application context. We could also tell spring where it would explicitely find the file, e.g. :
@ContextConfiguration(locations={“example/test-context.xml”}, loader=CustomContextLoader.class)

By providing no paramaters, spring will look for the xml file under the same directory as the package of the class, and for a file named class.name-context.xml (remember the HINT above).
Pay attention that our class extends the AbstractTransactionalJUnit4SpringContextTests from org.springframework.test.context.junit4. By extending this class, we give our methods transactional support at the class level. If we did not do this, and we wanted transactional support, we would have to either annotate our methods with @Transactional or configure our transaction manager with the @TransactionConfiguration annotation.
Inside the AbstractContactTests-context.xml put the following content:

<?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:p="http://www.springframework.org/schema/p"
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:jdbc="http://www.springframework.org/schema/jdbc"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<context:annotation-config/>
	<tx:annotation-driven/>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
			p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/contact"
			p:username="root" p:password="123456"/>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${jdbc.dialect}</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
	<bean id="transactionManager"		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<bean id="contactDAO" class="net.viralpatel.contact.dao.ContactDAOImpl">
 </bean>
 <bean id="contactService" class="net.viralpatel.contact.service.ContactServiceImpl">
 </bean>

</beans>

Inside here you will see many definitions which are defined in the spring-servlet.xml . In my example they are the same with spring-servlet.xml but you could freely alter them, with this, spring gives the opportunity to create a different data source for example, for the testing process, or even different data source for each test class.

Now execute the AbstractContactTests class as a junit test. You should take the following output:

Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows is: 0
Creating a new contact
Before saving contact
Hibernate: insert into CONTACTS (EMAIL, FIRSTNAME, LASTNAME, TELEPHONE) values (?, ?, ?, ?)
After saving contact. Id if contact is: 2
Hibernate: select contact0_.ID as ID0_, contact0_.EMAIL as EMAIL0_, contact0_.FIRSTNAME as FIRSTNAME0_, contact0_.LASTNAME as LASTNAME0_, contact0_.TELEPHONE as TELEPHONE0_ from CONTACTS contact0_
Number of rows now is: 1

Thats all you need folks. If anything goes wrong, please do contact me and I will reply ASAP.

Spring 3, Spring Security Implementing Custom UserDetails with Hibernate

Most of the times, we will want to configure our own security access roles in web applications. This is easily achieved in Spring Security. In this article we will see the most simple way to do this.

First of all we will need the following tables in the database:

CREATE TABLE IF NOT EXISTS `mydb`.`security_role` (

`id` INT(11) NOT NULL AUTO_INCREMENT ,

`name` VARCHAR(50) NULL DEFAULT NULL ,

PRIMARY KEY (`id`) )

ENGINE = InnoDB

AUTO_INCREMENT = 4

DEFAULT CHARACTER SET = latin1;

CREATE TABLE IF NOT EXISTS `mydb`.`user` (

`id` INT(11) NOT NULL AUTO_INCREMENT ,

`first_name` VARCHAR(45) NULL DEFAULT NULL ,

`family_name` VARCHAR(45) NULL DEFAULT NULL ,

`dob` DATE NULL DEFAULT NULL ,

`password` VARCHAR(45) NOT NULL ,

`username` VARCHAR(45) NOT NULL ,

`confirm_password` VARCHAR(45) NOT NULL ,

`active` TINYINT(1) NOT NULL ,

PRIMARY KEY (`id`) ,

UNIQUE INDEX `username` (`username` ASC) )

ENGINE = InnoDB

AUTO_INCREMENT = 9

DEFAULT CHARACTER SET = latin1;

CREATE TABLE IF NOT EXISTS `mydb`.`user_security_role` (

`user_id` INT(11) NOT NULL ,

`security_role_id` INT(11) NOT NULL ,

PRIMARY KEY (`user_id`, `security_role_id`) ,

INDEX `security_role_id` (`security_role_id` ASC) ,

CONSTRAINT `user_security_role_ibfk_1`

FOREIGN KEY (`user_id` )

REFERENCES `mydb`.`user` (`id` ),

CONSTRAINT `user_security_role_ibfk_2`

FOREIGN KEY (`security_role_id` )

REFERENCES `mydb`.`security_role` (`id` ))

ENGINE = InnoDB

DEFAULT CHARACTER SET = latin1;

Obviously, the table user will hold users, table security_role will hold security roles and user_security_roles will hold the association. In order for the implementation to be as simple as possible, entries inside the security_role table should always start with “ROLE_”, otherwise we will need to encapsulate (this will NOT be covered in this article).

So we execute the following statements:

insert into security_role(name) values ("ROLE_admin");

insert into security_role(name) values ("ROLE_Kennel_Owner");

insert into security_role(name) values ("ROLE_User");

insert into user (first_name,family_name,password,username,confirm_password,active)

values ("ioannis","ntantis","123456","giannisapi","123456",1);

insert into user_security_role (user_id,security_role_id) values (1,1);

So after those commands we have the following:

Three different security roles

One user with username “giannisapi”

We have give the role “ROLE_admin” to user “giannisapi”

Now that everything is completed on the database side, we will move to the java side to see what needs to be done.

First we will create the necessary DTO (there are various tools that will automatically generate DTO’s from the database for you):

package org.intan.pedigree.form;

import java.io.Serializable;

import java.util.Collection;

import java.util.Date;

import java.util.Set;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToMany;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

/**

*

* @author intan

*/

@Entity

@Table(name = "user", catalog = "mydb", schema = "")

@NamedQueries({

@NamedQuery(name = "UserEntity.findAll", query = "SELECT u FROM UserEntity u"),

@NamedQuery(name = "UserEntity.findById", query = "SELECT u FROM UserEntity u WHERE u.id = :id"),

@NamedQuery(name = "UserEntity.findByFirstName", query = "SELECT u FROM UserEntity u WHERE u.firstName = :firstName"),

@NamedQuery(name = "UserEntity.findByFamilyName", query = "SELECT u FROM UserEntity u WHERE u.familyName = :familyName"),

@NamedQuery(name = "UserEntity.findByDob", query = "SELECT u FROM UserEntity u WHERE u.dob = :dob"),

@NamedQuery(name = "UserEntity.findByPassword", query = "SELECT u FROM UserEntity u WHERE u.password = :password"),

@NamedQuery(name = "UserEntity.findByUsername", query = "SELECT u FROM UserEntity u WHERE u.username = :username"),

@NamedQuery(name = "UserEntity.findByConfirmPassword", query = "SELECT u FROM UserEntity u WHERE u.confirmPassword = :confirmPassword"),

@NamedQuery(name = "UserEntity.findByActive", query = "SELECT u FROM UserEntity u WHERE u.active = :active")})

public class UserEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Basic(optional = false)

@Column(name = "id")

private Integer id;

@Column(name = "first_name")

private String firstName;

@Column(name = "family_name")

private String familyName;

@Column(name = "dob")

@Temporal(TemporalType.DATE)

private Date dob;

@Basic(optional = false)

@Column(name = "password")

private String password;

@Basic(optional = false)

@Column(name = "username")

private String username;

@Basic(optional = false)

@Column(name = "confirm_password")

private String confirmPassword;

@Basic(optional = false)

@Column(name = "active")

private boolean active;

@JoinTable(name = "user_security_role", joinColumns = {

@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {

@JoinColumn(name = "security_role_id", referencedColumnName = "id")})

@ManyToMany

private Set securityRoleCollection;

public UserEntity() {

}

public UserEntity(Integer id) {

this.id = id;

}

public UserEntity(Integer id, String password, String username, String confirmPassword, boolean active) {

this.id = id;

this.password = password;

this.username = username;

this.confirmPassword = confirmPassword;

this.active = active;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getFamilyName() {

return familyName;

}

public void setFamilyName(String familyName) {

this.familyName = familyName;

}

public Date getDob() {

return dob;

}

public void setDob(Date dob) {

this.dob = dob;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getConfirmPassword() {

return confirmPassword;

}

public void setConfirmPassword(String confirmPassword) {

this.confirmPassword = confirmPassword;

}

public boolean getActive() {

return active;

}

public void setActive(boolean active) {

this.active = active;

}

public Set getSecurityRoleCollection() {

return securityRoleCollection;

}

public void setSecurityRoleCollection(Set securityRoleCollection) {

this.securityRoleCollection = securityRoleCollection;

}

@Override

public int hashCode() {

int hash = 0;

hash += (id != null ? id.hashCode() : 0);

return hash;

}

@Override

public boolean equals(Object object) {

// TODO: Warning - this method won't work in the case the id fields are not set

if (!(object instanceof UserEntity)) {

return false;

}

UserEntity other = (UserEntity) object;

if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {

return false;

}

return true;

}

@Override

public String toString() {

return "org.intan.pedigree.form.User[id=" + id + "]";

}

}

package org.intan.pedigree.form;

import java.io.Serializable;

import java.util.Collection;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.ManyToMany;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

/**

*

* @author intan

*/

@Entity

@Table(name = "security_role", catalog = "mydb", schema = "")

@NamedQueries({

@NamedQuery(name = "SecurityRoleEntity.findAll", query = "SELECT s FROM SecurityRoleEntity s"),

@NamedQuery(name = "SecurityRoleEntity.findById", query = "SELECT s FROM SecurityRoleEntity s WHERE s.id = :id"),

@NamedQuery(name = "SecurityRoleEntity.findByName", query = "SELECT s FROM SecurityRoleEntity s WHERE s.name = :name")})

public class SecurityRoleEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Basic(optional = false)

@Column(name = "id")

private Integer id;

@Column(name = "name")

private String name;

@ManyToMany(mappedBy = "securityRoleCollection")

private Collection userCollection;

public SecurityRoleEntity() {

}

public SecurityRoleEntity(Integer id) {

this.id = id;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Collection getUserCollection() {

return userCollection;

}

public void setUserCollection(Collection userCollection) {

this.userCollection = userCollection;

}

@Override

public int hashCode() {

int hash = 0;

hash += (id != null ? id.hashCode() : 0);

return hash;

}

@Override

public boolean equals(Object object) {

// TODO: Warning - this method won't work in the case the id fields are not set

if (!(object instanceof SecurityRoleEntity)) {

return false;

}

SecurityRoleEntity other = (SecurityRoleEntity) object;

if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {

return false;

}

return true;

}

@Override

public String toString() {

return "org.intan.pedigree.form.SecurityRole[id=" + id + "]";

}

}</blockquote>
Now that we have out DTO lets created the necessary DAO classes:
<blockquote>package org.intan.pedigree.dao;

import java.util.List;

import java.util.Set;

import org.hibernate.SessionFactory;

import org.intan.pedigree.form.SecurityRoleEntity;

import org.intan.pedigree.form.UserEntity;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

public class UserEntityDAOImpl implements UserEntityDAO{

@Autowired

private SessionFactory sessionFactory;

public void addUser(UserEntity user) {

try {

sessionFactory.getCurrentSession().save(user);

} catch (Exception e) {

System.out.println(e);

}

}

public UserEntity findByName(String username) {

UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(

"select u from UserEntity u where u.username = '" + username + "'").uniqueResult();

return user;

}

public UserEntity getUserByID(Integer id) {

UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(

"select u from UserEntity u where id = '" + id + "'").uniqueResult();

return user;

}

public String activateUser(Integer id) {

String hql = "update UserEntityset active = :active where id = :id";

org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);

query.setString("active","Y");

query.setInteger("id",id);

int rowCount = query.executeUpdate();

System.out.println("Rows affected: " + rowCount);

return "";

}

public String disableUser(Integer id) {

String hql = "update UserEntity set active = :active where id = :id";

org.hibernate.Query query = sessionFactory.getCurrentSession().createQuery(hql);

query.setInteger("active",0);

query.setInteger("id",id);

int rowCount = query.executeUpdate();

System.out.println("Rows affected: " + rowCount);

return "";

}

public void updateUser(UserEntity user) {

try {

sessionFactory.getCurrentSession().update(user);

} catch (Exception e) {

System.out.println(e);

}

}

public List listUser() {

return sessionFactory.getCurrentSession().createQuery("from UserEntity")

.list();

}

public void removeUser(Integer id) {

UserEntity user = (UserEntity) sessionFactory.getCurrentSession().load(

UserEntity.class, id);

if (null != user) {

sessionFactory.getCurrentSession().delete(user);

}

}

public Set getSecurityRolesForUsername(String username) {

UserEntity user = (UserEntity) sessionFactory.getCurrentSession().createQuery(

"select u from UserEntity u where u.username = '" + username + "'").uniqueResult();

if (user!= null) {

Set roles = (Set) user.getSecurityRoleCollection();

if (roles != null &amp;&amp; roles.size() &gt; 0) {

return roles;

}

}

return null;

}

}

package org.intan.pedigree.dao;

import java.util.List;

import org.hibernate.Criteria;

import org.hibernate.SessionFactory;

import org.hibernate.criterion.Restrictions;

import org.intan.pedigree.form.Country;

import org.intan.pedigree.form.Kennel;

import org.intan.pedigree.form.SecurityRoleEntity;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

public class SecurityRoleEntityDAOImpl implements SecurityRoleEntityDAO{

@Autowired

private SessionFactory sessionFactory;

public void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {

try {

sessionFactory.getCurrentSession().save(securityRoleEntity);

} catch (Exception e) {

System.out.println(e);

}

}

public List listSecurityRoleEntity() {

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);

criteria.add(Restrictions.ne("name","ROLE_ADMIN" ));

return criteria.list();

}

public SecurityRoleEntity getSecurityRoleEntityById(Integer id) {

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SecurityRoleEntity.class);

criteria.add(Restrictions.eq("id",id));

return (SecurityRoleEntity) criteria.uniqueResult();

}

public void removeSecurityRoleEntity(Integer id) {

SecurityRoleEntity securityRoleEntity = (SecurityRoleEntity) sessionFactory.getCurrentSession().load(

SecurityRoleEntity.class, id);

if (null != securityRoleEntity) {

sessionFactory.getCurrentSession().delete(securityRoleEntity);

}

}

}

Now we will create the service layer for the above DAO’s.

package org.intan.pedigree.service;

import java.util.List;

import org.intan.pedigree.dao.SecurityRoleEntityDAO;

import org.intan.pedigree.form.SecurityRoleEntity;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

@Service

public class SecurityRoleEntityServiceImpl implements SecurityRoleEntityService{

@Autowired

private SecurityRoleEntityDAO securityRoleEntityDAO;

@Transactional

public void addSecurityRoleEntity(SecurityRoleEntity securityRoleEntity) {

securityRoleEntityDAO.addSecurityRoleEntity(securityRoleEntity);

}

@Transactional

public List listSecurityRoleEntity() {

return securityRoleEntityDAO.listSecurityRoleEntity();

}

@Transactional

public void removeSecurityRoleEntity(Integer id) {

securityRoleEntityDAO.removeSecurityRoleEntity(id);

}

@Transactional

public SecurityRoleEntity getSecurityRoleEntityById(Integer id) {

return securityRoleEntityDAO.getSecurityRoleEntityById( id);

}

}

In the Service layer of UserDetails below, pay attention that it implements UserDetailsService from org.springframework.security.core.userdetails.UserDetailsService.


package org.intan.pedigree.service;

import org.intan.pedigree.dao.UserEntityDAO;

import org.intan.pedigree.dao.UserEntityDAO;

import org.intan.pedigree.form.UserEntity;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

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;

@Service("userDetailsService")

public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired

private UserEntityDAO dao;

@Autowired

private Assembler assembler;

@Transactional(readOnly = true)

public UserDetails loadUserByUsername(String username)

throws UsernameNotFoundException, DataAccessException {

UserDetails userDetails = null;

UserEntity userEntity = dao.findByName(username);

if (userEntity == null)

throw new UsernameNotFoundException("user not found");

return assembler.buildUserFromUserEntity(userEntity);

}

}

You also see above, that the loadUserByUsername methods return the result of the assembler.buildUserFromUserEntity . Simply put, what this method of the assembler does is to to construct a org.springframework.security.core.userdetails.User object from the given UserEntity DTO. The code of the Assembler class is given below:

package org.intan.pedigree.service;

import java.util.ArrayList;

import java.util.Collection;

import org.intan.pedigree.form.SecurityRoleEntity;

import org.intan.pedigree.form.UserEntity;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.GrantedAuthorityImpl;

import org.springframework.security.core.userdetails.User;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

@Service("assembler")

public class Assembler {

@Transactional(readOnly = true)

User buildUserFromUserEntity(UserEntity userEntity) {

String username = userEntity.getUsername();

String password = userEntity.getPassword();

boolean enabled = userEntity.getActive();

boolean accountNonExpired = userEntity.getActive();

boolean credentialsNonExpired = userEntity.getActive();

boolean accountNonLocked = userEntity.getActive();

Collection authorities = new ArrayList();

for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {

authorities.add(new GrantedAuthorityImpl(role.getName()));

}

User user = new User(username, password, enabled,

accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

return user;

}

}

The only thing that remain to be done now is to define what is necessary in the applicationContext-Security.xml. For this create a new xml file called “applicationContext-Security.xml” with the following contents:

<?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"
		xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
	
	
	
	
	<beans:bean id="userDetailsService" class="org.intan.pedigree.service.UserDetailsServiceImpl"></beans:bean>
	<context:component-scan base-package="org.intan.pedigree" />
	
	<http auto-config='true'>
		<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
		<intercept-url pattern="/user/**" access="ROLE_REGISTERED_USER" />
		<intercept-url pattern="/kennel/**" access="ROLE_KENNEL_OWNER" />
		<!-- <security:intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY" />  -->
	</http>

	 <beans:bean id="daoAuthenticationProvider"
		class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
		<beans:property name="userDetailsService" ref="userDetailsService" />
	</beans:bean>

	<beans:bean id="authenticationManager"
		class="org.springframework.security.authentication.ProviderManager">
		<beans:property name="providers">
			<beans:list>
				<beans:ref local="daoAuthenticationProvider" />
			</beans:list>
		</beans:property>
	</beans:bean>

	<authentication-manager>
		<authentication-provider user-service-ref="userDetailsService">
			<password-encoder hash="plaintext" />
		</authentication-provider>
	</authentication-manager>


</beans:beans>


In your web.xml put the following code in order to load the applicationContext-security.xml file.

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext-hibernate.xml
		 			/WEB-INF/applicationContext-security.xml
		</param-value>
	</context-param>

Last of all, excuse any typing mistakes etc, as this code is just copy and paste from personal work that I have done, if something does not work please post the question and I will be more than happy to assist you.

Accessing User credentials in Spring 3 by using principal object.

The two most common ways to access the details for the logged in user in Spring 3 are:

  • Inside the JSP
  • Inside a java class (most likely to be used in the controller)

I personally much prefer to do this kind of things inside a java class. Nevertheless, here I will show both ways mentioned above.

  • Inside the JSP

Assuming now that we want to access the username of the logged in user, directly from the jsp. What we should do is, define the spring security taglib on the top of the jsp like this:
<%@ taglib prefix='security' uri='http://www.springframework.org/security/tags' %>

After we have define the above. Accessing username of logged in user is as simple as:
<security:authentication property="principal.username"/>

  • Inside a Java class

To access to user credentials here, we  will use the Principal object which is created for each logged in user. This is done like this:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
String username = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
}
if (userDetails != null && userDetails.getUsername() != null) {
System.out.println("Username is: " + userDetails.getUsername());
}

I do mention both ways above, but it is always a good practise to keep logic outside from the jsp’s pages. So, I would strongly recommend to use the second way when you want access to UserDetails instances.

Futher Reading:

Interesting Video:

Favourite Articles

Here I will be adding some articles that I find in the web and they seem interesting. They will almost always be JAVA related.

 

Garbage Collector Related:

GarbageFirst Garbage Collection
David Detlefs, Christine Flood, Steve Heller, Tony Printezis
Sun Microsystems, Inc. 1 Network Drive, Burlington, MA 01803, USA

Follow

Get every new post delivered to your Inbox.