Monday, June 30, 2014

Future in Java - Asynchronous Computation

These days I am doing a bit of Java programming. One of the new Features that I learned recently is Future.

A Future is a representation of the result of an asynchronous computation. A Future has methods to check if the computation has completed and retrieve the result of the task. You can also cancel a computation if you choose to, unless the computation has already completed.

A couple of notable methods in Future

  •  isDone() returns a boolean representing if the task is done. This method is used for polling to check if the task is done.
  • Get() returns the final result of the Future,it is a blocking method which waits until the computation is   done. This method take a timeout argument in milliseconds. Which specifies the maximum amount of   time we wait for the computation to complete. If the task is not done in the specified time, a  timeout exception will be thrown.
  •  Cancel()  will abort the computation.

Let’s see the context in which we can see the usage of Futures.Think of a hypothetical scenario in which we have to fire a http request asynchronously and do some random task while waiting for the response to come.

 The steps involved look like the following    
  • Fire http request and get the Future representing the outcome(i.e no waiting for the request to finish).
  • Do some random task
  • Check if the response is ready. Here we use the get() method to block and retrieve the response.

To demonstrate this with a code I will use an AsyncHttpClient from NING. This Client allows us to send out http requests and receive the response asynchronously. The execute method of this client returns a Future. 

 If you are using maven for your dependency management you can add NING to your project by adding this dependency.

<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.8.11</version>
</dependency>


Then your code will look like the following code snipnet . I am using the RequestBuilder utility from the same  library that allow me set the url, headers and other properties corresponding to http request.

RequestBuilder requestBuilder = new com.ning.http.client.RequestBuilder();
requestBuilder.setUrl("http://www.example.com");
AsyncHttpClient client = new AsyncHttpClient();
Future response = asyncHttpClient.executeRequest(requestBuilder.build());

//do some task here while waiting for the response

//check if the task is done.If not done , do some other task
If(!response.isDone()) {
// Do some other task
}
//at this point , block and wait for the response
try {
NettyResponse  value =(NettyResponse) response.get();
}
Catch(TimeoutException ex) {
//Log the exception or bubble it
}
Catch (ExecutionException ex) {
//Log the exception  or bubble it
}
Catch (Exception ex) {
//Log the exception  or bubble it
}

Saturday, February 1, 2014

Using Node.js to build a site that returns JSON data


I am working on a project that integrates with multiple other vendors using Http endpoint. We send http requests with JSON payload and the vendors has to consume that and respond with a response with JSON payload. I wanted to have a simple dummy site that takes the request and responds with the same kind of data I expect from the vendors. The whole objective of having this is to mock the vendor and test the integration. Moreover, I wanted an easy and fast process to create, deploy and start multiple mock vendor sites.

Node.js can be used to achieve this. For those of you who are already familiar with javascript, the code needed to create and run these sites is very minimal.


Note: this post is not supposed to be a tutorial on Node.js. That would be a topic for another day.Once I am comfortable enough with the nitty gritty details of Node.js, I hope to come back with a post.

I am using a Windows machine and here are the steps I followed,

1. Install Node.js from here

  •  Node.js will install a console window that you can use as a     playground or IDE.  Here you can write and run any JavaScript code
  •  Node.js root directory is included in the PATH variable of  system environment  variables . Thus you can invoke the node command from your command prompt
 2. I created a folder c:\projects\nodejsfiles where I keep all my            Node.js related files.     
    Note: You can keep your node file at any directory you want.

3. Copy the code shown below(after step 5) into notepad and save        it as myhttpendpoint.js under  the directory I created above.
   
4.  Open Command Prompt and navigate to the path where the              myhttpendpoint.js is located.
    
5.  In my case  c:\projects\nodejsfiles and then run the command
     node myhttpendpoint.js

