Wednesday, 25 February 2015

Sample pom.xml (spring ,Spring-Security,Hibernate,log4j,Junit...etc.

<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.thingovation.smartdogcollar</groupId>
<artifactId>SmartDogCollar</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>PublicAPI</artifactId>
<packaging>war</packaging>
<name>PublicAPI Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.8.RELEASE</spring.version>
<jersy.version>1.8</jersy.version>
<maven.copy.plugin.version>0.2.3</maven.copy.plugin.version>
<maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
<maven.apt.plugin.version>1.0</maven.apt.plugin.version>
<log4j.version>1.2.14</log4j.version>
<spring-security.version>3.2.2.RELEASE</spring-security.version>

</properties>

<dependencies>

<!-- dependencies from parent pom start -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>

<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<!-- dependencies from parent pom end -->
<!-- Logger -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>

<!-- Jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersy.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersy.version}</version>
</dependency>

<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId>
<version>1.3.1.RELEASE</version> </dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- Jedis Driver Library -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.2</version>
</dependency>

<!-- Jersey + Spring -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersy.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<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-context</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- Hiberante template with mysql start -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
</dependency>

<!-- Spring security Start -->

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0</version>
</dependency>

<!-- Spring security End -->

<!-- <dependency> <groupId>org.glassfish.metro</groupId> <artifactId>webservices-osgi</artifactId>
<version>2.2.1</version> </dependency> -->

<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>webservices-osgi</artifactId>
<version>2.0.1</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- Java Mail API -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>


</dependencies>

<build>
<finalName>PublicAPI</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

Tuesday, 24 February 2015

LOGGER

#  Logging level
sdc.log=/logs/SDCLOGS/
log4j.rootLogger=debug, file, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS}-%t-%x-%-5p-%-10c:%m%n

#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9

#- File to log to and log format
log4j.appender.file.File=${sdc.log}/SDCReporting.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m%n

##log4j.logger.org.apache.zookeeper=WARN
##log4j.logger.org.apache.hadoop=WARN

# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF

#set hibernate logs to Error level
log4j.logger.org.hibernate=WARN

#set spring logs to Error level
log4j.logger.org.springframework=WARN

Thursday, 12 February 2015

Java – private constructor example

Singleton Class

The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time. We will see in the below example how to use private constructor for limiting the number of objects for a singleton class.


package beginnersbook.com;
public class SingleTonClass {
   //Static Class Reference
   private static SingleTonClass obj=null;
   private SingleTonClass(){
      /*Private Constructor will prevent 
       * the instantiation of this class directly*/
   }
   public static SingleTonClass objectCreationMethod(){
 /*This logic will ensure that no more than
  * one object can be created at a time */
 if(obj==null){
     obj= new SingleTonClass();
 }
        return obj;
   }
   public void display(){
 System.out.println("Singleton class Example");
   }
   public static void main(String args[]){
 //Object cannot be created directly due to private constructor 
        //This way it is forced to create object via our method where
        //we have logic for only one object creation
 SingleTonClass myobject= SingleTonClass.objectCreationMethod();
 myobject.display();
   }
}
Output:
Singleton class Example

Monday, 9 February 2015

How to override equals() in Java - Example

How to override equals() in Java - Example

. "Why to override equals() in Java" and "How to override equals() in Java".

We all know it very well that all classes in Java are descendent of Object class, or we can say every class inherits the methods and properties of Object class by default. There are a number of methods in Object class and hence is "public boolean equals(){}".

The public boolean equals(){}, compares two objects and return true or false accordingly. If we don’t override equals in our own class than one present in Object class is called and it compares the object using ‘==’ operator and hence two objects are equal only if their references are same.

Assume we have an class Apple, lets compare its objects using equals() and examine the result.

class Apple {

 private int id;
 private String name;

 public Apple() {
 }

 public Apple(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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


No lets see what happened when we call an equals() method from Object class itself without overriding it.
public class Implementation {
 public static void main(String args[]) {
  Apple greenApple = new Apple(1, "Apple");
  Apple redApple = new Apple(1, "Apple");

  // returns a false
  System.out.println(greenApple.equals(redApple));
 }
}
In the example above we can see that even if two instance of Apple are having same data in them but the equals() method from Object class is assuming them to be non equal. The reason is the default implementation of equals() check for references and two objects are same only if their reference is same. And certainly you would not want this kind of behavior in your application, hence we override equals.
Note: Two String object with same values returns true on equals() even if having different references, the reason is String itself override equals() and implement the functionally so that the String content to compare not their references. Hence we can do it in our very own class.

We can override equals() in our own class and give that our own implementation to compare objects considering some contract. The meaning of contract here is that when overriding equals() we must took care of certain rules and those rules should not violate.

If an class “Apple” has three instances “greenApple” , “redApple” and “yellowApple” than according to contract

1) greenApple.equals(greenApple) must be true always. Reflexive

2) If greenApple.equals(redApple) is true than redApple.equals(greenApple) must be true. Symmetric

