Sunday, June 22, 2014 2 comments

A little bit on the JVM and JIT

As you might be aware, the JVM(Java Virtusal Machine) is what makes it possible for Java to adhere to the write-once-run-anywhere paradigm. At its core, the JVM consists of the following components;

Heap
Stack
PermGen and Method Area
JIT Compiler
Code cache

The heap is where memory is allocated for every new operator you use during the application code development stage. Stack will store the local variables that you will assign within the scope of a method. One thing to note is that the variables defined within the scope of a method will be removed after the completion of the method. If for example, a String is assigned within the scope of a method, and its scope is guaranteed to be of local scope, then this will be stored in the stack which would otherwise be assigned within the heap.
The PermGen space will store class and method level data as well as static variables that are defined in your application. The method area is actual an area within the PermGen space where it will store all method,field, constant pool level details of your application.

The JIT compiler and the code cache go hand in hand. The JVM at its core interprets the Java Byte Code into assembly code at runtime. Interpreting can be a slow process because the code needs to be converted from byte code to machine code at runtime every time a portion of your application code is executed. This is where the JIT compiler comes into action, with its super awesome compilation of methods which it then stores in the code cache.

The JIT compiler analyzes the application code at runtime to understand which methods can be categorized as hot methods. Hot in this context meaning code fragments that are accessed more frequently. At a very high level, what the JIT compiler does is that it will have a counter for each method executed in order to understand the frequency of its usage. When the counter reaches a defined threshold value, the method then becomes eligible to be compiled by the JIT compiler to its respective assemble code which will then be stored within the code cache. What happens is that now, whenever the JIT compiler comes across calls to those methods which were compiled and stored within the code cache, it will not try to interpret them yet again but will use the already compiled assembly code available within the code cache. This gives your application a performance boost because using the compiled code is much faster than interpreting it during runtime.

When talking about the JIT compiler, there are mainly two flavors of it which we are mostly oblivious of due to the fact of the lack of documentation around them. The two types are;

Client
Server

The default compiler used will defer according to the machine architecture and the JVM version (32bit or 64bit) that you are running on. Let us briefly see what each one does.

The client compiler starts compiling your byte code to assembly code at the application startup time. What this indirectly means is that your application will have a much improved startup time. But the main disadvantage this brings along with it is that your code cache will run out of memory faster. Most optimizations can be made only after your application has run for a brief period of time. But since the client compiler already took up the code cache space, you will not have space to store the assembly code for these optimizations. This is where the server cache excels.

Unlike the client compiler, the server compiler will not start compiling at the start of your application. It will allow the application code to run for some time (which is often referred to as the warm-up period) after which it will start compiling the byte code to assembly code which it will then store within the code cache.
In my next post I will discuss how we can actually mix and match the client and server compilation and also introduce you to a few more JVM flags that we seldom come across but are vital for increasing the performance of your application.

Friday, June 6, 2014 1 comments

Finding the Equilibrium index of an array

I wanted to do a brain teaser today so i took up an algorithmic question to give a shot at. Now i know this question already has many answer on the internet if you do a quick search. But i wanted to try it out with the solution that came to my mind. The problem statement is as follows;

Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an arrya A:

A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0

3 is an equilibrium index, because:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]

6 is also an equilibrium index, because sum of zero elements is zero, i.e., A[0] + A[1] + A[2] + A[3] + A[4] + A[5]=0

7 is not an equilibrium index, because it is not a valid index of array A.

Write a function int equilibrium(int[] arr); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist.

The solution i came up with is as follows;


 
public static int solution(int[] A) {

  if (A == null || A.length < 3)
   throw new RuntimeException("Cannot find equilirbium");
  int pointer = 1;
  int lowerIndCount = A[0];
  int upperIndCount = 0;

  for (int i = 2; i < A.length; i++) {
   upperIndCount += A[i];
   if (lowerIndCount < 0) {
    if (upperIndCount > lowerIndCount && i != A.length - 1)
     continue;
    if (upperIndCount == lowerIndCount && i == A.length - 1)
     break;
    lowerIndCount += A[pointer];
    upperIndCount = 0;
    ++pointer;
    i = pointer;
   } else {
    if (upperIndCount > lowerIndCount) {
     lowerIndCount += A[pointer];
     upperIndCount = 0;
     ++pointer;
     i = pointer;
    }
   }
  }

  if (upperIndCount == lowerIndCount)
   return pointer;

  return -1;
 }

