Showing posts with label technology. Show all posts
Showing posts with label technology. Show all posts

Saturday, February 25, 2017

Apache Kafka: Multiple ways for Consume or Read messages from Kafka Topic

In our previous post, we are using Apache Avro for producing messages to the kafka queue or send message to the queue. In this post, we are going to create Kafka consumers for consuming the messages from Kafka queue with avro format. Like in previous post, there are multiple ways for producing the messages, same as with consumer, there are multiple ways for consuming messages from kafka topics.

As per previous post, with avro, we are using confluent registry for managing message schema. Before deserializing message kafka consumer read the schema from registry server and deserialize schema with type safety. If we want to check our schema is schema server, we can hit following end point using any rest tool.


  • http://localhost:8081/subjects (List of all save schema)
  • http://localhost:8081/subjects/<schema-name>/versions/1 (For detail structure of schema)

I: Simple Consumer

Like simple producer, we have simple Consumer for consuming messages produced by simple consumer. The best practices are, we need to follow same way for Producing/Consuming messages from topic. 

public class SimpleConsumer {

    private static Properties kafkaProps = new Properties();

    static {
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "CustomerCountryGroup");

    }

    private static void infinitePollLoop() {
        try(KafkaConsumer kafkaConsumer = new KafkaConsumer<>(kafkaProps)){
            kafkaConsumer.subscribe(Arrays.asList("CustomerCountry"));
            while(true) {
                ConsumerRecords records = kafkaConsumer.poll(100);
                records.forEach(record -> {
                    System.out.printf("Topic: %s, Partition: %s, Offset: %s, Key: %s, Value: %s",
                            record.topic(), record.partition(), record.offset(), 
record.key(), record.value());
                    System.out.println();

                });
            }
        }
    }

    public static void main(String[] args) {
        infinitePollLoop();
    }
}

II: Apache Avro DeSerialization Generic Format: 

Like Generic format producer, we have same Generic format consumer as well. In consumer, the same thing we need like avro schema or generated POJO class, by any built tools generator or plugin. 

public class AvroGenericConsumer {

    private static Properties kafkaProps = new Properties();

    static {
        // As per my findings 'latest', 'earliest' and 'none' values are used with 
kafka consumer poll.
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroGenericConsumer-GroupOne");
        kafkaProps.put("schema.registry.url", "http://localhost:8081");
        kafkaProps.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
    }

    public static void infiniteConsumer() throws IOException {
        try (KafkaConsumer kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("AvroGenericProducerTopics"));

            while (true) {
                ConsumerRecords records = kafkaConsumer.poll(100);

                records.forEach(record -> {
                    CustomerGeneric customer = (CustomerGeneric) SpecificData.get()
.deepCopy(CustomerGeneric.SCHEMA$, record.value());
                    System.out.println("Key : " + record.key());
                    System.out.println("Value: " + customer);
                });
            }
        }
    }

    public static void main(String[] args) throws IOException {
        infiniteConsumer();
    }
}

III: Apache Avro DeSerialization Specific Format One: 

This example is used for deserializer kafka message with specific format. This deserializer is used with corresponding Apache Avro Serialization Specific Format One in our previous post.  In this we are using Kafka Stream from deserialize the message. There is another simple way for deserialize the message which we will look into next example. 

public class AvroSpecificProducerOne {
    private static Properties kafkaProps = new Properties();
    private static KafkaProducer kafkaProducer;

    static {
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        kafkaProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class);
        kafkaProps.put("schema.registry.url", "http://localhost:8081");
        kafkaProducer = new KafkaProducer<>(kafkaProps);
    }

    public static void fireAndForget(ProducerRecord record) {
        kafkaProducer.send(record);
    }

    public static void asyncSend(ProducerRecord record) {
        kafkaProducer.send(record, (recordMetaData, ex) -> {
            System.out.println("Offset: " + recordMetaData.offset());
            System.out.println("Topic: " + recordMetaData.topic());
            System.out.println("Partition: " + recordMetaData.partition());
            System.out.println("Timestamp: " + recordMetaData.timestamp());
        });
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        Customer customer1 = new Customer(1001, "Jimmy");
        Customer customer2 = new Customer(1002, "James");

        ProducerRecord record1 = new ProducerRecord<>("AvroSpecificProducerOneTopic",
                "KeyOne", customer1
        );
        ProducerRecord record2 = new ProducerRecord<>("AvroSpecificProducerOneTopic",
                "KeyOne", customer2
        );

        asyncSend(record1);
        asyncSend(record2);

        Thread.sleep(1000);
    }
}

IV: Apache Avro DeSerialization Specific Format Two: 

This example of deserializer is used to deserialize message from kafka queue by Apache Avro Serialization Specific Format One producer. In the previous example we are using Kafka Streams, But in this, we are using simple way for deserialize the message. 

public class AvroSpecificDeserializerThree {

    private static Properties kafkaProps = new Properties();