6. Voila! the server should be up and running now. If you hit the url http://127.0.0.1:1337 from browser, you     should    see the JSON response being returned.

        The code looks like the following,

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/json'});
  var responseObj = {
  id: null,
  detail: [
    {
      part1: [
        {
          property1: 55,
          property2: "hello there!",
          property3: 12.0,
          property4: null,
          property5: 0,
          property6: true
        }
      ],
    
    }
  ],
 
};
  res.end(JSON.stringify(responseObj));
  }).listen(1330, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1330/');

Wednesday, June 26, 2013

IIS Servant - a web based management tool for IIS Manager

Big kudos to  Jonas Hovgaard for building it and making it available for public.  IIS Servant gives you access to IIS manager and you can do most of the basic tasks related to web site creation and maintenance that you normally do through IIS manager.

It saves you the trouble of  remote desktop to your severs to open IIS manager and manage your web sites.
It allows you do all this management actions through a beautiful user interface.

 I installed it on some of our web server boxes .The installation is very simple and you can install it and start using it in a matter of few minutes.

I had a CNAME ready to use for the iismanager site it is going to create and I used that as 'servant url' during installation.

You can download it from servant io
Here is a screen shot of one of my servant IIS configurations ...


Tuesday, April 23, 2013

The PRG /POST-REDIRECT-GET/ Pattern using ASP.NET MVC

This pattern is used to solve the double submit problem. When a user tries to refresh the result page of a post request, The page is resubmitted again resulting in undesirable results like double withdrawal of account, multiple orders etc.

If a post request is supposed to return a page, instead it should  does its side effect operation(e.g. saving order) and  redirect to a get request that returns the page. Thus result of the get request could be bookmarked and can be requested as needed with out a side effect(undesired additional orders).


The double submit problem is explained in depth in this article by Michael Jouravlev.

Using the ASP.Net MVC framework it is simple to implement the PRG pattern, below you will find a small 


code snipnet that uses the RPG pattern.


Step1(POST)  Controller action will make a redirect to Step 1(GET request) on error or if successful it will make a GET request to the next step 2(GET). Step 1(POST)  doesn't build and return pages it self.
[HttpGet]
[ImportModelStateFromTempData]
public ActionResult Step1(int id)
{

var m = _orderService.GetOrder(id);
return View(m);
}

[HttpPost]
[ExportModelStateToTempData]
public ActionResult Step1(Order m)

//If the model is valid(satisfies all the validation requirements set for it)
//persist it and make a get request to the next step 
//else make a redirect to GET request page 

if (ModelState.IsValid)
{
// save
-orderService.Save(m);
// Go to the next step (Step 2 here is a HttpGet ActionResult)
return RedirectToAction("Step2", new { id = m.OrderId });
}
//redirect to the Get Request

return RedirectToAction("Step1",new {id =m.OrderId});

}

[HttpGet]
[ImportModelStateFromTempData]
public ActionResult Step2(int id)
{

var m = _orderService.GetOrder(id);
return View(m);
}

Friday, March 22, 2013

Lunch and Learn Session on SignalR .Net - Realtime for Web


Here is the power-point  to the presentation I gave  my colleagues a few weeks back on SignalR.

Tuesday, January 15, 2013

Extending the default Command Timeout in Nhibernate



There was a Nhibernate query that is taking more than 30 sec , 34 seconds to be exact. The query involves a view that joins so many views and tables. It started taking more than 30 seconds last week. Reviewing the execution plan and throwing indexes here and there didn't help. The next immediate solution was to extend the Nhibernate default timeout time (i.e.30 seconds).

I believe extending the timeout should be a last resort approach , should be used as immediate fix until you come up with a long term solution - like redesigning your data architecture , optimizing your queries and others.

Nhibernate allows you set the command timeout for query. This timeout is the length of time the query will be allowed to execute and finish. If  the query takes more than this time,the query will be aborted and SQL timeout exception will be thrown.

Currently you can set the timeout on query if you are using ICriteria. The Nhibernate team is working to make this method (setting the timeout) available on  QueryOver  on the next release (3.3.x). 