If this is the optimum or not im not sure. Im also not sure if this will work on very large data sets. But for the data sets i tried(both negative and positive) it worked fine. And also this has O(N) complexity as I am iterating through the array only once.


Sunday, January 26, 2014 0 comments

Enter the Node-Hood

So today we will explore the node neighborhood in order to see what awesome goodies lie in the node-land. Ok I am no expert artist, but I remember well when I jot down something I learn into a diagram and utter those famous words “A picture speaks a thousand words”. And of course I love to learn by adding some humor to it which again makes me remember things better. So this is my lame attempt in doing just that to introduce the world of Node to anyone who might be interested.


If you are a node pro, I will save you the time and ask you to close this tab right now… Ah so you did not close it, great, then come on in. So let us see what we will find today on node-land. Following is a picture I just drew in order to emphasize what we will focus on today.



So this is the node home as of now for me. You are greeted with a door mat which leads to the site where you can get more information on the same. And as always you can see just right to the door, there is a CD( who uses CDs nowadays, I know) which states the famous command you will encounter many a times when you are working with node.
npm install <module_name>
Add a –save to the end of the command, and it will save the module you just installed in your package.json file. More on that in the future when we discuss web development with express.
The today’s special bored in the house highlights some core modules that you will find when working with node. They include;
  •  fs
  • crypto
  • process
  • http


This is not the whole list and you will indeed find many more as we go along with the journey through nodejs.

So we have a friend inside our nodehood who is asking for a cool beer. His best friend as you can see is approaching the Node Fridge to get him one. In node land, you can ask for external elements if they are willing to expose their functionality. And this is done through the use of exports. Let us see more closely what is happening inside the Node Fridge;


 
var  drink = function(name){
 return "Cool "+name;
}

module.exports.drink = drink;


So the Node Fridge is exposing a drink function which returns any drink that is passed into it with an added coolness to the drink. Of course there is no point in the fridge having the cold drinks if no one is going to be drinking it, and hence we use a mode.exports at the end to expose this coolness to the whole world.

So his friend has to open up and drink this up. Since he requested this first from his friend, he added the following;


 
var beer = request('./nodefridge');