3) If greenApple.equals(redApple) is true and redApple.equals(yellowApple) is also true than greenApple.equals(yellowApple) must be true. Transitive

4) For any two refrences say “redApple” and “yellowApple” the equals() method must return true or false consistently unill and unless the property of class that is used is equals() is not modified. Consistent

5) For any non-null reference value greenApple, greenApple.equals(null) should return false. Null Test


Now let’s check if we did it right and does not violate the contract.

And we are getting the expected result that passes the equals() override contract. Now the conclusion of the whole story is that:

1) The public boolean equals(){} is a method that resides in Object class and hence can be overridden in our own classes as well.

2) If one does not override it than the default behavior is being calles i.e. two objects are equal only if their references are same.

3) We can override equals() in our own class and can give own implementation to compare two objects until and unless we are not violating the equals() contract.

Big Big NOTE: If you override equals() in your own class than you must override hashCode() as well, unless it can violate hashCode() contract with equals() that results in Hash Based collections functionality and implementation.


In this particular blog we came across "why to override equals() in Java" and "How to override equals in Java". In our upcoming blog we will come across "how to override hashCode() in Java" and other tips and tricks about Java.

Spring Security with Hibernate using Maven - Authentication and Authorization Example

URL: http://www.beingjavaguys.com/2014/08/spring-security-with-hibernate.html


