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. 

Sunday, March 2, 2014

Spring WEB-MVC Project Setup (Pure Java Based Configurations) with Using Spring Data

Introduction:

Hello friends, thanks to like my last post of "Spring WEB-MVC Project Setup (Pure Java Based Configuration) without using Database". This new Post is based on previous post and in this post, we use same project with "Spring Data" and spring database configurations are done using Pure Java Classes. For create this post, there are so many Google search help me and most import spring documentation, Spring Accessing Data with JPA and Fruzenshtein's notes. They help me create a good example for how to use Java Based configuration and how to use Spring Data. If you want to download the source of examples, please checkout from My Git Repository

Spring Data: 

Spring Data, provide a way to remove boilerplate code from our project and make our application more reliable. For performing CRUD operation with database, every developer need to create some base template class, which provide some CRUD functionality to perform Database Operation. But all this things are now handle by spring data easily. Spring data easily work with SQL and NO-SQL databases. 

In this i only cover Database configuration and some database classes for handle DB operations, and web based classes are same as previous post. There are some minor changes in web configuration java classes and pom.xml which we discuss in this post. I am using MySQL as a DB.    

Step 1:

Our package structure of example is in screen shot:


Step 2:

Create DBConfiguration.java file for database configuration. The code is following : 

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.springjavaconfig.repository")
public class DBConfiguration {

private static final String PROPERTY_NAME_DATABASE_URL = "jdbc:mysql://localhost/spring_test"; 
private static final String PROPERTY_NAME_DATABASE_DRIVER = "com.mysql.jdbc.Driver";  
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "root";  
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "root";
    
    @Bean
    public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl(PROPERTY_NAME_DATABASE_URL);
    dataSource.setDriverClassName(PROPERTY_NAME_DATABASE_DRIVER);
    dataSource.setUsername(PROPERTY_NAME_DATABASE_USERNAME);
    dataSource.setPassword(PROPERTY_NAME_DATABASE_PASSWORD);;
   
    return dataSource;
    }
    
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean.setPersistenceProviderClass(HibernatePersistence.class);
    factoryBean.setPackagesToScan("com.springjavaconfig.entity"); //  use Spring-based scanning for entity classes in the classpath
    factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
    return factoryBean;
    }

private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setShowSql(true);
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(true);
return jpaVendorAdapter;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}

  1. @Configuration annotation we discuss in our previous POST. 
  2. @EnableTransactionManagement : This annotation is similar <tx:*/> tag in xml based configuration. This is used to enable transaction with the using of annotations. It provide some more flexibility then <tx:*/>. In xml, we are not assign flexible name to the bean, but with this annotation we are flexible to assign the name of the bean. for more detail Click on this link.
  3. @EnableJpaRepositories : This annotation scan the repository of Spring Data and in the arguments we pass the package structure of spring data repository. String Data repository provide Implementation of CRUD operation with entities. 
In this class we create data source, entity manager and transaction beans. And configure JPA implementation provide by Hibernate. We use default data source, but it depends on you, you also used your own data source implementation or used Apache DBCP or any other. For JPA implementation you will use any vendor like top link, eclipse link etc. For more details of classes, please follow spring documentation. 

Step 3:

Create an Entity Class for perform some CRUD operations. 

@Entity
public class User implements Serializable{
/**
*/
private static final long serialVersionUID = -3012564413270146956L;
private Integer id;
private String name;
private int age;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
        
        @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}

Step 4:

Create a class for Spring Data Repository. 

public interface UserRepo extends CrudRepository<User, Integer> {
}

This interface contain empty body. but it extends CrudRepository interface. This is Spring Data interface provide some implementation for performing CRUD operation with our entity. This is generic interface and we pass or entity and ID for maintain our entity. Spring Data provide some more interface for provide some more functionality with the CRUD operationks like pagination etc. The implementation of these interfaces are abstract. For more detail Click on this link. There is one more interface in Spring DATA is JPARepository. For difference between CrudRepository and JPARepository Click here.

Step 5:

In previous step we create Spring Data Repository, now we provide some CRUD operation that perform by these repository. we use some abstract layer for hide the implantation of Spring Data Repository. 

public interface UserService {

public User save(User user);
public List<User> findAll();
}

Step 6:

In this step we create implementation of abstract layer and use repository to perform CRUD operation with entity. 

@Service
public class UserServiceImpl implements UserService {

@Resource
private UserRepo userRepo;
@Override
@Transactional
public User save(User user) {
return userRepo.save(user);
}

@Override
@Transactional
public List<User> findAll() {
return Lists.newArrayList( userRepo.findAll());
}
}

In this step we only cover two operations save and find-all, but you can also use some more operations like delete, findById etc. for this please check Spring Data Documentation. 

Step 7:

Create a controller class for handle Http Requests : 

@Controller
public class FirstController {

@Autowired
private UserService userService;
@RequestMapping(value="/saveuser", method=RequestMethod.POST)
public String saveUser(String name, int age){
User user = new User();
System.out.println("name : "+name+" ******** age : "+age);
user.setName(name);
user.setAge(age);
System.out.println(userService.save(user));
return "helloworld";
}
@RequestMapping(value="/getallusers", method=RequestMethod.GET)
public String getAllUser() {
List<User> users = userService.findAll();
for(User user : users){
System.out.println(user.toString());
}
return "helloworld";
}
}

Step 8: 

Create some HTML or JSP pages for input : 

<%@ 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>Index</title>
</head>
<body>
<h1>Index File</h1><br />
<form action="saveuser" method="post">
<table>
<tr>
<td>Name : </td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Age : </td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
<br />
<a href="getallusers">Click here to get all users, and check the output on server console</a>
</body>
</html>

Step 9:

There are some few changes in Web Configuration Java File that we use in previous POST. We add some new annotations only : 

@Configuration
@EnableWebMvc
@Import({DBConfiguration.class})
@ComponentScan({"com.springjavaconfig.web", "com.springjavaconfig.service.impl"})
public class WebAppConfig extends WebMvcConfigurerAdapter{
@Bean
public UrlBasedViewResolver setupViewResolver(){ 
--------------------------------------------

The @Import annotation is used to import more configuration file in main configuration file. We add new package name in @ComponentScan annotation, for scan some more components in java packages. 

Step 10: 

There are some changes in pom.xml file. we need to add some more dependencies for spring data and add some maven plugins for handle maven task easily. 

<properties>
<spring-version>4.0.0.RELEASE</spring-version>
<jdk.version>1.7</jdk.version>
</properties>

<!-- Spring Dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>

<!-- Servlet Dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- Database and Spring data Dependencies -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>

<!-- Hibernate for JPA implementation -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>
<!-- Mysql JDBC drivers -->

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
            
<!-- use some extra libraries for java collections -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<!-- If we not need to include web.xml in our war file like in servelet 
3.0 -->
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>

Mostly maven provide some default functionality to create war file, but the default implementation some time creates a problem and some time we need to modify war file structure. So we need to add war file plugins. The other plugins in maven compiler plugins maven 3.X provide JDK 1.5 compiler implementation, so if we need to use JDK new version or different version, we need to add maven compiler plugins. With my experience i realize that maven default plugins create some problem, which irritate the developer. So i think we always need to add some maven plugins for handle some specific task. So, if i am wrong  please correct me or If any other user have some more experience with spring data or any other technology, please share the knowledge.