Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Sunday, October 11, 2015

Spring Security Expression: Secure URL Dynamically According to Users and Permissions.

Introduction:

Today's we discuss about for securing URL using Spring-Security-Expression at Run Time in Application. Using ACL security we can set URL and permissions like read-write permissions per user but some time we just secure URL, there is no issue with Read and Write permission. That time, there is no need for using ACL security, because ACL have some complexity for implementation. But with the Spring-Security-Expression handler, we can easily secure urls by calling custom functions.

Step 1:

Create tables for User and UserPermssion as below: 
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `role` varchar(45) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `password` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `users_permissions` (
  `id` varchar(100) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `url` varchar(300) NOT NULL,
  `permission` enum('ACCESS','DENIED') NOT NULL,
  PRIMARY KEY (`user_id`,`url`),
  KEY `fk_users_permissions_1_idx` (`user_id`),
  CONSTRAINT `fk_users_permissions_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


You can also import sample data from SQL script using this link.

Step 2:

We are using Spring Java Based configuration. Our first requirement is to enable Spring-Security-Expression in our Application using following code in our security configuration file:

@EnableGlobalMethodSecurity(prePostEnabled=true)

Step 3:

 Create your custom bean for checking user security permission using database. This can contain method for validate permission and this method is used for Spring-Security-Expression. Following is our bean code:
@Component(value="securityService")
public class SecruityServiceImpl {

 @Autowired
 private UserPermissionRepo userPermissionRepo;
 
 public boolean userHasPermissionForURL(final Authentication auth, String url) {
  User user = (User) auth.getPrincipal();
  List permissions = userPermissionRepo.findByUserAndUrlAndPermission(user, url, CommonEnum.PERMSSION.ACCESS.getPermission());
  return (permissions != null && !permissions.isEmpty())? true: false;
 }
}

Step 4:

Secure our Spring-MVC controller methods using Spring-Security-Expression.  In the following code, we are using @PreAuthorize annotation for validate our expression.

@RequestMapping(value="/section-one", method=RequestMethod.GET)
@PreAuthorize(value="@securityService.userHasPermissionForURL(authentication, '/section-one')")
public String sectionOne() {
 LOG.info("In sectionOne Controller method");
  
 return "user/section-one";
}
 

Step 5:

 We can also secure our URL in user interface. The Spring-Security-Expression hide the link if user have not permission to access the URL. We are using thymeleaf for Spring-Security so, thymeleaf also provide some attribute. We can also use Spring-Security JSTL tag in JSP. For Thymeleaf following is the code.

sec:authorize="@securityService.userHasPermissionForURL(authentication, '/section-one')"

For download a complete code of sample application  access this link.

References:

  • http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html
  • http://www.blackpepper.co.uk/spring-security-using-beans-in-spring-expression-language/
  • http://www.borislam.com/2012/08/writing-your-spring-security-expression.html

Saturday, January 24, 2015

Depedencies Injection In Play-Framework 2.2.x Version Using Spring

Introduction:

Hello Friends, today we discuss about "How we use Dependencies Injection With Play-Framework Using JAVA". There are so many languages who have its own framework for developing web application easily and effectively like PHP have Cake-PHP, Zend etc or Python have its DJango etc. These web framework build a good web application easily and quickly, because the major thing is that there is not need to configure application manually, these frameworks are help the developers to create a basic web application struture with couple of seconds and easily customizable. These are Open-Source framework. But still java had not any open-source web framework for build reliable and scalable web-application. 

Explanation:

Now the day's Typesafe launches a Play-Framework for build a "Reactive" application using Java or Scala. Play 1.x build using Java but 2.x build with Scala, The Scala is a hybrid lanugage which have so features and Play uses these features for better performance. For more information about Play click on this link.
Now the day's Reactive Programming is the part of developement. Play is a reactive and follow reacive principles as below: 
  • Responsive
  • Resilient
  • Elastic
  • Message Driven
For basics understanding of reactive go to Reactive Manifesto

Play-Framework have so many features for build a reliable, scalable web applications easily, But the main limitation i feel in the Play-Framework is, the Play does not have its own dependency injection management. Most of the Java developers are habitual with Dependencies Injection because using new in our code is a bad practices. Play-Framework is a scalable, we easily scale our web application with play framework and for dependencies injection we are using third party plug-ins for Dependency Management like Spring, Google Guice etc.

We are trying to integrate Spring Dependency Injection with Play-Framework as below. Our requirements as below:                                                       


  • Download Play Framework
  • Install Java 1.6 or above
  • Eclipse IDE or other Rich Editor

Step 1:

Download the project from Github . Still Play have support for IDE, but some of the Java web developers found the different way for deploy application with play framework. Because for spring we are using tomcat and integrate tomcat with IDE easily and run the application. Play have its own server and we are using command line for run the server and create the application. With IDE we are write our code with rich environment and also debug the application. But still there is dependency of command line. 

NOTE: We are using Play-Framework 2.2 version and we hope in Play-Framework 3.x have its own dependency injection management module.

Step 2:

Download spring depedencies as below: 

 "org.springframework" % "spring-context" % "4.1.3.RELEASE"

NOTE: Play using Scala-Built Tool for build the application and dependencies management. 

Step 3:

For add spring dependencies configuration, we need to create a Global class at the root package and Inherit GlobalSettings class for override some default configurations settings for application. The Global class define some global configurations for application.

NOTE: One application have one Global Class. If we change the class name Global class to another name or change the Package of Global class, the application pick its default configuration because application search global settings class with Global name and on root package.



public class Global extends GlobalSettings{

	private Logger logger = null;	
	private final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	
	public Global() {
		logger = Logger.getLogger("GlobalConfiguration");
		logger.setLevel(Level.ALL);
	}
	
	@Override 
	public void onStart(Application app) {
		super.onStart(app);
		
		logger.info("ON START");
		applicationContext.scan("com.harmeetsingh13");
		applicationContext.refresh();
		
		// This will construct the beans and call any construction lifecycle methods e.g. @PostConstruct
		applicationContext.start();
	}
	
	@Override
	public void onStop(Application app) {
		applicationContext.close();
		
		super.onStop(app);
	}
	
	@Override
	public  A getControllerInstance(Class clazz) throws Exception {
		logger.info("getControllerInstance");
		return applicationContext.getBean(clazz);
	}
}

Sunday, December 7, 2014

Perform CRUD Operations Using Spring-Data-Neo4j.

Introduction:

In this post, we are trying to use Spring-Data-Neo4j with web application to persist the data in the graph form. Spring-Data-Neo4j is the huge wrapper on Neo4j, which is famous graph database community. Neo4j implementation is done by Java , but have support for connectivity with multiple programming languages. Neo4j have two types, one is opensource and other is licensed. 
There are so many graph database engines are available, but still the Neo4j is good product in all open source and have good community support. 

Graph-Database engines are designed in two ways as follow:
  1. Some database engines are native engines, means they store the data in the way of graphs internally. These types of engines are fast and efficient like Neo4j, OrientDB etc 
  2. Some database engines are store the graphs and nodes internally in RDBMS, Object Oriented Database and some other general databases. The example of these graph-database is FoundationDB. These are also called graph layer database. 
In the Graph Database, we create the nodes for store the data and these nodes are connected with each others. Graph Database is the part of No-SQL (Not-Only SQL) but provide ACID operations for store data. For more information go to this link

Graph-Database Storage For RDBMS Developers:

  1. In the table storage, the data is store in the form of records. One table have multiple records. In Graph database one node represent to one record.
  2. In the table storage the one table represent to one entity like User, Address etc and one table have multiple records. In graph storage nodes have labels and we identify multiple records represent to one entity through labels.
  3. In table storage we are use SQL for query the data from tables. In graph storage the query language is depends on graph-db engine like neo4j use cypher query language and orientdb use sql. 
  4. In table storage the relations between tables are manage through primary-key foreign-key relationship for (1:1) and (1:n) or (n:1). If the relation is (m:m) we maintain join tables. In graph-db the relation is by-directional and we also maintain as uni-directional. In these relationship we also set the attributes about relationship, that's why these relationship are called first class relationship. In graph-db relations are individual represent as entity and in graph we easily traverse from different nodes relationship without any headache of sql joins.

Example:

In the example, we are creating a flow to create, delete, read and maintain the relationship between nodes. Our example Technoloy stack as follow: 
  1. Spring-Data-Neo4j
  2. Thymeleaf
  3. Junit with Hamcrest
  4. JDK 8
  5. Google Guava
  6. Project Lombok
NOTE: For run the example, firstly configure project lombok with eclipse. For more information go to this link

Download the example code from github as below:
https://github.com/harmeetsingh0013/Spring-Data-Neo4j-Example

After downloading the code, you need to follow some steps:

  1. Before Import project into eclipse, configure project lombok
  2. Change the database path according to your system in "db.properties" file.
  3. Configure neo4j-community application for check nodes as a graphic layout. Download from this link. After installation set the path of db, that is used by example application. 
  4. At one time, the one instance is used Neo4j database like our application or neo4j-community application. Otherwise you get an exception related for lock the database.
  5. When run the JUNIT test, it run successfully, but nodes are not store permanently. When the actual application is run and save the node, the node persist permanently successfully.
  6. After launch an sample application, click on following URL: http://localhost:8080/neo4j-spring-example-web/save-person


Please give you suggestion in comments. 


Monday, July 28, 2014

Integrate Oauth-2.0 Security, Spring-Security And Jersey For Rest Services Using Database.

Introduction:

Hello Friends, Today we are discuss about Oauth-2.0 Integration with Spring-Security. Thanks to Spring, provide some user friendly API's for using Oauth2 with Spring-Security easily. Here we are not discuss about What is Oauth and Spring-Security, because these topics are itself so large and we assume you already have knowledge of these two topics. Here we just discuss about, how we integrate Oauth-2.0 with Spring-Security with the help of database. We Store our client Information and token information in database. Because i think, in real life we use database for store our client and token information. If you need to download the source code of example go to below link :-
https://github.com/harmeetsingh0013/oauth2-jersey-rest-spring-db

Step 1: pom.xml

<properties>
 <jdk-version>1.8</jdk-version>
 <maven-compiler-plugin>3.0</maven-compiler-plugin>
 <maven-war-pugin>2.4</maven-war-pugin>
 <org .springframework.version="">4.0.5.RELEASE</org>
 <hibernate>4.3.6.Final</hibernate>
 <spring-security-oauth2>2.0.1.RELEASE</spring-security-oauth2>
 <spring .security.version="">3.2.4.RELEASE</spring>
 <jersey-spring>1.18.1</jersey-spring>
 <servlet-version>3.0.1</servlet-version>
</properties>

<dependencies>
 <!-- Spring Dependencies -->
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-beans</artifactid>
  <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-expression</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-aop</artifactid>
  <version>${org.springframework.version}</version>
 </dependency>
 <!-- Spring web dependencies -->
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-web</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-webmvc</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-web</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-expression</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
  <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-jdbc</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-context</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-expression</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-orm</artifactid>
  <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-context-support</artifactid>
  <version>${org.springframework.version}</version>
 </dependency>
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-oxm</artifactid>
  <version>${org.springframework.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
  <!-- Spring security Dependencies -->
 <dependency>
  <groupid>org.springframework.security</groupid>
  <artifactid>spring-security-core</artifactid>
  <version>${spring.security.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-expression</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
  <dependency>
  <groupid>org.springframework.security</groupid>
  <artifactid>spring-security-web</artifactid>
  <version>${spring.security.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-web</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework.security</groupid>
    <artifactid>spring-security-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-expression</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>org.springframework.security</groupid>
  <artifactid>spring-security-config</artifactid>
  <version>${spring.security.version}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework.security</groupid>
    <artifactid>spring-security-core</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <!-- for OAuth 2.0 -->
 <dependency>
  <groupid>org.springframework.security.oauth</groupid>
  <artifactid>spring-security-oauth2</artifactid>
  <version>${spring-security-oauth2}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework.security</groupid>
    <artifactid>spring-security-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework.security</groupid>
    <artifactid>spring-security-config</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework.security</groupid>
    <artifactid>spring-security-web</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-webmvc</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
  <!-- Hibernate Dependencies -->
 <dependency>
  <groupid>org.hibernate</groupid>
  <artifactid>hibernate-entitymanager</artifactid>
  <version>${hibernate}</version>
 </dependency>
 <dependency>
  <groupid>org.hibernate</groupid>
  <artifactid>hibernate-core</artifactid>
  <version>${hibernate}</version>
 </dependency>
 <dependency>
  <groupid>org.apache.commons</groupid>
  <artifactid>commons-dbcp2</artifactid>
  <version>2.0.1</version>
 </dependency>
 <dependency>
  <groupid>mysql</groupid>
  <artifactid>mysql-connector-java</artifactid>
  <version>5.1.31</version>
 </dependency>

 <!-- Jersey Spring Integration -->
 <dependency>
  <groupid>com.sun.jersey.contribs</groupid>
  <artifactid>jersey-spring</artifactid>
  <version>${jersey-spring}</version>
  <exclusions>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-beans</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-core</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-context</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-web</artifactid>
   </exclusion>
   <exclusion>
    <groupid>org.springframework</groupid>
    <artifactid>spring-aop</artifactid>
   </exclusion>
  </exclusions>
 </dependency>
 <dependency>
  <groupid>com.sun.jersey</groupid>
  <artifactid>jersey-server</artifactid>
  <version>${jersey-spring}</version>
 </dependency>
  <!--Start Servlet Dependencies -->
 <dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>javax.servlet-api</artifactid>
  <version>${servlet-version}</version>
 </dependency>
</dependencies>

Step 2: db.sql

DROP TABLE IF EXISTS oauth_client_details;

CREATE TABLE oauth_client_details (
  client_id varchar(256) NOT NULL,
  resource_ids varchar(256) DEFAULT NULL,
  client_secret varchar(256) DEFAULT NULL,
  scope varchar(256) DEFAULT NULL,
  authorized_grant_types varchar(256) DEFAULT NULL,
  web_server_redirect_uri varchar(256) DEFAULT NULL,
  authorities varchar(256) DEFAULT NULL,
  access_token_validity int(11) DEFAULT NULL,
  refresh_token_validity int(11) DEFAULT NULL,
  additional_information varchar(4096) DEFAULT NULL,
  autoapprove varchar(4096) DEFAULT NULL,
  PRIMARY KEY (client_id)
);


INSERT INTO oauth_client_details(client_id, resource_ids, client_secret, scope, authorized_grant_types, authorities, access_token_validity, refresh_token_validity)
VALUES ('harmeet', 'rest_api', '$2a$11$gxpnezmYfNJRYnw/EpIK5Oe08TlwZDmcmUeKkrGcSGGHXvWaxUwQ2', 'trust,read,write', 'client_credentials,authorization_code,implicit,password,refresh_token', 'ROLE_USER', '4500', '45000');

  DROP TABLE IF EXISTS oauth_access_token;

  CREATE TABLE oauth_access_token (
  token_id varchar(256) DEFAULT NULL,
  token blob,
  authentication_id varchar(256) DEFAULT NULL,
  user_name varchar(256) DEFAULT NULL,
  client_id varchar(256) DEFAULT NULL,
  authentication blob,
  refresh_token varchar(256) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


DROP TABLE IF EXISTS oauth_refresh_token;

CREATE TABLE oauth_refresh_token (
  token_id varchar(256) DEFAULT NULL,
  token blob,
  authentication blob
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 3: db-config.xml

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
   <value>classpath:properties/database.properties</value>
  </property>
 </bean>

 <bean class="org.apache.commons.dbcp2.BasicDataSource" id="dataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}">
  <property name="url" value="${jdbc.url}">
  <property name="username" value="${jdbc.username}">
  <property name="password" value="${jdbc.password}">
 </property></property></property></property></bean>

 <bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
  <property name="dataSource" ref="dataSource">
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.hbm2ddl.auto">create</prop>
    <prop key="hibernate.hbm2ddl.import_files_sql_extractor">org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor
    </prop>
   </props>
  </property>
 </property></bean>

 <bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager">
  <property name="sessionFactory" ref="sessionFactory">
</property></bean></beans><h3 style="text-align: left;">
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><bean class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean></beans></h3>
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 <tx:annotation-driven transaction-manager="transactionManager">

 <bean class="org.springframework.transaction.interceptor.TransactionInterceptor" id="transactionInterceptor">
  <property name="transactionManager" ref="transactionManager">
  <property name="transactionAttributeSource"></property>
 </property></bean>
</tx:annotation-driven></beans>

Step 4:  Spring-Security-Oauth-Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:oauth="http://www.springframework.org/schema/security/oauth2" xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd         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">
   <!-- Create client details bean for manage client details from database -->
   <!-- The JdbcClientDetailsService provide default implementation for fetching 
  the data from oauth_client_details table Other wise we need to create our 
  custom class that Implement ClientDetailsService Interface and override its   loadClientByClientId method -->
   <bean class="org.springframework.security.oauth2.provider.client.JdbcClientDetailsService" id="clientDetails">
      <constructor-arg index="0">
         <ref bean="dataSource" />
      </constructor-arg>
   </bean>
<!-- Configure Authentication manager -->
   <bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder">
      <constructor-arg name="strength" value="11" />
   </bean>
<!-- This class is the custom implementation of UserDetailSerive Interface 
  that provide by the spring, which we Need to implement and override its method. 
  But for Oauth spring provide us ClientDetailsUserDetailsService, which already 
  implement UserDetailSerive Interface and override its method. -->
   <bean class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService" id="clientDetailsUserService">
      <constructor-arg ref="clientDetails" />
   </bean>
   <sec:authentication-manager alias="authenticationManager">
      <sec:authentication-provider user-service-ref="clientDetailsUserService">
         <sec:password-encoder ref="passwordEncoder" />
      </sec:authentication-provider>
   </sec:authentication-manager>
<!-- Oauth Token Service Using Database -->
   <!-- The JdbcTokenStore class provide the default implementation from access 
  the token from database. If we want to customize the JDBC implementation 
  we need to implement TokenStore interface and overrider its methods -->
   <bean class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore" id="tokenStore">
      <constructor-arg ref="dataSource" />
   </bean>
<!-- This the service class which is used to access the function of JdbcTokenStore 
  class. This is like MVC structure JdbcTokenStore is Dao layer and DefaultTokenServices 
  is service layer -->
   <bean class="org.springframework.security.oauth2.provider.token.DefaultTokenServices" id="tokenServices">
      <property name="tokenStore" ref="tokenStore">
         <property name="supportRefreshToken" value="true">
            <property name="clientDetailsService" ref="clientDetails">
               <property name="accessTokenValiditySeconds" value="4500" />
            </property>
         </property>
      </property>
   </bean>
<!-- A user approval handler that remembers approval decisions by consulting 
  existing tokens -->
   <bean class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory" id="oAuth2RequestFactory">
      <constructor-arg ref="clientDetails" />
   </bean>
   <bean class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler" id="userApprovalHandler">
      <property name="requestFactory" ref="oAuth2RequestFactory">
         <property name="tokenStore" ref="tokenStore" />
      </property>
   </bean>
<!-- Authorization Server Configuration of the server is used to provide 
  implementations of the client details service and token services and to enable 
  or disable certain aspects of the mechanism globally. -->
   <oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler">
      <oauth:authorization-code>
         <oauth:implicit>
            <oauth:refresh-token>
               <oauth:client-credentials>
                  <oauth:password authentication-manager-ref="authenticationManager" />
               </oauth:client-credentials>
            </oauth:refresh-token>
         </oauth:implicit>
      </oauth:authorization-code>
   </oauth:authorization-server>
<!-- A Resource Server serves resources that are protected by the OAuth2 
  token. Spring OAuth provides a Spring Security authentication filter that 
  implements this protection. -->
   <oauth:resource-server id="resourceServerFilter" resource-id="rest_api" token-services-ref="tokenServices">
      <!-- Grants access if only grant (or abstain) votes were received. We can 
  protect REST resource methods with JSR-250 annotations such as @RolesAllowed -->
      <bean class="org.springframework.security.access.vote.UnanimousBased" id="accessDecisionManager">
         <property name="decisionVoters">
            <list>
               <bean class="org.springframework.security.access.annotation.Jsr250Voter" />
            </list>
         </property>
      </bean>
<!-- If authentication fails and the caller has asked for a specific content 
  type response, this entry point can send one, along with a standard 401 status -->
      <bean class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" id="clientAuthenticationEntryPoint">
         <property name="realmName" value="Authorization/client">
            <property name="typeName" value="Basic" />
         </property>
      </bean>
      <bean class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" id="oauthAuthenticationEntryPoint">
         <property name="realmName" value="Authorization" />
      </bean>
      <bean class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" id="oauthAccessDeniedHandler">
         <!-- Allows clients to authenticate using request parameters if included 
  as a security filter. It is recommended by the specification that you permit 
  HTTP basic authentication for clients, and not use this filter at all. -->
         <bean class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter" id="clientCredentialsTokenEndpointFilter">
            <property name="authenticationManager" ref="authenticationManager" />
         </bean>
         <bean class="org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter" id="oAuth2ClientContextFilter" />
         <sec:http authentication-manager-ref="authenticationManager" create-session="stateless" pattern="/oauth/token">
            <sec:intercept-url access="IS_AUTHENTICATED_ANONYMOUSLY" pattern="/oauth/token">
               <sec:http-basic entry-point-ref="clientAuthenticationEntryPoint">
                  <sec:custom-filter before="BASIC_AUTH_FILTER" ref="clientCredentialsTokenEndpointFilter">
                     <sec:custom-filter after="EXCEPTION_TRANSLATION_FILTER " ref="oAuth2ClientContextFilter">
                        <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
                     </sec:custom-filter>
                  </sec:custom-filter>
               </sec:http-basic>
            </sec:intercept-url>
         </sec:http>
         <sec:http authentication-manager-ref="authenticationManager" create-session="never" pattern="/rest/**">
            <sec:anonymous enabled="false">
               <sec:intercept-url access="ROLE_USER" method="GET" pattern="/rest/**">
                  <sec:custom-filter before="PRE_AUTH_FILTER" ref="resourceServerFilter">
                     <sec:http-basic entry-point-ref="oauthAuthenticationEntryPoint">
                        <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
                     </sec:http-basic>
                  </sec:custom-filter>
               </sec:intercept-url>
            </sec:anonymous>
         </sec:http>
      </bean>
   </oauth:resource-server>
</beans>

Step 6:  RestServiceUsingJersey.java

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.springframework.stereotype.Component;

/**
 * @author Harmeet Singh(Taara)
 *
 */

@Component
@Path(value="/")
public class RestServiceUsingJersey {

 @Path("/message")
 @GET
 public Response message() {
  return Response.status(Status.ACCEPTED).entity("Hello Jersy Rest Spring").build();
 }
}

Step 7:  web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
   </context-param>
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
   <servlet>
      <servlet-name>jersey-serlvet</servlet-name>
      <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
      <init-param>
         <param-name>com.sun.jersey.config.property.packages</param-name>
         <param-value>com.the13star.api</param-value>
      </init-param>
   </servlet>
   <servlet-mapping>
      <servlet-name>jersey-serlvet</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping>
   <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>
</web-app>

From The above code, i am just trying to cover main configuration for regarding Oauth-2.0. I know i really missing so many things, so please go and download the code from above mentioned link or click on the link.
For Testing you can use CURL , POSTMAN, REST-CLIENT etc are many for calling rest services. I am using POSTMAN client by Chrome. Below is the screen shots of example.




Thursday, May 22, 2014

Integrate JOOQ With Spring and Perform CRUD Operations.

Introduction:

In the last POST we discuss about  generate Java classes using JOOQ maven generator. These java files are represent table in database. Like hibernate Jboss tools are used to generate entities corresponding to the table. Today we perform CRUD Operations with the help of JOOQ. For Generating java classes, refer to my previous POST. In this we Integrate  JOOQ with SPRING framework. There are may blog post that help me to create this example and also the JOOQ website, which share lots of example. 

Step 1:

The Dependencies that we need : 


Step 2:

Create the class to handle JOOQ exception in standard exception. Mostly the framework follow the standard SQLException framework, in which the framework specific exception are wrap into standard SQL exception so it can maintain easily. Now we create the class for handle JOOQ exception and wrap into Standard Exception. 

import org.jooq.ExecuteContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DefaultExecuteListener;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;

public class JOOQToSpringExceptionTransformer extends DefaultExecuteListener {
  private static final long serialVersionUID = -5749466061513426635L;
  @Override
  public void exception(ExecuteContext ctx) {
 SQLDialect dialect = ctx.configuration().dialect();
 SQLExceptionTranslator sqlExceptionTranslator = null;
 if(dialect != null){
  sqlExceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dialect.getName());
 }else{
  sqlExceptionTranslator = new SQLStateSQLExceptionTranslator();
 }
 
 ctx.exception(sqlExceptionTranslator.translate("JOOQ", ctx.sql(), ctx.sqlException()));
  }
}

In this :
DefaultExecuteListener : The DefaultExecuteListener class is the public default implementation of the ExecuteListener interface which provides listener methods for different life cycle events of a single query execution.

Step 3: 

In this we Cover Database Java Based Configuration: 

Properties File : application.properties
#Database Configuration
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/jooq_test
db.username=test
db.password=root

#jOOQ Configuration
jooq.sql.dialect=MYSQL

Database Configuration file: PersistenceConfiguration.java

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.jooq.impl.DefaultExecuteListenerProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Programmers
 *
 */
@Configuration
@ComponentScan({"com.the13star.service.test", "com.the13star.service.impl", "com.the13star.dao.impl" })
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistenceContext {

 @Autowired
 private Environment environment;

 @Bean(destroyMethod = "close") // destroyMethod attribute is used to close the bean
 public DataSource dataSource() {
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName(environment.getRequiredProperty("db.driver").trim());
  dataSource.setUrl(environment.getRequiredProperty("db.url").trim());
  dataSource.setUsername(environment.getRequiredProperty("db.username").trim());
  dataSource.setPassword(environment.getRequiredProperty("db.password").trim());
  dataSource.setInitialSize(5);
  dataSource.setMaxTotal(5);
  return dataSource;
 }

 // To delay opening a jdbc connection until the first actual sql statement
 // happens use LazyConnectionDataSourceProxy
 @Bean
 public LazyConnectionDataSourceProxy lazyConnectionDataSource() {
  return new LazyConnectionDataSourceProxy(dataSource());
 }

 // Configure jOOQ's ConnectionProvider to use Spring's
 // TransactionAwareDataSourceProxy,
 // which can dynamically discover the transaction context
 /**
  * Configure the TransactionAwareDataSourceProxy bean. This bean ensures
  * that all JDBC connection are aware of Spring-managed transactions. In
  * other words, JDBC connections participates in thread-bound transactions
  */
 @Bean
 public TransactionAwareDataSourceProxy transactionAwareDataSource() {
  return new TransactionAwareDataSourceProxy(lazyConnectionDataSource());
 }

 /**
  * Configure the DataSourceTransactionManager bean. We must pass the
  * LazyConnectionDataSourceProxy bean as as constructor argument when we
  * create a new DataSourceTransactionManager object.
  */
 @Bean
 public DataSourceTransactionManager dataSourceTransactionManager() {
  return new DataSourceTransactionManager(lazyConnectionDataSource());
 }

 /**
  * Configure the DataSourceConnectionProvider bean. jOOQ will get the used
  * connections from the DataSource given as a constructor argument. We must
  * pass the TransactionAwareDataSourceProxy bean as a constructor argument
  * when we create a new DataSourceConnectionProvider object. This ensures
  * that the queries created jOOQ participate in Spring-managed transactions.
  */
 @Bean
 public DataSourceConnectionProvider connectionProvider() {
  return new DataSourceConnectionProvider(transactionAwareDataSource());
 }

 @Bean
 public JOOQToSpringExceptionTransformer jooqToSpringExceptionTranslator() {
  return new JOOQToSpringExceptionTransformer();
 }

 /**
  * Invoking an internal, package-private constructor for the example
  * Implement your own Configuration for more reliable behaviour
  */
 @Bean
 public DefaultConfiguration configuration() {
  DefaultConfiguration configuration = new DefaultConfiguration();
  configuration.set(connectionProvider());
  configuration.set(new DefaultExecuteListenerProvider(
    jooqToSpringExceptionTranslator()));

  String sqlDialect = environment.getRequiredProperty("jooq.sql.dialect");
  SQLDialect dialect = SQLDialect.valueOf(sqlDialect);
  configuration.set(dialect);

  return configuration;

 }

 /**
  * Configure the DSL object, optionally overriding jOOQ Exceptions with
  * Spring Exceptions. We use this bean when we are creating database queries
  * with jOOQ.
  */
 @Bean
 public DSLContext dslContext() {
  return new DefaultDSLContext(configuration());
 }

 /**
  * We use this bean to create the database schema for database when our
  * application is started (If you don’t use an embedded database, you don’t
  * have to configure this bean).
  */
 /*
 @Bean
 public DataSourceInitializer dataSourceInitializer() {
  DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
  dataSourceInitializer.setDataSource(dataSource());
  
  ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
  databasePopulator.addScript(new ClassPathResource(environment.getRequiredProperty("")));
  
  dataSourceInitializer.setDatabasePopulator(databasePopulator);
  return dataSourceInitializer;
 }*/
}

Step 4: 

Create Service layer : 
import java.util.List;

import com.the13star.dbmetadata.tables.records.UserDetailRecord;

public interface UserDetailService {
 public void saveUserDetail(int id, String name, int age);

 public List getAllUsers();

 public UserDetailRecord getUserByID(int i);

 public int updateUserById(UserDetailRecord userDetailRecord);

 public int deleteUserById(int id);
}

import java.util.List;

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

import com.the13star.dao.UserDetailDao;
import com.the13star.dbmetadata.tables.records.UserDetailRecord;
import com.the13star.service.UserDetailService;

/**
 * @author Programmers
 *
 */
@Service
public class UserDetailServiceImpl implements UserDetailService {
 
 @Autowired
 private UserDetailDao userDetailDao;

 /* (non-Javadoc)
  * @see com.the13star.service.UserDetailService#saveUserDetail(int, java.lang.String, int)
  */
 @Override
 public void saveUserDetail(int id, String name, int age) {
  UserDetailRecord record = new UserDetailRecord();
  record.setId(id);
  record.setName(name);
  record.setAge(age);
  
  userDetailDao.insertNewUser(record);
 }

 @Override
 public List getAllUsers() {
  return userDetailDao.getAllUsers();
 }

 @Override
 public UserDetailRecord getUserByID(int id) {
  return userDetailDao.getUserByID(id);
 }

 @Override
 public int updateUserById(UserDetailRecord userDetailRecord) {
  return userDetailDao.updateUserById(userDetailRecord);
 }

 @Override
 public int deleteUserById(int id) {
  return userDetailDao.deleteUserById(id);
 }

}

Step 5:

Create Dao Layer : 
import java.util.List;

import com.the13star.dbmetadata.tables.records.UserDetailRecord;


/**
 * @author Programmers
 *
 */
public interface UserDetailDao {

 public void insertNewUser(UserDetailRecord userDetailRecord);

 public List getAllUsers();

 public UserDetailRecord getUserByID(int id);

 public int updateUserById(UserDetailRecord userDetailRecord);

 public int deleteUserById(int id);
}

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

import org.jooq.DSLContext;
import org.jooq.DeleteConditionStep;
import org.jooq.DeleteWhereStep;
import org.jooq.InsertValuesStep3;
import org.jooq.Result;
import org.jooq.UpdateConditionStep;
import org.jooq.UpdateSetFirstStep;
import org.jooq.UpdateSetMoreStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.the13star.dao.UserDetailDao;
import com.the13star.dbmetadata.tables.UserDetail;
import com.the13star.dbmetadata.tables.records.UserDetailRecord;

/**
 * @author Programmers
 *
 */
@Repository
public class UserDetailDaoImpl implements UserDetailDao {

 @Autowired
 DSLContext dslContext;

 public void insertNewUser(UserDetailRecord userDetailRecord) {
  InsertValuesStep3 userdetails = dslContext
    .insertInto(UserDetail.USER_DETAIL, UserDetail.USER_DETAIL.ID,
      UserDetail.USER_DETAIL.NAME, UserDetail.USER_DETAIL.AGE);
  userdetails.values(userDetailRecord.getId(),
    userDetailRecord.getName(), userDetailRecord.getAge());
  userdetails.execute();
 }

 @Override
 public List getAllUsers() {
  Result userDetails = dslContext
    .fetch(UserDetail.USER_DETAIL);
  return new ArrayList<>(userDetails);
 }

 @Override
 public UserDetailRecord getUserByID(int id) {
  return dslContext.fetchOne(UserDetail.USER_DETAIL,
    UserDetail.USER_DETAIL.ID.equal(id));
 }

 @Override
 public int updateUserById(UserDetailRecord userDetailRecord) {
  UpdateSetFirstStep updateSetFirstStep = dslContext
    .update(UserDetail.USER_DETAIL);
  UpdateSetMoreStep updateSetMoreStep = updateSetFirstStep
    .set(UserDetail.USER_DETAIL.NAME, userDetailRecord.getName())
    .set(UserDetail.USER_DETAIL.AGE, userDetailRecord.getAge());
  UpdateConditionStep updateConditionStep = updateSetMoreStep
    .where(UserDetail.USER_DETAIL.ID.equal(userDetailRecord.getId()));
  return updateConditionStep.execute();
 }

 @Override
 public int deleteUserById(int id) {
  DeleteWhereStep deleteWhereStep = dslContext.delete(UserDetail.USER_DETAIL);
  DeleteConditionStep deleteConditionStep = deleteWhereStep.where(UserDetail.USER_DETAIL.ID.equal(id));
  return deleteConditionStep.execute();
 }

}

Step 6: 

Launch Our Code:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import com.the13star.configurations.PersistenceContext;
import com.the13star.dbmetadata.tables.records.UserDetailRecord;
import com.the13star.service.UserDetailService;

/**
 * @author Programmers
 *
 */
@Component
public class UserDetailTest {
 
 @Autowired
 private UserDetailService userDetailService;
 /**
  * @param args
  */ 
 
 private void start() {
  //userDetailService.saveUserDetail(3, "MICKY", 21);
  List userDetails = userDetailService.getAllUsers();
  for(UserDetailRecord record : userDetails){
   System.out.println(record);
  }
  /*
  UserDetailRecord record = userDetailService.getUserByID(1);
  System.out.println(record);*/
  /*
  UserDetailRecord userDetailRecord = new UserDetailRecord();
  userDetailRecord.setId(3);
  userDetailRecord.setName("Micky");
  userDetailRecord.setAge(26);
  int result = userDetailService.updateUserById(userDetailRecord);*/
  /*
  int result = userDetailService.deleteUserById(2);
  System.out.println("Result : "+result);*/
 }
 
 public static void main(String[] args) {
  AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersistenceContext.class);
  UserDetailTest userDetailTest = applicationContext.getBean(UserDetailTest.class);
  userDetailTest.start();
  applicationContext.close();
 }

}

For downloading the example code, go to the this link

Thursday, April 17, 2014

JOOQ Reverse Engineering Using Maven Generator

Introduction : 

JOOQ is used to write type safe SQL queries using JAVA. Some time it is difficult to write SQL queries for Java Developer, because Java Developer is familiar with Object Oriented World and with its own language syntax. SQL is a different language and developers need to learn new language for deal with data base using queries. For the sake of learning new language syntax and new structure, The JOOQ provide a way to use queries using Java Programming Syntax. There are lots of rich ORM tools which also provide the way to implement queries using Java Programming Syntax, these queries called CRITERIA queries. But these ORM tools have some Limitations , so if the programmer only need to apply types safety queries, the JOOQ is the best way to do this. There are lots of things that JOOQ provide. For JOOQ detail go to JOOQ Home Page. JOOQ also provide some classes or function that are familiar for SQL developer like for select query JOOQ provide select method in class. 

JOOQ also provide the reverse engineering for generate Java POJO's or Entities from existing table in database. They provide several approaches to use generator to generate Entities. In this POST we discuss about Maven Generator for generate Entities.  

Step 1:

Add the Generator plugin in Maven pom.xml. 

 3.3.1



 
  org.jooq
  jooq
  ${jooq-version}
 

 
  org.jooq
  jooq-meta
  ${jooq-version}
 

 
  org.jooq
  jooq-codegen
  ${jooq-version}
 




 
 org.jooq
 jooq-codegen-maven
 ${jooq-version}

 
 
   
   
   generate
  
  
 

 
  
   mysql
   mysql-connector-java
   5.1.30
  
 

 
 
  
  
   com.mysql.jdbc.Driver
   jdbc:mysql://localhost/jooq_test
   root
   root
  

  

  
   org.jooq.util.DefaultGenerator
   
    org.jooq.util.mysql.MySQLDatabase
    .*
    
    jooq_test
   
   
    com.the13star.entities
    src/main/java
   
  


For JOOQ we need some dependencies to add in the pom.xml file. But the generator plugin also need some dependencies for plugin use only. That dependencies are declare in the generator plugin. If we already declare dependencies in dependency block and not declare in plugin the generator will not run. We again need to declare dependencies in the generator plugin, because plugin use its individual dependencies for run like MySQL dependency in the above code. If maven provide the way to use dependencies of dependency block in plugin please discuss.
In this we use DefaultGenerator for generate Entities, you can also use your custom generator.

Step 2

For run the generator use Maven install command from eclipse or command line, after generator run, there are three packages structures are automatically create in your project. 
The three pakcages are 
1. com.the13star.dbmetadata: According to its name it is used to represent meta information of database table. Like Kyes.java contain information regarding primary key's etc. 
2.  com.the13star.dbmetadata.tables: This package contain the information of db tables like. Field in table, types of column etc. One java file represent one table. according to above example there is only one table in DB. 
3.  com.the13star.dbmetadata.tables.records: This package represent the record of table or represent the one row in table. We will also said that, this is our Java POJO or Entity file. 

Saturday, August 17, 2013

Perform CRUD Operation's MongoDB with Java.


MongoDB :

Data in MongoDB has a flexible schemaCollections do not enforce document structure. This means that:

  • documents in the same collection do not need to have the same set of fields or structure, and
  • common fields in a collection’s documents may hold different types of data.

Each document only needs to contain relevant fields to the entity or object that the document represents. In practice, most documents in a collection share a similar structure. Schema flexibility means that you can model your documents in MongoDB so that they can closely resemble and reflect application-level objects. For more information Click on that link.

Requirements : 

  1. Download MongoDB from here.
  2. Install MongoDB and set the PATH variable . 
  3. Install JDK 7 (The following code is Tested On JDK 7.

Note: Before Running the code, Need to start MongoDB server .


Following is the CODE to perform CRUD operation's of MongoDB with JAVA.

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.QueryBuilder;
import com.mongodb.ServerAddress;

public class MongoDBCRUDOperationInJava {
 public static void main(String[] args) throws UnknownHostException {
  MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
  DB courseDB = client.getDB("students");
  DBCollection collection = courseDB.getCollection("grades");
  //collection.drop();
  //insertDocument(collection);
  //findOne(collection);
  //findAll(collection);
  //count(collection);
  //findWithCriteriaUsingDBObject(collection);
  findWithCriteriaUsingQueryBuilder(collection);
}

public static void insertDocument(DBCollection collection) {
 DBObject doc = new BasicDBObject("_id", new ObjectId());
 doc.put("name", "Harmeet");
 doc.put("age", 24);
 doc.put("birthday", new Date(12312312313l));
 doc.put("programmer", true);
 doc.put("language", Arrays.asList("Java", "Scala", "Python"));
 doc.put("address", new BasicDBObject("street", "5").append("area", "moga"));
 DBObject doc2 = new BasicDBObject().append("name", "Jimmy");
System.out.println("Before Inserting the Document in Collection : "+doc);
 collection.insert(Arrays.asList(doc, doc2));
 System.out.println("After Inserting the Document in Collection : "+doc);
}
public static void findOne(DBCollection collection) {
 DBObject doc = collection.findOne();
 System.out.println(doc);
}
public static void findAll(DBCollection collection) {
 DBCursor cur = collection.find();
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
 cur.close();
 }
}
public static void count(DBCollection collection) {
 System.out.println("COunt of collection Documents : "+collection.count());
}
public static void findWithCriteriaUsingDBObject(DBCollection collection) {
 DBObject criteria = new BasicDBObject("type", "homework").append("student_id", 9);
 DBCursor cur = collection.find(criteria);
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
  cur.close();
 }
}
public static void findWithCriteriaUsingQueryBuilder(DBCollection collection) {
 QueryBuilder builer =  QueryBuilder.start("type").is("homework").and("student_id").is(9).and("score").greaterThan(60);
 DBCursor cur = collection.find(builer.get(), new  BasicDBObject("student_id" , true).append("_id", false));
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
  cur.close();
 }
}
}

Download the CODE from here.

Thursday, February 28, 2013

Generate PDF using Jasper Reports and IReport

Jasper Reports :  JasperReports is an open source Java reporting tool that can write to a various types of report formats such as: PDF, HTML ,Microsoft Excel, RTF, ODT, Comma-separated values or XML files . It can be used in Java-enabled applications, including Java EE or web applications, to generate dynamic content. It reads its instructions from an XML or .jasper file

Ireport : iReport is a GUI tool that helps users and developers that use the JasperReports library to visually design reports.Through a rich and very simple to use GUI, iReport provides all the most important functions to create nice reports in little time. iReport can help people that don't know the JasperReports library create complex reports and learn the XML syntax, taking a look to the generated code. iReport can help skilled report designers compose very complex pages, saving a lot of time. iReport is written in Java.

Requirements : 

  1. Ireport Tool 4.5
  2. Apache Tomcat Container (up to 7.0)
  3. Libraries (jar files that needed to create the report from java)                                                                  Following the list of jar files : 
    • commons-beanutils-1.8.2.jar 
    • commons-collections-3.2.1.jar 
    • commons-digester-1.7.jar
    • commons-logging-1.1.jar 
    • groovy-all-1.7.5.jar 
    • iText-2.1.7.jar 
    • jasperreports-4.5.0.jar

Steps : 

Step 1 : Download and install the ireport tool from http://community.jaspersoft.com/download website .

Step 2 : Open the ireport tool and select the blank A4 template to create the report.


Step 3 : Design the report using ireport tools.

Step 4 : To connect the report with JavaBean Datasource , put the bean jar file in ireport class path Tools -> options -> classpath -> AddJar.


Step 5 : Save the report file at project/WEB-INF/ReportFormat/DemoReport.jrxml and put the project in Apache tomcat webapps directory.

Step 6 : create the jsp file to enter the user detail.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>PDF Generator</title>
</head>
<body>
            <h1>Generate PDF file using Jasper Reports </h1>
            <form action="addUser" method="post">
            <table>
                        <tr>
                                    <td><label for="firstName">First Name : </label></td>
                                    <td><input type="text" id="firstName" name="firstName"></td>
                        </tr>
                        <tr>
                                    <td><label for="lastName">Last Name : </label></td>
                                    <td><input type="text" id="lastName" name="lastName"></td>
                        </tr>
                        <tr>
                                    <td><label for="age">Age : </label></td>
                                    <td><input type="text" id="age" name="age"></td>
                        </tr>
                        <tr>
                                    <td><label for="sex">Sex : </label></td>
                                    <td>
                                                <select name="sex" id="sex">
                                                <option value="male">Male</option>
                                                <option value="female">Female</option>
                                                <option value="others">Others</option>
                                                </select>
                                    </td>
                        </tr>
                        <tr>
                                    <td><label for="address">Address : </label></td>
                                    <td><textarea name="address" id="address" rows="4" cols="20" ></textarea></td>
                        </tr>
                        <tr>
                                    <td><input type="submit" value="Report" name="submit"/></td>
                                    <td><input type="submit" value="Submit" name="submit"></td>
                        </tr>
            </table>
            </form>
</body>
</html>

Step 7 : Create the domain or Java Bean Class to add the detail of user.

package domain;
public class User {
                private String firstName;
                private String lastName;
                private String age;
                private String sex;
                private String address;
               
                /* public getter/setter */
}

Step 8 : Create the controller to add the list of users in List<User>.

package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
…………………………….

@WebServlet("/jsp/addUser")
public class AddUser extends HttpServlet{
                public void doPost(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                               
                                String submit = request.getParameter("submit");
                                if(submit.equalsIgnoreCase("submit")){
                                                createUser(request, response);
                                }else{
                                                processReports(request,response);
                                }
                }

private void createUser(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                                String firstName = request.getParameter("firstName");
                                String lastName = request.getParameter("lastName");
                                String age = request.getParameter("age");
                                String sex = request.getParameter("sex");
                                String address = request.getParameter("address");
                               
                                User user = new User();
                                user.setFirstName(firstName);
                                user.setLastName(lastName);
                                user.setAge(age);
                                user.setSex(sex);
                                user.setAddress(address);
                               
                                UserCollections collections = new UserCollections();
                                collections.addUser(user);
                               
                                RequestDispatcher view = request.getRequestDispatcher("index.jsp");
                                view.forward(request, response);
                }
.........................................................................................................
}


package tempdatabase;


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

import domain.User;

public class UserCollections {
                private static List<User> userList = new ArrayList<User>();
               
                public void  addUser(User user) {
                                userList.add(user);
                }
               
                public List<User> getUserList() {
                                return userList;
                }
}

Step 9 : When the List<User> is filled with Users. Generate the pdf report report using following code.

package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
…………………………….

@WebServlet("/jsp/addUser")
public class AddUser extends HttpServlet{
                public void doPost(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                               
                                String submit = request.getParameter("submit");
                                if(submit.equalsIgnoreCase("submit")){
                                                createUser(request, response);
                                }else{
                                                processReports(request,response);
                                }
                }

private void processReports(HttpServletRequest request,
                                                HttpServletResponse response) {
                               
                                File filePath = new File(getServletContext().getRealPath("ReportFormat/DemoReport.jrxml"));
                                File savePath = new File(getServletContext().getRealPath("WEB-INF/GeneratedReports/userDetail.pdf"));
                                new ProcessReports().generateReport(filePath , savePath);
                                String path = savePath.toString();
                                try{
                                                if(path != null){
                                                                response.setContentType("application/pdf");
                                                                response.setHeader("content-dispostion","attachment;");
                                                                ServletContext ctx = getServletContext();
                                                                InputStream is = ctx.getResourceAsStream("WEB-INF/GeneratedReports/userDetail.pdf");
                                                               
                                                                int read = 0;
                                                                byte[] bytes = new byte[1024];
                                                               
                                                                OutputStream os = response.getOutputStream();
                                                                while((read = is.read(bytes)) != -1){
                                                                                os.write(bytes,0,read);
                                                                }
                                                                os.flush();
                                                                os.close();
                                                }
                                }catch(IOException ex){
                                                ex.printStackTrace();
                                }
                }

package tempdatabase;

import java.io.File;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ProcessReports {
                public void generateReport(File filePath , File savePath) {
                                try{
                                                String pdfPath = savePath.toString();
                                                savePath.delete();
                                                JasperDesign design = JRXmlLoader.load(filePath);
                                                JasperReport report = JasperCompileManager.compileReport(design);
                                                JasperPrint print = JasperFillManager.fillReport(report, null,
                                                                                new JRBeanCollectionDataSource(new UserCollections().getUserList()));
                                                JasperExportManager.exportReportToPdfFile(print, pdfPath);
                                               
                                }catch(JRException ex){
                                                ex.printStackTrace();
                                }
                }
}

Step 10 : After generate the report , the pdf is open in browser.



To download the source code Click .