Saturday 20 February 2016

Simple Producer Consumer design pattern in Java

Here I am going to create a simple producer-consumer program in java.
Let's take the below problem scenario.
Suppose I have a file containing the huge number of data. So my producer will read this data from the input file.
Put this data into a queue. Let's have two consumers to read this data from the queue.
Now we can go to implementation steps.

1.Producer
   For creating the producer thread, we can either extends Thread class or implements Runnable interface. here we are going to implement Runnable class since it has more advantages.

If we extend Thread class, we can’t extend any other class which may be required later. So I would prefer to use runnable interface.

Let's declare and use a shared queue in our producer as shown in the below snippet.

In producer, we are reading the data one by one from input.txt file and offering(putting) each entry one by one to String queue.
package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;

public class Producer implements Runnable {

private Queue<String> dataQ;

public Producer(Queue<String> sharedDataQ) {
dataQ=sharedDataQ;
}

@Override
public void run() {
File f=new File("test.txt");
try {
Scanner sc=new Scanner(f);
while(sc.hasNext()){
dataQ.offer(sc.next());
}
DataQueue.QofferCompleted=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}



2.Consumer

In Consumer thread, we will be polling the data from the queue and printing the output to the console. code snippets are shown below. Here we used a thread number variable to identify which thread is processing the data.
package test;

import java.util.Queue;

public class Consumer implements Runnable {

private int threadNumber;
private Queue<String> dataQ;
Consumer(int threadNumber, Queue<String> sharedDataQ){
this.threadNumber=threadNumber;
dataQ=sharedDataQ;
}

@Override
public void run() {
      while(!dataQ.isEmpty() || !DataQueue.QofferCompleted){
     if( !dataQ.isEmpty())  {
     try {
     String consumedData= dataQ.poll();    
     System.out.println("From "+this.threadNumber+":"+consumedData);
     } catch (Exception e) {
     e.printStackTrace();
     }
     }
     
      }
}

}


Now we can go corresponding runner class.

3.Runner
In Runner class, we are going to create one producer to read the data from the file and two consumers to process the data from the queue. Shared data queue is created and set for both producer and consumers. 

package test;

import java.util.LinkedList;
import java.util.Queue;

public class Runner {

public static void main(String[] args) {

Queue<String> sharedDataQ=new LinkedList<>();
Thread p=new Thread(new Producer(sharedDataQ));
p.start();
Thread c1=new Thread(new Consumer(1,sharedDataQ));
c1.start();
Thread c2=new Thread(new Consumer(2,sharedDataQ));
c2.start();

}

}


That's it. Hope this example helps the beginners to create a simple producer-consumer framework.
You will get below output finally for a sample test input file. Please add your suggestions to improve this.

From 1:example
From 1:of
From 1:producer
From 1:consumer
From 2:show
From 2:java
From 2:code
From 2:example



Wednesday 10 February 2016

Creating a restful web service and Invocation using angular

Step 1: Create a restful-webservice  as mentioned in
Step 2:
To access this rest api from angular, we need to create an angular web-app
Follow the below steps to create web-app in eclipse.
a) Create a Dynamic Web project in eclipse
    File->New->Dynamic web Project
    Give the project name as "angularjs-rest service".

b) Create the first page index.html

    Right click on WebContent folder ->New ->HTML File.
    Change the name to index.html.
    Open index.html and change the <title> as  “Angular Rest Service Demo".


c) Import AngularJs libraries

     We can include AngularJS library to our application using 'script' tag.
     Download following js files and copy them to Webcontent/js/lib folder.
     If the folder doesn’t exist, please create the same.

  •        angular.js
  •         angular-resource.js
       You can include them in the index.html as mentioned below

   

<script src="js/lib/angular.js"></script>
<script src="js/lib/angular-resource.js"></script>

d) Making angular app.
      Now we have imported all the required angular libraries required for invocation of your rest api.
      Now let’s define this app as angular app using ng-app directive from angular as mentioned below

       <body ng-app="serviceDemoApp">
       </body>

       Here name serviceDemoApp defines module for your angular app
e) Adding controller for your index.html
     Now let’s add a controller for your index.html file. In angular js controller controls the data  flow   to an html element using ng-controller directive. One can define the controller in a script file as mentioned below
For this we can create a new controller js inside Webcontent/js folder
Inside the controller we need to invoke the service, So before creating the  controller.js file, let’s create a service  js access your restful created.
We can use $resource from angular-resource for this purpose. This will help us to create a resource      object that lets you interact with RESTful server-side data sources.         
      Include ng-Resource module to your service module script as below

    var app=angular.module('serviceDemoApp',['ngResource']);

f) Defining service
You can define and register a service using a module.factory method. Here we are going to define
A DemoService to invoke your rest service created before
Save the file as service.js file, We will be invoking this service from controller js file


var app=angular.module('serviceDemoApp',['ngResource']);

app.factory('DemoService',function($resource){

       return $resource('/RestWebApp/rest/data/get/msg',{},{

              query:{

                     method:'GET',

                     params:{},

                     isArray:false
              }
       });
});
Here we have  defined a query method to get for GET request
e) Invoking the service
Inside the controller we need to pass the service instance created, please refer the code
below to create a controller and access the service, we will be setting the response to a controller.


var app = angular.module('serviceDemoApp');
app.controller('serviceCtrl',['DemoService','$scope',function(DemoService, $scope){
       //calling service 
       DemoService.query(function(DemoService){
              $scope.response=DemoService;

       })]);


Save the file as controller.js

f) Invoking from index.html

Add below scripts to your index.html


<script src="js/service.js"></script>
<script src="js/controller.js"></script>


Let’s add a div box  with controller added to reflect the data from backend restful web service

<div ng-controller="serviceCtrl">
        <table border="1">
            <tr>
                <td>Header</td>
                <td ng-bind="response.msgHeader"></td>
            </tr>
            <tr>
                <td>Data</td>
                <td ng-bind="response.content"></td>
            </tr>
        </table>         
   </div>

e) That’s it.
Now you can run the app in a server and you can view the results as the message you set from API.