console.log("Chilling with a ”+beer.drink("beer");


As he is making the request for the drink from the same house itself, he can do as it has been highlighted in the above code. But if he was asking this from the backyard of the house, then he will need to request for the same as follows;


 
var beer = request('./backyard/nodefridge');

The assumption here is that the nodefridge.js is residing in the backyard directory. You can download this simple example from here and run it using node main.js.

So today we will cover how file streams work in the node world. The main point here is that node file streams work with the use of Event Emitters which is a way of notifying results as and when an event occurs. It is slightly different from callbacks where you can get partial results even if an error occurs midway through. It acts as more of a Pulish/Subscribe model as opposed to the Request/Reply  model in callbacks.


Before diving into how streaming works in Node, let us see how they actual work within this new found Event emitter paradigm. Again a little comic strip will better help you understand the interaction between the Readable Streams and Writtable Streams. And no surprises with their names where RS Dude is representing Readable Streams and WS Dude will be representing Writable Streams. Let us see how this turns out;




The story is self explanatory I believe. But if you want to go all technical, here is it in technical terms.

·         The read stream will pipe itself to the writable stream where by the writable stream will it’s write method internally.
·         As it keeps on writing, the write() method can send false which means it cannot accept any more data for the moment. At this moment, the readable stream will call it’s pause() method.
·         After the writable stream is ready again, it will call it’s drain() method and in turn the readable stream will call it’s resume() method and the data will again start flowing.
·         When the end of the stream is reached by the readable stream, it will call it’s end() method and the writable stream will call it’s end() method as well and close the stream.

I have included a sample on using readable streams which is available in the same download I mentioned earlier. You can run the examples as follows;
node readable.js
node wriestream.js

Note that before you run this, please run npm install request as this example requires this module.


Tuesday, October 29, 2013 1 comments

Templating with KnockoutJS

Another nice feature of KnockoutJS is the ability to have templates to display your data. For instance, say that if you have a collection of data and you want them to be displayed in a particular format without having to do much DOM manipulation. This can be achieved in two ways when it comes to KnockoutJS;


  • Using jQuery based templating
  • Using native knockout templating
In this tutorial i will show you both the ways and you will see why you would always want to use the native KnockoutJS templating given its unobtrusive nature.

So first off let us look at the example below;


 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Superhero Registration</title>
</head>

<body>

 <div data-bind="template:'superHeroTemplate'">
  
  
 </div>


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery-tmpl.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

 <script type="text/javascript">
 
 $(function(){
   
   var data = [
    new superHero('Superman'),
    new superHero('Spiderman')
   ];
   
   var viewModel = {
    superHeroes:ko.observableArray(data)
   };
   
   function superHero(name){
    return {
     name:ko.observable(name)
    };
   }
   
   ko.applyBindings(viewModel);
  }
  );
 </script>
<script id="superHeroTemplate" type="text/html">
 <ul>
  {{each superHeroes}} 
   <li>${name}</li>
  {{/each}}
  
 </ul>
</script>
</body>
</html>

Ok i am obsessed with superheroes hence the use of examples follow the same pattern. Here what i am doing is constructing an observable array of super heroes.


 
function superHero(name){
    return {
     name:ko.observable(name)
    };
   }

The above function wraps the passed in input parameter to an observable object and passes it back. This is not required, but i have done as such so that Knockout will manage not only the observable array, but also the elements within the array since these are now observable objects themselves.

Here i am using jQuery templating and as such you need one additional script file to be included which you can dowload from here. Then you need to include it on your path in order for this example to work. I have saved this script file as jquery-tmpl.js. Note that the order you include these scripts are important as well. First it should be the jQuery script, then the jQuery template script and finally the KnockoutJS script.

First in the root element we need to define the template we are going to use. This is done as follows;


 
<div data-bind="template:'superHeroTemplate'">

Here you can see in the data-bind attribute i have defined the template as superHeroTemplate. Now this name is the name i have used as the id attribute within the template script i have used below;


 
<script id="superHeroTemplate" type="text/html">
 <ul>
  {{each superHeroes}} 
   <li>${name}</li>
  {{/each}}
  
 </ul>
</script>

Note that i have specified the type as text/html here since i do not want the browser to interpret this script tag since we are using this for the sole purpose of templating. The superHeroes attribute i have defined within the each tag is the name in my viewModel which is shown below. Also the ${name} attribute is what i am returning from the superHero function that returns obserable objects when passed in the name of the super hero.


 
 var viewModel = {
    superHeroes:ko.observableArray(data)
   };

This is all that is required for this to work. One thing you might have noticed is that this is a bit too obtrusive in terms of using additional DOM and script tags to make this work. This looks more of a hack since we are specifying script tags with a type calls text/html which is not valid just to make the templating work. This is where the native Knockout templating comes in handy. Let us look at how you can do the same using that and you will see why that is much cleaner.



 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Superhero Registration</title>
</head>

<body>

 <div>
  <ul>
   <!-- ko foreach:superHeroes -->
    <li data-bind="text: $data.name"></li>
   <!--/ko-->
  </ul>
  
 </div>


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery-tmpl.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

 <script type="text/javascript">
 
 $(function(){
   
   var data = [
    new superHero('Superman'),
    new superHero('Spiderman')
   ];
   
   var viewModel = {
    superHeroes:ko.observableArray(data)
   };
   
   function superHero(name){
    return {
     name:ko.observable(name)
    };
   }
   
   ko.applyBindings(viewModel);
  }
  );
 </script>

</body>
</html>

As you can see, no script tags were used. You directly work on the DOM and only need to add HTML comments block and write your code within that. You can even get rid of writing it within comments and directly embed the foreach loop within the DOM element as follows;


 
<div>
  <ul data-bind="foreach:superHeroes">
   <li data-bind="text:$data.name"></li>
  </ul>
  
 </div>

Much cleaner isnt it? No more hacks, just direct DOM manipulation. That is the power this library gives you. You can write it according to what you prefer.

So that ends my article on how to use templating with KnockoutJS. If you have any queries or feedback, please do leave by a comment which is as always highly appreciated.

Have a nice day everyone!!
Monday, October 28, 2013 0 comments

Getting knocked out

Everyone is saying JavaScript is the future and i was wondering what all the hype was. Was never a big fan of JavaScript to begin with since i was involved mainly with writing back-end code. But i am always open for new things and being the enthusiast i am, thought to try out one of the plethora of JavaScript libraries out there.

Since MVC knowledge is inherent in anyone who would have written any serious web application, i wanted to try out something closer to my comfort zone. This is where i stumbled upon knockoutjs . It advocates more of a MVVM(Model-View-View-Model) architectural pattern which i believe is a very handy way to handle your front-end logic with a clear layer of separation.

I remember the code we wrote prior to these libraries where we used a separate JSON array for each page to hold all the elements in that page and do all validations based on the attributes we define on each JSON attribute.

With Knockout, this is all handled by the library. It handles the data bindings to the elements, changes to the elements as well dependency tracking. I did some reconnaissance of my own on the library and this article is just an introduction to what you can achieve with this library.

The code is simple, i enter my first name and last name and i have a separate field that displays the full name by concatenating the first name and the last name. Then i have a simple button to generate the JSON string which we could use to send the data back to the server.

Let us look at the code;

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Personal Information</title>
</head>

<body>

 <div>
  <table>
   <tr>
    <td>First Name : </td>
    <td><input type="text" name="txtName" id="txtName" data-bind="value:firstname,valueUpdate:'afterkeydown'"></td>
   </tr>
   
   <tr>
    <td>Last Name : </td>
    <td><input type="text" name="txtLName" id="txtLName" data-bind="value:lastname,valueUpdate:'afterkeydown'"></td>
   </tr>
   
   <tr>
    <td colspan="2"><span id="lblFullName" data-bind="text:fullname"></span></td>
   </tr>
   
   <tr>
    <td colspan="2"><button data-bind="click: generateJSON">Generate JSON String</button></td>
   </tr>
  </table>
 </div>

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

 <script type="text/javascript">
 
 $(function(){
   var person = {
    firstname:ko.observable(''),
    lastname:ko.observable(''),
    generateJSON:function(){
     alert(ko.toJSON(person));
    }
   };
   
   person.fullname = ko.computed(function(){
    
    return "The full name is : "+this.firstname()+" "+this.lastname();
   },person);
  
   ko.applyBindings(person);
  
  }
  );
 </script>
</body>
</html>

As you can see from the code this is just a normal HTML mark-up. The magic happens within the code between the script tags. For ease of use of this code i have included the knockout and jquery scripts directly from the CDN locations because otherwise you would have to manually download them and include the scripts.

In Knockout, everything revolves around your Model. This is the main point of interaction in terms of Knockout. Here i have defined by model as person. One thing to note is that i have defined the firstname and lastname properties as observable. In Knockout, observables are JavaScript functions since not all browsers support getters/setters.

Then i need to tell how to map each property in my model to the DOM elements. This is done through the data-bind attribute. As you can see, in each input element, i have defined the data-bind attribute and stated that the value property should be equal to the value of the property in my Model.

Knockout also has a concept called computed observables which was previously called Dependent-Observables. What this does is that it allows me to aggregate any fields within the model and show them as part of the result as well and any change in the properties will be reflected in the computed observable variable as well. You can see that if you keep typing values to the firstname and last name input boxes, the full name string also changes accordingly. I have specified another value in the data-bind attribute as valueUpdate:'afterkeydown' which allows the changes typed into the input boxes to be reflected as the user types in which otherwise would only have reflected if the user tabs into the fields.

To bind our Model to the Knockout library, we call ko.applyBindings passing in our Model. There are helper methods that allow us to generate a JSON string of our model which is what i have done in the click event function defined within my Model.

I hope this introduction would get you interested to try this library out if you have not already. I will follow up this post with more advanced topics such as templating, observable arrays, parent binding context etc..

As always your comments and suggestions are most welcome.
Sunday, June 30, 2013 3 comments

Saying Hello To jQuery Mobile

You find a lot of debate on native mobile applications vs applications running on web views. For me the main priority was to get an application done in the minimum time whilst trying to achieve the smoothness of a native app.

Looking through many content on the web, i ended up with two main options as follows;


This was actually a pretty well thought out framework which was if i am not mistaken, not free initially but made available for free since recent times. Sencha Touch 2 is said to deliver applications that resemble a native application in the Web view space. I was inclined to go ahead with Sencha Touch 2 initially, yet since it was based mostly on JavaScript and since my JavaScript knowledge is a bit rusty and given the time constraints, i had to give up that idea since the learning curve was too steep.

Are we not all fans of jQuery? Well i sure am. Loved the jQuery core API and the time it saved me having to deal with nitty gritty JavaScript details. And then they go and develop a framework for the mobile space. As the syntax was not alien for me as it was when i was looking at some Sencha Touch 2 code, i digged a bit deeper to find out the pros and cons of the framework. I actually ended up using JQM on top of PhoneGap.

All WebView based applications depend on the native browser's support in order to deliver animations to resemble a native application. One drawback in terms of JQM was that my application was experiencing a jittery feel on Android 2.3 (GingerBread). The issue there being that the native browser which comes with GingerBread had less animation support. All animations work fine on higher versions other than 2.3 and lower. This was a drawback i had to succumb to given my time constraints on developing a native application. 

So in this post i will give a glimpse of common problems i ran into whilst using JQM and how to overcome those issues.


  • How do you bind to events on a given page
Coming from some experience on the jQuery core library, i jumped into using the document ready method which was what i was using when building web applications and trying to bind DOM events after the document was loaded. 
Yet this is not how things work on the JQM world. Since all pages are made up of div elements in the JQM space, the pages are loaded using ajax requests which enables the framework to resemble a native app which would not have been possible if the pages refreshed on each page load. Following is a code snippet which shows how one should bind events to a particular page in the world of JQM.



 
<div id="firstPage" data-role="page">
 <div data-role="content">
   <h1>Content</h1>
   
   <a id="showalert" data-role="button">Click Me</a>
 </div>
</div>


<script type="text/javascript">
$( "#firstPage" ).on( "pageinit", function( event, ui ) {

$('#showalert').click(function(){
 alert('i was clicked');
});

});
</script>

You will see that the page bindings happen using the on() method which is the successor for the predecessor methods such as live(), bind(). Here we have two options, we can either use the pageinit option or the pageshow option. I would not delve into the details of the two since it is self-explanatory.


  • How to programmatically move to another page
By default, page transitions happen through the usage of href links to the page ID of the page you want to go to. But on certain situations, you need the ability to do page transitions based on say a button click. This is how you would achieve this with JQM;



<div id="firstPage" data-role="page">
  <div data-role="header">Hi!! </div>
  <div data-role="content">
  <a id="gotoPage" data-role="button">Go to second page</a>
  </div>
  
  <div data-role="footer">The End</div>
 </div> 
 
<div id="secondPage" data-role="page">
 <div data-role="content">
   <h1>Second page</h1>
   
   
 </div>
</div>


<script type="text/javascript">
$( "#firstPage" ).on( "pageinit", function( event, ui ) {

$('#gotoPage').click(function(){
  $.mobile.changePage( "#secondPage", { transition: "flip"} );
});

});
</script>

Here what we are doing is transitioning from the first page to the second page on a button click. The usage of $.mobile.changePage allows us to accomplish our goal. The second option passed into it is optional where we could define various configuration parameters. I have defined an animation for the page transition when it occurs.


  • Dynamically loading content to a List View
You would often want to populate data to a list view by perhaps reading data from an external system. It would not work by simply creating the HTML content and appending it to the unordered list element. Following is how this can be achieved;



<div id="firstPage" data-role="page">
  <div data-role="header">Hi!! </div>
  <div data-role="content">
  <ul id="myList" data-role="listview" data-filter="true"
    data-filter-reveal="true"
    data-filter-placeholder="Search List..." data-inset="true">

   </ul>
  </div>
  
  <div data-role="footer">The End</div>
 </div> 



<script type="text/javascript">
$( "#firstPage" ).on( "pageinit", function( event, ui ) {

var dataArr = ["one","two","three"];
var content = '';
for(i=0;i<dataArr.length;i++){
content+='<li>'+dataArr[i]+'</li>';
}

 $('#myList').html(content);
 /**
 The following two method calls will refresh the List view with the updated data after page initialization
 **/
 $("#myList").listview("refresh");
 $("#myList").trigger( "updatelayout");

});
</script>

I have used a Javascript array here, but your typical use-case will fetch the data from an external source. The two calls to the listview after appending the html content to the list is where the update of the list takes place. Otherwise you will just get an empty list with no data on it.


  • Revealing list view data only on search
Here my requirement was to reveal the data within the list view only when the user types characters into the search bar. Something similar to a soft search functionality.  How i achieved this is shown from the following code snippet;





<div id="firstPage" data-role="page">
  <div data-role="header">Hi!! </div>
  <div data-role="content">
  <ul id="myList" data-role="listview" data-filter="true"
    data-filter-reveal="true"
    data-filter-placeholder="Search List..." data-inset="true" style="display:none;">

   </ul>
  </div>
  
  <div data-role="footer">The End</div>
 </div> 



<script type="text/javascript">
          $( document ).on( "pageinit", "#firstPage", function() {
   
    $( "#myList" ).on( "listviewbeforefilter", function ( e, data ) {
               
                                $input = $( data.input );
        value = $input.val();
                                if(value.length>0){
                                                loadData();
                                                $('#myList').css("display","block");
                                              
                                }
                                else if(value.length==0){
                                                
                                                $('#myList').css("display","none");
                                }
                               
    });
 

function loadData(){

var dataArr = ["one","two","three"];
var content = '';
for(i=0;i<dataArr.length;i++){
content+='<li>'+dataArr[i]+'</li>';
}

 $('#myList').html(content);
 /**
 The following two method calls will refresh the List view with the updated data after page initialization
 **/
 $("#myList").listview("refresh");
 $("#myList").trigger( "updatelayout");

}
</script>

Using the  listviewbeforefilter i would check if any data is input by the user and only in that instance would i load the data to the list view. Afterwards with a little bit of css i would show or hide the list view based on the input length entered by the user.


  • Passing data from one page to another
Another requirement for me was to pass data from one page to another while transitioning to that page. Since there is no concept of POST or GET in terms of JQM, i had to search how this can be accomplished. The following code snippet shows how this can be achieved;



<div id="firstPage" data-role="page">
  <div data-role="header">Hi!! </div>
  <div data-role="content">
   <a href="#secondPage?name=Tom&phone=9411225597" data-role="button">Check Name</a>
  </div>
  
  <div data-role="footer">The End</div>
 </div> 

<div id="secondPage" data-role="page">
 <div data-role="content">
  <h1 id="txtName"> </h1>
  <h1 id="txtPhone"> </h1>
 </div>
</div>

<script type="text/javascript">
     $( "#secondPage" ).on( "pageshow", function( event, ui ) {
                                 
                                 
      var query = $(this).data("absUrl").split("?")[1];
                                 
        if(typeof query != 'undefined'){
            var params = query.split("&");
                               
            $('#txtName').html(params[0].replace("name=",""));
   $('#txtPhone').html(params[1].replace("phone=",""));
  }
    });
</script>

I am passing the data using the href  tag by appending the parameters as i would do in a typical GET request. The key here is how to capture the data once the data is passed into the second page. We first need to retrieve the URL using the absUrl attribute and thereafter its a simple split and replace of the parameters embedded within the URL. This is the only way i found by which one page can transfer data to another on page transition.


That's about it people. The points where i got stuck are the ones i wanted to highlight here so that anyone else who might face similar issues will benefit from this post if they ever came across it in time :).. I'm sure i will face many more obstacles along the way whereby i will follow this post up with those as well.

Thank you for reading and have a blessed day ahead.

And as usual comments and criticisms are always welcome along with your views on JQM as a framework for the mobile platform. So what do you think?


Monday, April 15, 2013 3 comments

Let us write a document style Web Service

You might be aware that there are mainly four different styles of web services we can make use of. They are as follows;


  • Document/Literal
  • Document/Literal Wrapped
  • RPC/Encoded
  • RPC/Literal
Of course the RPC/Encoded style is now deprecated. If you are interested you can read up on the different styles of web services and their pros on cons on this very comprehensive article found here.

Today we will see how to write a Document/Literal wrapped kind of a web service. The agenda of this post is as follows;

  • Write a simple web service based on Document/Literal wrapped
  • How to host the simple web service on a tomcat web container
  • A simple test client to test our service
So let us begin our journey;

  • Write a simple web service based on Document/Literal wrapped

package com.wsbindings;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.ParameterStyle;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;

@WebService
@SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL, parameterStyle = ParameterStyle.WRAPPED)
public interface AddService {

 @WebMethod
 public int addIntegers(@WebParam(name = "intOne") int paramOne,
   @WebParam(name = "intTwo") int paramTwo);
}


So this is our basic web service. This is our base interface for our service. As you can see, we first annotate it with the @javax.jws.WebService to indicate that its a web service we are going to write. Then comes the interesting part where we define our SOAPBinding. Here we state that we want to write a DOCUMENT style web service which is LITERAL and is a WRAPPED style. One thing to note here is that all three attribute values specified within the Soap Binding annotation are the default values so you can get away without declaring them here explicitly. I have done so for the purpose of clarity of this article.

Moving on, let us see how the implementation will look like for this particular interface;


package com.wsbindings;

import javax.jws.WebService;

@WebService(endpointInterface="com.wsbindings.AddService")
public class AddServiceImpl implements AddService{

 public int addIntegers(int paramOne, int paramTwo) {
  return paramOne+paramTwo;
 }

}


Again nothing spectacular here in terms of what this service does. Just adds the two numbers passed in and send back the result of the addition. Note that here again we have to annotate the implementation class with the @WebService annotation.

Now that we have completed the initial part of writing our web service contract and the implementation, let us see how we can host this on a tomcat web container.


  • How to host the simple web service on a tomcat web container
As you know, by default tomcat does not come with a JAX-WS implementation unlike typical application servers such as JBoss, Glassfish. Hence to get it working you need to get an implementation of the JAX-WS specification. In this instance we will be using Metro. You can either copy the jar files from the download to your WEB-INF/lib directory or you can make use of Maven to do that for you, which is what i will be doing in this article. So to get the require jar files related to the Metro implementation i add the following dependency to my pom;


 <dependency>
   <groupId>com.sun.xml.ws</groupId>
   <artifactId>jaxws-rt</artifactId>
   <version>2.1.3</version>
   <exclusions>
    <exclusion>
     <groupId>com.sun.xml.stream</groupId>
     <artifactId>sjsxp</artifactId>

    </exclusion>
   </exclusions>
  </dependency>

Note that i have added one exclusion here for the sjsxp artifact since i needed a newer version than which was being drawn up from transitive dependency. Because else you will get the following exception;

 Could not initialize class javax.xml.stream.XMLStreamException: Underlying stream encoding UTF-8 and input paramter for writeStartDocument() method utf-8 do not match.

In order to overcome this issue i needed to add the following dependency to my pom;


 <dependency>
   <groupId>com.sun.xml.stream</groupId>
   <artifactId>sjsxp</artifactId>
   <version>1.0.1</version>
  </dependency>

I was able to find this solution thanks to this thread.

Moving on, we need to define a specific xml file which should go under the WEB-INF directory called sun-jaxws.xml. This XML specifies how we can access our web services and where the implmentation class is found. Lets look at the content of this file;


<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
  <endpoint
     name="AddWS"
     implementation="com.wsbindings.AddServiceImpl"
     url-pattern="/addws"/>
</endpoints> 

Here we give the package in which our web service implementation class resides in as well as the URL pattern on how to access the particular web service. One last thing we should do is to add the following to our web.xml in order to host our web service successfully;


<listener>
  <listener-class>
   com.sun.xml.ws.transport.http.servlet.WSServletContextListener
  </listener-class>
 </listener>
 <servlet>
  <servlet-name>AddWS</servlet-name>
  <servlet-class>
   com.sun.xml.ws.transport.http.servlet.WSServlet
  </servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>AddWS</servlet-name>
  <url-pattern>/addws</url-pattern>
 </servlet-mapping>

Note that we have to define a context listener and a Servlet class which will handle our web service invocations. If you look at the source of the WSServletContextListner you will see it reads the sun-jaxws.xml file from the WEB-INF directory and creates class loaders accordingly for the web service context.

One thing about Document style web services is that you need to generate some code for the request and response. If you do not do this, you will get the following error with the following message;

Have you run APT to generate them?

You can generate the required classes using the wsgen tool which comes bundled up with your JDK installation. You can also use Apache-CXF to generate these classes for you. We will use the latter approach by using the apache-cxf maven plugin which is available for us. Include the following to your pom and your good to go;


 <plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>2.0.9</version>
    <dependencies>
     <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
      <version>2.0.9</version>
     </dependency>
    </dependencies>
    <executions>
     <execution>
      <id>generate-wsdl</id>
      <phase>process-classes</phase>
      <configuration>
       <className>com.wsbindings.AddServiceImpl</className>
       <argline>-classdir ${project.build.directory}/classes</argline>

      </configuration>

      <goals>
       <goal>java2wsdl</goal>
      </goals>
     </execution>
    </executions>
   </plugin>

Here we are using the java2wsdl command to generate the required request and response objects for our web service. As you can see i have used the <argline> attribute to specify where i want my generated classes to go to. Since the normal maven compile task which is run when building the war file will look in the classes directory, i have specified our classes to be included in the same path as well so that they will be bundled along with our web service class when the war is created. You can see all possible commands you can issue by going through the parameters specified here.

My pom was indicating an error when i included my apache-cxf maven plugin as follows;

Plugin execution not covered by lifecycle configuration

 and after some research on the problem i stumbled upon a solution as stated here.Hence to overcome this issue you have to include the following snippet under the <build> tag of your pom;


 
<pluginManagement>
   <plugins>
    <!--This plugin's configuration is used to store Eclipse m2e settings 
     only. It has no influence on the Maven build itself. -->
    <plugin>
     <groupId>org.eclipse.m2e</groupId>
     <artifactId>lifecycle-mapping</artifactId>
     <version>1.0.0</version>
     <configuration>
      <lifecycleMappingMetadata>
       <pluginExecutions>
        <pluginExecution>
         <pluginExecutionFilter>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-codegen-plugin</artifactId>
          <version>2.0.9</version>
          <goals>
           <goal>test-compile</goal>
           <goal>compile</goal>
          </goals>
         </pluginExecutionFilter>
         <action>
          <execute />
         </action>
        </pluginExecution>
       </pluginExecutions>
      </lifecycleMappingMetadata>
     </configuration>
    </plugin>
   </plugins>
  </pluginManagement>

That should get rid of that error for you though i cannot give you an exact reason to why that warning pops up. If any of you know the exact reason, i would appreciate if you could leave a comment for the benefit of us all.

After that you can simply generate the war file and copy it to the webapps directory of tomcat. Then you will be able to access the web service on the following path;

http://localhost:8080/ws-bindings/addws

Where 8080 is the port on which i have hosted tomcat on and ws-bindings is the name of my war file.

Lastly let us see how to generate the client stubs required for our service and then write a small client to test our web service.


  • A simple test client to test our service
We will yet again use the apache-cxf maven plugin to generate the client stubs using the wsdl2java command. Note that first we need to get the wsdl from the path where our web service is hosted. It will be located at;

http://localhost:8080/ws-bindings/addws?wsdl

Then i copied the content to a separate xml file and saved it under a resources directory on the separate maven project i created to generate the client stubs. Then all you need to do is add the configuration required to generate the stubs in the pom as follows;


 
<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>2.0.9</version>
    <executions>
     <execution>
      <id>generate-sources</id>
      <phase>generate-sources</phase>
      <configuration>
     
       <wsdlOptions>
        <wsdlOption>
         <wsdl>${project.basedir}/src/main/resources/AddService.wsdl</wsdl>
        </wsdlOption>
       </wsdlOptions>
      </configuration>
      <goals>
       <goal>wsdl2java</goal>
      </goals>
     </execution>
    </executions>
   </plugin>

This will generate the required stubs for you to test your web service. Lastly let us write a client to use the generated stub to access our web service;


 
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.wsbindings.AddService;


public class DocWrapperClient {

 public static void main(String[] args) throws MalformedURLException {
   URL wsdlLocation = new URL("http://localhost:8080/ws-bindings/addws?wsdl");  
    
         QName qName = new QName("http://wsbindings.com/", "AddServiceImplService");  

         Service service = null;  
         service = Service.create(wsdlLocation, qName);  
         
         AddService ser = service.getPort(AddService.class);
         System.out.println(ser.addIntegers(1, 1));
 }
}


That is about it guys, and i hope you found the content useful. You can check out the example by downloading the server related maven project from here and the client stub generation maven project from here.

Thank you for reading and hope you have a lovely day ahead of your. Comments and criticisms are welcome as always.
 
;