    static {
        // As per my findings 'latest', 'earliest' and 'none' values are used with kafka consumer poll.
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroSpecificDeserializerThree-GroupOne");
        kafkaProps.put("schema.registry.url", "http://localhost:8081");
        kafkaProps.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
    }

    public static void infiniteConsumer() throws IOException {
        try (KafkaConsumer kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("AvroSpecificProducerOneTopic"));

            while (true) {
                ConsumerRecords records = kafkaConsumer.poll(100);

                records.forEach(record -> {
                    Customer customer = record.value();
                    System.out.println("Key : " + record.key());
                    System.out.println("Value: " + customer);
                });
            }
        }
    }

    public static void main(String[] args) throws IOException {
        infiniteConsumer();
    }
}



V: Apache Avro DeSerialization Specific Format Three: 

In this example we deserialize our messages from kafka with some Specific format. This is used for Apache Avro Serialization Specific Format Two producer in our previous post.

public class AvroSpecificDeserializerTwo {

    private static Properties kafkaProps = new Properties();

    static {
        // As per my findings 'latest', 'earliest' and 'none' values are used with kafka consumer poll.
        kafkaProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        kafkaProps.put("bootstrap.servers", "localhost:9092");
        kafkaProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        kafkaProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
        kafkaProps.put(ConsumerConfig.GROUP_ID_CONFIG, "AvroSpecificDeserializerTwo-GroupOne");
        kafkaProps.put("schema.registry.url", "http://localhost:8081");
        kafkaProps.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
    }

    public static void infiniteConsumer() throws IOException {
        try (KafkaConsumer kafkaConsumer = new KafkaConsumer<>(kafkaProps)) {
            kafkaConsumer.subscribe(Arrays.asList("AvroSpecificProducerTwoTopic"));

            while (true) {
                ConsumerRecords records = kafkaConsumer.poll(100);

                records.forEach(record -> {
                    DatumReader customerDatumReader = new SpecificDatumReader<>(Customer.SCHEMA$);
                    BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(record.value(), null);
                    try {
                        Customer customer = (Customer) customerDatumReader.read(null, binaryDecoder);
                        System.out.println("Key : " + record.key());
                        System.out.println("Value: " + customer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }

    public static void main(String[] args) throws IOException {
        infiniteConsumer();
    }
}

Still there are lots of ways for Produce/Consume messages from kafka. Some of the way we are discuss here, for other, may be we will come with new posts. Please feel free for sending feedback and post the comments. 


References: 

Wednesday, January 25, 2017

Short Interview With SMACK Tech Stack !!!

Hello guy's, today's we conduct short interview with SMACK about its architecture and there uses. Let's start with of some introduction.

Interviewer: How would you describe your self ?
SMACK: I am SMACK (Spark, Mesos, Akka, Cassandra and Kafka) and belongs to all open source technologies. Mesosphere and Cisco collaboration bundles these technologies together and create a product called Infinity.  Which is used to solved pipeline data challenges where the speed of response is matters like fraud detection system.

Interviewer: Why SMACK ?
SMACK: Now day's modern data-processing challenges are :
  • Data is getting bigger or more accurately, the number of data source is increasing.
  • Today, many modern business models data from one hour ago is practically obsolete.
  • Data analysis becomes to slow to get any return on investment info.
  • One modern requirement is to have horizontal scaling with low cost.
  • We live in a age where data freshness matters many times more than the amount or size of data.
There are many challenges we are facing, SMACK exist because one technology doesn't make an architecture. SMACK is a pipelined architecture model for data processing.

Interviewer: Lambda Architecture is data processing architecture and have advantage of both batch and stream processing methods, So, how SMACK different ?
SMACK: Yes, Lambda Architecture have these features, but most of the lambdas solutions cannot meet two needs at the same time :
  1. Handles a massive data stream in real time.
  2. Handles multiple and different data models from multiple data source.
For these. Apache Spark is responsible for real time analysis for both historical and recent and from massive information torrent and all such information and analysis results are persisted in Apache Cassandra. So, in the case of failure we can recover the real time data from any point of time. With lambda Architecture it's not always possible.

Interviewer: SMACK can you briefly describe about you technologies ?
SMACK: Yes sure, as we discussed SMACK is basically used for Pipeline data architecture for online data stream processing. There are lots of books and articles are available on each and every technology but we are using every technology for some specific purpose like:
  • Apache Spark: Processing Engine.
  • Akka: The Model.
  • Apache Kafka: The Broker.
  • Apache Cassandra: The Storage.
  • Apache Mesos: The Container.
See, all are Apache projects with the exception of Akka.

Interviewer: Is, SMACK is only solution ?
SMACK: No, You can replace individual components as per you requirements like Yarn could be used as the cluster scheduler instead of Mesos and Apache Flink would be suitable batch and stream processing alternatives to Akka. There are many alternatives to SMACK.

Interviewer: Could you discuss one of your case study with us ?
SMACK: Yes, But not know. I need to go with my technologies for some hangout, that we will discuss further in our next interview.

Interviewer: Can I take one picture of you ?
SMACK: Yes sure, cheeezzzz .....


References:

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.