Application-Context.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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:sec="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.thingovation.smartcollar.*" />
    <!-- <context:property-placeholder location="database.properties"/> -->
    <context:property-placeholder
        location="classpath*:database.properties,classpath*:mailConfs.properties" />

    <!-- CentOS -->
    <!-- <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:use-pool="true" p:host-name="${redis.hostname}" p:port="${redis.port}"/> -->

    <!-- Dev Server -->
    <bean id="jedisConnFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:use-pool="true" p:host-name="${redis.hostname}" p:port="${redis.port}"
        p:password="${redis.password}" />

    <!-- Redis Template -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
        p:connection-factory-ref="jedisConnFactory" />


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${mysql.drivername}" />
        <property name="url" value="${mysql.url}" />
        <property name="username" value="${mysql.username}" />
        <property name="password" value="${mysql.password}" />
        <property name="maxWait" value="10" />
        <property name="maxIdle" value="5" />
        <property name="maxActive" value="5000" />
        <property name="validationQuery" value="SELECT 1" />
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="true" />
        <property name="testWhileIdle" value="true" />
        <property name="timeBetweenEvictionRunsMillis" value="10000" />
        <property name="minEvictableIdleTimeMillis" value="600000" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.thingovation.smartcollar.dto" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/> </bean> <tx:annotation-driven
        transaction-manager="transactionManager"/> -->

    <!-- Spring security -->

    <sec:http auto-config="true" create-session="stateless"
        entry-point-ref="restAuthenticationEntryPoint"

        authentication-manager-ref="authenticationManager">
        <sec:intercept-url pattern="/rest/publicapi/getDogActivityByTagId/*"
            access="ROLE_USER,ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getMostRecentDogActivity/*"
            access="ROLE_USER,ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getDogActivitiesByDateRange/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getAddress/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getTagsNearBy/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url
            pattern="/rest/publicapi/getTagsNearByRadiusSearchOverTime/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url
            pattern="/rest/publicapi/getTagsInGivenAreaByRadiusSearch/**" access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/postUserLocation/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/savePermanentLocations/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/saveTemporaryVisitedLocations/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getCommandResponseStatus/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/SaveGeofencingCoordinations/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/getDogActivities/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/saveDogStatus/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/saveGigyaId/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/saveGestureSequences/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/saveGestureSequencesToTag/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/tagActivation/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/userFirstLogin/**"
            access="ROLE_ADMIN" />
        <sec:intercept-url pattern="/rest/publicapi/showEventStatus/**"
            access="ROLE_ADMIN" />
        <sec:form-login authentication-success-handler-ref="mySuccessHandler"
            authentication-failure-handler-ref="myFailureHandler" />
        <sec:logout />
        <sec:http-basic />
    </sec:http>


    <bean id="restAuthenticationEntryPoint"
        class="com.thingovation.smartcollar.security.RestAuthenticationEntryPoint" />
    <bean id="mySuccessHandler"
        class="com.thingovation.smartcollar.security.SavedRequestAwareAuthenticationSuccessHandler" />
    <bean id="myFailureHandler"
        class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
    <!-- Spring Mail -->

    <!-- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${smtp.host}" /> <property name="port" value="${smtp.port}"
        /> <property name="username" value="${smtp.authenticationUsername}" /> <property
        name="password" value="${smtp.authenticationPassword}" /> <property name="javaMailProperties">
        <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop>
        <prop key="mail.smtp.ssl.trust">smtp.gmail.com</prop> </props> </property>
        </bean> -->
   
    <!-- Configure Authentication manager -->
    <bean id="bcrypt"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <constructor-arg name="strength" value="11" />
    </bean>
   
    <sec:authentication-manager alias="authenticationManager">
        <sec:authentication-provider>
            <sec:password-encoder ref="bcrypt" />
            <sec:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="SELECT USERNAME, PASSWORD, ENABLED FROM USERS WHERE USERNAME=?"
                authorities-by-username-query="SELECT US.USERNAME ,UR.ROLENAME FROM USERS US, USER_ROLES UR
                WHERE US.UID = UR.UID AND US.USERNAME =? " />
        </sec:authentication-provider>
    </sec:authentication-manager>

</beans>


Spring-sesurity.xml



<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.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 id="clientDetails"
        class="org.springframework.security.oauth2.provider.client.JdbcClientDetailsService">
        <constructor-arg index="0">
            <ref bean="dataSource" />
        </constructor-arg>
    </bean>

    <!-- Configure Authentication manager -->
    <bean id="passwordEncoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <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 id="clientDetailsUserService"
        class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <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 id="tokenStore"
        class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <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 id="tokenServices"
        class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
        <property name="tokenStore" ref="tokenStore" />
        <property name="supportRefreshToken" value="true" />
        <property name="clientDetailsService" ref="clientDetails" />
        <property name="accessTokenValiditySeconds" value="300" />
    </bean>

    <!-- A user approval handler that remembers approval decisions by consulting
        existing tokens -->
    <bean id="oAuth2RequestFactory"
        class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg ref="clientDetails" />
    </bean>
    <bean id="userApprovalHandler"
        class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
        <property name="requestFactory" ref="oAuth2RequestFactory" />
        <property name="tokenStore" ref="tokenStore" />
    </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: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"
        token-services-ref="tokenServices" resource-id="rest_api" />

    <!-- Grants access if only grant (or abstain) votes were received. We can
        protect REST resource methods with JSR-250 annotations such as @RolesAllowed -->
    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
        <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 id="clientAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="Authorization/client" />
        <property name="typeName" value="Basic" />
    </bean>
    <bean id="oauthAccessDeniedHandler"
        class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

    <!-- 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 id="clientCredentialsTokenEndpointFilter"
        class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="oAuth2ClientContextFilter"
        class="org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter">
    </bean>

    <sec:http pattern="/oauth/token" create-session="stateless"    authentication-manager-ref="authenticationManager">
        <sec:intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <sec:http-basic entry-point-ref="clientAuthenticationEntryPoint" />
        <sec:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
        <sec:custom-filter ref="oAuth2ClientContextFilter" after="EXCEPTION_TRANSLATION_FILTER    " />
        <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
    </sec:http>

    <sec:http pattern="/**" create-session="never" authentication-manager-ref="authenticationManager">
        <sec:anonymous enabled="false" />
        <sec:intercept-url pattern="/**" method="GET"    access="ROLE_USER" />
        <sec:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
        <sec:http-basic entry-point-ref="oauthAuthenticationEntryPoint" />
        <sec:access-denied-handler ref="oauthAccessDeniedHandler" />
    </sec:http>
   
   
    <bean id="oauthAuthenticationEntryPoint"
        class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="Authorization" />
    </bean>
   
</beans>


web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
            <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
            <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-security.xml, classpath:applicationContext.xml,/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>
   
    <!-- <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>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.thingovation.smartcollar.controller</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </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>

mvc-dispatcher-servlet.xml













































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

    <context:component-scan base-package="com.thingovation.smartcollar.controller" />

    <mvc:annotation-driven />

</beans>

Friday, 6 February 2015

Sending form data from AJAX to spring controller


Sending form data from AJAX to spring controller

We will select the form elements on the basis of their id's using jquery and their values will be stored in js variables. Then a request parameters data string will be made to send to spring controller. See the code below.

 <%@ 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>Insert title here</title>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>

</head>
<body>
 <center>
 


 <b>Being Java Guys | Registration Form </b>

 

  <script>
   function doAjaxPost() {
  
  
    var name = $('#name').val();
    var gender = $('#gender').val();
    var email = $('#email').val();
    var phone = $('#phone').val();
    var city = $('#city').val();

    $.ajax({
     type : "Get",
     url : "hello.html",
     data : "name=" + name + "&gender=" + gender + "&email="
       + email + "&phone=" + phone + "&city=" + city,
     success : function(response) {
      alert(response);
     },
     error : function(e) {
      alert('Error: ' + e);
     }
    });
   }
  </script>
  <div id="form">
   <form method="get">
    <table>
     <tr>
      <td>Name :</td>
      <td><input type="text" id="name" /></td>
     </tr>
     <tr>
      <td>Gender :</td>
      <td><input type="radio" id="gender" value="male" /> Male

       <input type="radio" id="gender" value="female" /> Female</td>
     </tr>
     <tr>
      <td>Email :</td>
      <td><input type="text" id="email" /></td>
     </tr>
     <tr>
      <td>Phone :</td>
      <td><input type="text" id="phone" /></td>
     </tr>
     <tr>
      <td>City :</td>
      <td><select id="city"><option value="noida">Noida</option>
        <option value="delhi">Delhi</option>
        <option value="gurgaon">Gurgaon</option>
        <option value="others">Others</option>
      </select></td>
     </tr>
     <tr>
      <td> </td>
      <td><input type="button" value="Save" onclick="doAjaxPost();" />
      </td>
     </tr>
    </table>
   </form>
  </div>
 </center>
</body>
</html>

Getting ajax data in spring controller and sending response back to ajax

Now we will use @RequestMapping annotation along with required value attributes to get the data send from ajax as request parameters and store that directly in java variables. At the end we have used @ResponseBody annotation to send back the response to ajax function in json format. See the code below:

package com.beingjavaguys.controller;
/**
 * @author Nagesh Chauhan
 */
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Home {

 @RequestMapping("/hello")
 public @ResponseBody
 String hello(@RequestParam(value = "name") String name,
   @RequestParam(value = "gender") String gender,
   @RequestParam(value = "email") String email,
   @RequestParam(value = "phone") String phone,
   @RequestParam(value = "city") String city) {
  System.out.println(name);
  System.out.println(gender);
  System.out.println(email);
  System.out.println(phone);
  System.out.println(city);

  String str = "{\"user\": { \"name\": \"" + name + "\",\"gender\": \""
    + gender + "\",\"email\": \"" + email + "\",\"phone\": \""
    + phone + "\",\"city\": \"" + city + "\"}}";
  return str;

 }
}
If everything goes right ajax function will call the spring mvc controller along with data to sent, we will see sended data values printed on console and a response string from controller to ajax as alert.

 Simple Html Form

 