I was using Nhibernate QueryOver for my query, thus I had to rewrite it using ICriteria , I know it is a bummer :(  . Assuming you are using a unit of work pattern  the code will be along the line of the following 


var query = _unitOfWork.currentSession.CreateCriteria<MyView>().          setTimeout(TIMEOUT_IN_MILLISECONDS);


I will leave it like that until we completely remove that view and replace it with a roll up table in our next release.


Friday, December 28, 2012

SignalR and Interval Polling for Dashboard Update

Have you ever wondered how some dashboard update their content with new data without the users intervention? If you check out the google finance stock dashboard you see the stock data is updated every few seconds. Google finance can be found here http://www.google.com/finance
I can think of two ways of achieving this objective,
   A.    Interval polling
This approach involves the client polling the server for new data in preconfigured time interval.
The client displays the new data and waits for the specified time and repeats the request again.
The drawback of this alternative is the unnecessary requests that is wasted to continually check for new data- even if the new data is available or not.

The conversation between the client (browser) and the server goes along the line of
Client: “Do you have new Data?”
Server: “No”
Client waits for 5 seconds and tries again
Client: “Do you have new Data?”
Server: “yes”
Client will update the dashboard

However, instead of the client continually checking the server for new data, Is there a way where the server can notify the client when the new data is ready. Luckily yes. Here SignalR comes to the rescue.

 B.     SignalR
This library allows us to write an application in which there is a bi-directional communication between the server and the client. In the newest version of browsers that support the new HTML5 API web sockets are used for communication. In browser where web sockets are not supported it will fallback to other legacy options to achieve the same objective. The list of fallback options include long polling ,interval polling etc.
At the core of this implementation we have the  Connection Hubs . Hubs provide a high level RPC framework over PersistentConnection. All the notification from the server to the client and vice versa is done through the hub. When the application is run, SignalR will emit the javascript equivalent of the Hub you defined in your C# assembly. So that you can start a connection from the client and then call methods defined in the hub(Server Calls). Moreover you can add client call in your javascript file that can be called by the server methods for server to client communication.
The SignalR documentation can be found here
The SignalR Nuget package installation procedure can be found here 

Lets see some code …
1.       Install Nuget package . In this example I am hosting the hub inside asp.net mvc app.
2.       Register the routing for signalr hub to be accessed through URL . Note: the signalr route registration should come before the asp.net mvc route registration.
If you don’t specify an alternative path name. The default /signalr/hubs will be used
        protected void Application_Start()
        {
            RouteTable.Routes.MapHubs();
            RegisterRoutes(RouteTable.Routes);
           
        }



3.       Server Code : I created a hub class called ReportHub. All Hub classes should inherit from the base Hub Class.
The ReportHub class now will have access to the public properties defined in the HubClass
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRDemo
{
    public class ReportHub : Hub
    {
         public void NotifyClients()
        {
            //notify all other clients to update their data
            Clients.Others.updateReport1();
            Clients.Others.updateReport2();
        }
       
      
        public void BroadCastData1Available()
        {
            Clients.Others.updateReport1();
        }

        public void BroadCastData2Available()
        {
            Clients.Others.updateReport2();
        }

    }
}

The ReportHub has three server calls that can be invoked by clients.
Looking NotifyClients() in detail

      In this line of code Clients.Others.updateReport1();
      updateReport1 is a method defined in the client.

I am sending out the notification to all clients except for the one who made the server call. If you           want the notifier  itself to be notified too, You can use Clients.All instead of Clients.Others. Note updateReport1() is a method defined in the client. Upon notification the client will execute the updateReport1() method in the javascript.

Some notable properties of Hub.
a.       Clients -  list of clients connected to the hub. This property will give you access to
Clients.All – all clients
Clients.Others – all clients except the one calling the hub’s method
Clients.Caller – the called calling hub method.
b.      Context
c.       Groups

4.       Client Code :
Register the following scripts on your client/view
<script src="/Scripts/jquery.signalR-1.0.0-rc1.min.js" type="text/javascript"></script>
   <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
               
 "~/signalr/hubs” – this is the path defined on your route. When the application is run, the signalR assemblies will use reflection to emit the javascript equivalent of the ReportHub class defined in the assembly.
The hub can be accessed from the client as show below. The connections can be started and an optional call back can be invoked when the connection is started or done.
You can also define methods on the clients to be invoked by the server. The updateReport() method discussed in the above section (Server Code) is define as follows.
        // Declare a function on the myHub hub so the server can invoke it         
        rptHub.client.updateReport1 = function () {
            // do something
        };

       

The whole script of the client is shown below.
$(function () {
        // Proxy created on the fly         
        var rptHub = $.connection.reportHub;

        // Declare a function on the rptHub hub so the server can invoke it         
        rptHub.client.updateReport1 = function () {
            RefreshData('map_canvas');
        };

        rptHub.client.updateReport2 = function () {
            RefreshData('map_canvas2');
        };

        // Start the connection
        $.connection.hub.start().done(function () {
          
        });
     
    });
How can we call the server from the client?You will call the server property of the hub and then you will have access to all the public methods in the hub.
E.g. If you want to invoke the notifyClients() method defined in the server/hub.
    // Call the notifyClients method on the server
       rptHub.server.notifyClients();

 Putting it all together
I have included a demo asp.net mvc application hosting a signalR hub. The application has a dashboard page which has two geomap charts  and there is an admin page with three buttons. Clicking the buttons on the admin page will notify the charts on the dashboard to update their content with a new data. The demo shows the bi-directional communication from the client to the server and vice versa.
 Admin page to Server Hub => client to server
Server Hub to Dashboard page => server to client
The full demo can be downloaded from here