Response back from controller



In this particular blog we came across how to use a ajax function to send data to spring controller and getting back the response in json format. In upcoming blogs we will see more about spring mvc and other opensource technologies.

Thursday, 5 February 2015


Types of polymorphism in java- Runtime and Compile time polymorphism

Earlier we saw all about Polymorphism in Java. In this tutorial we will cover types of polymorphism in java. There are two types of polymorphism in java- Runtime polymorhism( Dynamic polymorphism) and Compile time polymorphism (static polymorphism).

Runtime Polymorhism( or Dynamic polymorphism)

Method overriding is a perfect example of  runtime polymorphism. In this kind of polymorphism, reference of class X can hold object of class X or an object of any sub classes of class X. For e.g. if class Y extends class X then both of the following statements are valid:
Y obj = new Y();
//Parent class reference can be assigned to child object
X obj = new Y();
Since in method overriding both the classes(base class and child class) have same method, compile doesn’t figure out which method to call at compile-time. In this case JVM(java virtual machine) decides which method to call at runtime that’s why it is known as runtime or dynamic polymorphism.
Lets see an example to understand it better.

Difference Between REST And SOAP

REST SOAP
Assumes a point-to-point communication model–not usable for distributed computing environment where message may go through one or more intermediaries Designed to handle distributed computing environments
Minimal tooling/middleware is necessary. Only HTTP support is required Requires significant tooling/middleware support
URL typically references the resource being accessed/deleted/updated The content of the message typically decides the operation e.g. doc-literal services
Not reliable – HTTP DELETE can return OK status even if a resource is not deleted Reliable
Formal description standards not in widespread use. WSDL 1.2, WADL are candidates. Well defined mechanism for describing the interface e.g. WSDL+XSD, WS-Policy
Better suited for point-to-point or where the intermediary does not play a significant role Well suited for intermediated services
No constraints on the payload Payload must comply with the SOAP schema
Only the most well established standards apply e.g. HTTP, SSL. No established standards for other aspects.  DELETE and PUT methods often disabled by firewalls, leads to security complexity. A large number of supporting standards for security, reliability, transactions.
Built-in error handling (faults) No error handling
Tied to the HTTP transport model Both SMTP and HTTP are valid application layer protocols used as Transport for SOAP
Less verbose More verbose