Pages

Sunday, September 20, 2015

Cascading select list using custom directive of angular JS that takes json inputs.

I was trying my hand with Angular JS as it is becoming very famous front end framework. For more details about Angular JS, you may visit https://angularjs.org/.

One of the problem that I stuck was to implement a cascading select list. A cascading select is actually a set of select lists; those are interrelated to each other. Its like a map of entries where selection of first select list, filters result of second select list and so on. One of the useful example is - assume you have three select lists one for country another one is for state and last one is for city. Selecting country filters record of state and selecting state filters record of city. Now without talking much let's see to tackle this.-

The first page is index.html where you would like to show the select lists. Here is list of thing we should notice about this file.
  • The head tag has angular JS dependency which all required to build and AngularJS app.
  • cascading.js is our js file that we will explain in a while
  • first div under body tag has ng-app attribute. This informs AngularJS that this is the div that will contain angular JS related stuff. That simply means that if we write any AngularJS specific code outside this; it will be skipped.
  • another div is stating about controller of angular JS.
  • The most important part of this html is cascading tag. This is not a html tag but it is created as part of angular JS custom directive. This custom directive is taking three JSON city-state-map, country-map and state-country-map al used to supply data to custom directive. 

<!doctype html>
<meta charset="utf-8">
<html>
<head>
    <title>Adnan Try</title>
    <script type="text/javascript" src="../js/1.4.5/angular.min.js"></script>
    <script type="text/javascript" src="cascading.js"></script>
</head>
<body>
<div ng-app="cascading">
    <div ng-controller="CascadingCtrl">
        <cascading city-state-map = '{
        "cityStateMap" : [
                   {
                   "stateId": 111, "cities": [
                                            {id: 123, "label": "Akbar-pur"},
                                            {id: 124, "label": "Lucknow"}
                                            ]
                    },
                    {
                    "stateId": 112, "cities": [
                                                {id: 124, "label": "Lucknow"}]
                    }
        ]
        }'
                   state-country-map = '{
                   "stateCountryMap":[
                    {
                    "countryId" : 106, "states" : [{"id" : 111, "label" : "Argentina"},
                                                   {"id" : 112, "label" : "Delhi"}]
                    },
                    {
                    "countryId" : 107, "states" : [{"id" : 112, "label" : "Delhi"}]
                    }
        ]}'

                   country-map =  '{
    "countryMap": [
        {
        "id": 106,
        "label": "US"
        },
        {
        "id": 107,
        "label": "INDIA"
        },
        {
        "id": 110,
        "label": "UP"
        }
        ]
        }'

                >

        </cascading>
    </div>
</div>
</body>
</html>
Another file cascading.js file. It actually has all AngularJS specific logic to play around. it creates directive and handles changing value of one select list using another. The code is as follows-
angular.module('cascading', [])
    .controller('CascadingCtrl', ['$scope', function($scope) {

    }])
    .directive('cascading', function() {
        return {
            restrict : "E",
            scope : {
                countryMap : '@',
                stateCountryMap : '@',
                cityStateMap : '@'
            },
            templateUrl: 'cascading.html',
            link: function($scope, $element, $attribute) {
                var newVal = $scope.$eval('(' + $scope.countryMap + ')');
                $scope.countries = newVal.countryMap;
                $scope.countryChange = function(val){
                    $scope.cityMap = null;
                    var stateArray = $scope.$eval('(' + $scope.stateCountryMap + ')');
                    var filtered = stateArray.stateCountryMap.filter(function (data) {
                        return data.countryId == val;
                    })[0];
                    $scope.stateMap = typeof filtered !== 'undefined' ? filtered.states : filtered;
                };

                $scope.stateChange = function(val){
                    var cityArray = $scope.$eval('(' + $scope.cityStateMap + ')');
                    var filtered = cityArray.cityStateMap.filter(function (data) {
                        return data.stateId == val;
                    })[0];
                    $scope.cityMap = typeof filtered !== 'undefined' ? filtered.cities : filtered;
                }

            }
        };
    });
The final and V of MVC of AngularJS is the html file. here is cascading.html file-
<div>
    Country:
    <select id="country" data-ng-Model="country"  ng-change="countryChange(country)"
            data-ng-options="country.id as country.label for country in countries">
        <option value=''>Select</option></select>
</div>
<div>
    States: <select id="state" data-ng-disabled="!stateMap" ng-change="stateChange(state)"
                    data-ng-model="state"
                    data-ng-options="state.id as state.label for state in stateMap">
    <option value=''>Select</option></select>
</div>
<div>
    City: <select id="city" data-ng-disabled="!cityMap" data-ng-model="city"
                    data-ng-options="city.id as city.label for city in cityMap">
    <option value=''>Select</option></select>
</div>

So this is the complete demonstration of three select lists with cascading behavior implemented in angularJS custom directive approach. Place these files in one folder and open index.html. It should work well. Please feel free to add comments below if you have any questions concern or you think the approach can be better. Happy Coding...

Saturday, October 5, 2013

CountDownLatch tutorial: A class of java concurrency package

CoutDownLatch class is very popular interview question of multi-threading and concurrency control in java. Let's dig this more and find out all minute details about this. In this post I will cover many aspects including example of how it works, real time usages, possible interview questions on CountDownLatch. So here we go..

About CountDownLatch

CountDownLatch was introduced in JDK 1.5 under java.util.concurrent package. This class operates on threads. Let's see what Java says about this class-

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

So CountDownLatch provides way to synchronize threads in such a way that some threads will wait until all threads complete their execution. CountDownLatch works on counters So Idea is, you set counter value some value and some thread will be in waiting state till counter reaches to zero and some threads will be responsible to decrement counter by 1. For example say counter value is set to 3 and we tell JVM, “Hey JVM, Threads t1, t2, t3 will be in waiting state until counter reaches to zero and other threads t4, t5, t6 will be executing and in the will decrement the counter by one. ” So in this example threads t1,t2 and t3 will call countDownLatch.await() method and will move to waiting state and t4, t5 and t6 will be calling countDownLatch.countDown(). Method that will decrement counter by 1 and the moment counter reaches to zero, t1, t2 and t3 will move to ready to run state and will resume its execution once they get CPU cycle. One very important point about CountDownLatch is it's counter will decrease, it can not be reset again to count from start. So once it reaches to zero you can not use CountDownLatch class further.

How CountDownLatch works

CountDownLatch works on three basic principle:-
  • Create CountDownLatch object by passing count value in the constructor.
  • Call countDownLatch.await() on threads those you want to wait until counter reaches to zero.
  • Call countDownLatch.countDown() from threads those are in execution.
Let's see this by an example of Worker and Dispatcher. So responsibility of Dispatcher will be to start many worker Threads those will perform certain task and once all task is over Dispatcher will report saying all task assigned to worker threads are now over.
Let's see the coding part of this.
The Worker class
This class will take a CountDownLatch object and List of Worker threads as input. It's run method will spawn one thread for each worker and will go in waiting state by calling countDownLatch.await() method. Once all worker threads finish it's execution Dispatcher thread will again come into execution and print last line “All worker threads executed successfully. I may be now rest in peace.”
So That way, Dispatcher thread will be in waiting state and will wait for all worker threads to complete it's execution. Here is the Dispatcher class.
class Dispatcher implements Runnable{

    private final List workers;
    private CountDownLatch latch;

    Dispatcher(List workers, CountDownLatch latch){
        this.workers = workers;
        this.latch = latch;
    }
    @Override
    public void run() {
        System.out.println("Being a dispatcher, I am going to dispatch request to workers to finish their work now.");
        for (Worker worker : workers ){
            new Thread(worker).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("All worker threads executed successfully. I may be now rest in peace.");
    }

}

Worker class
This class is doing simple stuff. This guy is simply running his work and increasing latch decreasing latch count down by 1.
class Worker implements Runnable {
    private String workerName;
    private final CountDownLatch latch;

    public Worker(String workerName, CountDownLatch latch) {
        this.workerName = workerName;
        this.latch = latch;
    }


    private void work() {
        System.out.println(workerName + " is working.");
    }

    @Override
    public void run() {
        work();
        latch.countDown();
    }
}

Main class
And finally the main class that prepares worker objects and invoke dispatcher to dispatch requests.
public class CountDownLatchExampleMain {

    private static final int NUMBER_OF_WORKER = 10;

    public static void main(String[] args) {
        System.out.println("Main thread starts it's execution.");
        CountDownLatch latch = new CountDownLatch(NUMBER_OF_WORKER);
        List workers = new ArrayList(NUMBER_OF_WORKER);
        for (int i = 1; i <= NUMBER_OF_WORKER; i ++ ) {
            workers.add(new Worker("worker-" + i, latch));
        }
        new Thread(new Dispatcher(workers, latch)).start();
        System.out.println("Main thread end it's execution.");
    }
}


Real life examples to use CountDownLatch

There are few example that one can consider to use CountDownLatch. Although there can be many more. I appreciate if you would like to share your use case in this post. It would be great for everyone to add more scenario.
Achieving maximum parallelism: One of the possible use case is, you have a test case that tests about how your common resource will behave if n number of thread tries to access that resource in same time. Or you have a singleton class and you want to test if n threads trying to create instance then only one thread should be able to successful and other thread should simply get object.
A niche thread synchronization: Communication between thread is a handy example to use CountDownLatch. Like the example I took above where dispatcher will wait for all the worker threads to complete their executions and finally print some message. Another example could be, you want to send a notification to the user that all worker threads are done with execution.

Interview questions on CountDownLatch

Here are some common interview questions those are asked on CountDownLatch. Feel free to add more. I'll appreciate that effort.
  • What is CountDownLatch and how it works?
  • Give a real life use case where CountDownLatch can be beneficial?
  • Differentiate CountDownLatch with CyclicBarrier?
I hope this post is helpful for you. Feel free to add comments or feedback, I'll appreciate it. Happy coding.

Sunday, September 29, 2013

[Amazon interview question] Implement data structure overflow queue.

Implement data structure overflow queue. Overflow queue is a normal queue with one extra property. It never throw Stack overflow exception. So whenever queue becomes full, it replaces the oldest element present in the queue and front pointer simply shifted one step ahead. Constraint:- it should have public void enQueue(int n) and public int deQueue() methods of time complexity O(1) The implementation should be optimum and clean.
public class OverflowQueue {
    private int[] queue;
    private int front = -1, rear = -1;

    public OverflowQueue(int size) {
        queue = new int[size];
    }

    public void enQueue(int n){
        rear = getNextIndex(rear);
        queue[rear] = n;
         if (rear == front || front == -1){
          front = getNextIndex(front);
        }

    }

    private int getNextIndex(int index){
        if (index == queue.length - 1 ){
            index = 0;
        } else {
            index ++ ;
        }
        return index;
    }

    public int deQueue(){
        if (front == -1 ){
           throw new NullPointerException("deQueue operation is called on empty queue.");
        }
        int elem = queue[front];
        if (front == rear ){
            front = -1;
            rear = -1;
        } else {
            front = getNextIndex(front);
        }
        return elem;
    }

    public static void main(String[] args) {
        OverflowQueue q = new OverflowQueue(5);
        q.enQueue(1);q.enQueue(2);q.enQueue(3);
        q.enQueue(4);q.enQueue(5);q.enQueue(6);
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
        System.out.println(q.deQueue());
    }
}

Please leave comments.

Saturday, September 28, 2013

[Amazon interview question] A character array of arbitary length with 'R', 'B', 'W' is needed to be sorted in that order.

There is char array of n length. Array can have elements only from of any order R, B, W. You need to sort array so that order should R,B,W i.e. all R will come first followed by B and then W.
Constraints: Time complexity is O(n) and space complexity should be O(1)
Assumption: You can assume one swap method is given with signature swap(int index1, int index2) that swaps number in unit time.
method given to implement: public sort(char[]array);
    public static void sort(char[] arr){
        int rIndex = 0, wIndex = arr.length -1;
        for (int i = 0 ; i <= wIndex; ){
            if ( arr[i] == 'R' ){
                swap(arr, i , rIndex ++ );
                i ++ ;
            } else if (arr[i] == 'W' ){
                swap(arr, i , wIndex -- );
            }else{
             i ++;
            }
        }
    }
    //a dummy implementation just for testing sake
    private static void swap(char[] arr, int index1, int index2){
        char temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }

Please leave your comments and suggestions that improves the logic above.

[Amazon interview Question] Calculate the weight of of binary tree path from root to leaf node in such a way that it would be equal to N

You have a binary tree (no BST etc, a simple binary tree). A number N will be given to you, you have to find out, whether path from root node to leaf node exists in such a way so that sum of all node's data in that path is equal to N. For example for given binary tree
           1

     2              3

 4       5      6           7

      3                           8
                             9


If value of N is 11 then path - 1 2 5 3 which is root node to left node 3 sums up to 11 hence for this tree method should return true.
Constraints: Time complexity is O(n) and space complexity should be O(1)
Method to implement : public boolean isSumTree(Node root, int N);
static class Node{ int data; Node left; Node right; } public static boolean isSumTree(Node root, int N){ if (root.left == null && root.right == null ){ return root.data == N; } boolean leftResult = root.left != null && isSumTree(root.left, N - root.data ); boolean rightResult = root.right != null && isSumTree(root.right, N - root.data ); return leftResult || rightResult; }

Please leave your valuable comments to improve my answer.

Sunday, September 22, 2013

Shortest Path between 2 points


Write a java program to find the shortest path from point A to point B in a maze.
Maze:
- The maze is represented by a 2-dimensional array of 1's and 0's
- 0 represent that user can traverse a path
- 1 represents that user cannot traverse path
- User can move only horizontal and vertical

Input: PointA, PointB, Maze Details
Output: Shortest Path

Sample Input:
PointA = 0,1
PointB = 2,3
Number of Rows in Maze = 5
Number of Columns in Maze = 5
Maze Co-ordinates = 1 0 1 1 1
1 0 1 0 0
1 0 0 0 1
1 0 1 1 1
0 1 1 1 1


1
0
1
1
1
1
0
1
0
0
1
0
0
0
1
1
0
1
1
1
0
1
1
1
1
Sample Output (Shortest Path):
1,0; 1,1; 1,2; 2,2; 2,3



Here is the program for the above. I took approach of breadth first search. Here is the algorithm for this. 
1. create a queue and push source point 
2. pop up element from queue and find out all of it's unvisited neighbors. 
3. if destination point found then back track them to the source and exit else mark the popped element visited and go to step 3. 
4. exit the queue if queue doesn't have any element. In this case destination can not be found given source. 

Here is the code. Point class that will represent each point within maze.
package com.adnan.shortestPath;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 4:49 PM
 */
public class Point {

    private int x;
    private int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Point){
            Point point = (Point) o;
            if ( point.getY() == this.getY()
                    && point.getX() == this.getX()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

Shortest path calculator service, this has main business logic to find out shortest path.
package com.adnan.shortestPath;

import java.util.*;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 4:36 PM
 */
public class ShortestPathCalculator {

    private static final ShortestPathCalculator calculator
 = new ShortestPathCalculator();
    private ShortestPathCalculator(){}
    private static final int PATH = 0;

    public static ShortestPathCalculator getInstance(){
        return calculator;
    }

    private class WeightedPoint {
        private Point point;
        private WeightedPoint parentPoint;
        private WeightedPoint(Point point, 
WeightedPoint parentPoint) {
            this.point = point;
            this.parentPoint = parentPoint;
        }
    }

    public Stack getShortestPath(int[][] maze, Point pointA, 
Point pointB){
        Queue queue = new LinkedList<>();
        queue.add(new WeightedPoint(pointA, null));

        WeightedPoint pointBWeightPoint = null;
        Set pointTransversed = new HashSet<>();
        pointTransversed.add(pointA);
        while ( ! queue.isEmpty() )  {
            WeightedPoint curr = queue.poll();
            Set neighbors = 
getAllNeighborsNotAlreadyTraversed(maze, curr, pointTransversed);
            pointTransversed.addAll(neighbors);
            if (neighbors.contains(pointB)){
                pointBWeightPoint = 
new WeightedPoint(pointB, curr);
                break;
            }
          queue.addAll(covertToWeightedPoint(neighbors, curr));
        }
        throwExceptionIfPathNotFound(pointBWeightPoint);
        return prepareResultStack(pointBWeightPoint);
    }

  private Collection covertToWeightedPoint
(Collection neighbors,WeightedPoint current) {
        Collection collection = new HashSet<>();
        for (Point point : neighbors ){
            collection.add(new WeightedPoint(point, current));
        }
        return collection;
    }

    private void throwExceptionIfPathNotFound
(WeightedPoint pointBWeightPoint) {
        if ( pointBWeightPoint == null ){
            throw new NoPathFoundException();
        }
    }

    private Stack prepareResultStack
(WeightedPoint pointBWeightPoint) {
        Stack stack =  new Stack<>();
        while (pointBWeightPoint != null ){
            stack.push(pointBWeightPoint.point);
            pointBWeightPoint = pointBWeightPoint.parentPoint;
        }
        return stack;
    }

   private Set getAllNeighborsNotAlreadyTraversed(int[][] maze, 
WeightedPoint currWeightedPoint, Set pointTraversed) {
        Set neighbors = new HashSet<>();
        Point currPoint = currWeightedPoint.point;
        Point upperPoint = getUpperPoint(maze, currPoint);
        updateNeighborIfPointNotNullAndNotPresentInSet(neighbors,
 upperPoint, pointTraversed);
        Point lowerPoint = getLowerPoint(maze, currPoint);
        updateNeighborIfPointNotNullAndNotPresentInSet(neighbors,
 lowerPoint, pointTraversed);
        Point rightPoint = getRightPoint(maze, currPoint);
        updateNeighborIfPointNotNullAndNotPresentInSet(neighbors,
 rightPoint, pointTraversed);
        Point leftPoint = getLeftPoint(maze, currPoint);
        updateNeighborIfPointNotNullAndNotPresentInSet(neighbors,
 leftPoint, pointTraversed);
        return neighbors;
    }

    private void updateNeighborIfPointNotNullAndNotPresentInSet(
Set neighbors,Point point, Set pointTraversed) {
        if (point != null && ! pointTraversed.contains(point) ){
            neighbors.add(point);
        }
    }

    private Point getLeftPoint(int[][] maze, Point currPoint) {
        int yMinus1 = currPoint.getY() - 1;
        if (yMinus1 >= 0 
&& maze[currPoint.getX()][yMinus1] == PATH  ){
            return new Point(currPoint.getX(), yMinus1);
        }
        return null;
    }

    private Point getRightPoint(int[][] maze, Point currPoint) {
        int totalColumns = maze[0].length;
        int yPlus1 = currPoint.getY() + 1;
        if (yPlus1 < totalColumns 
&& maze[currPoint.getX()][yPlus1] == PATH  ){
            return new Point(currPoint.getX(), yPlus1);
        }
        return null;
    }

    private Point getLowerPoint(int[][] maze, Point currPoint) {
        int xMinus1 = currPoint.getX() - 1;
        if (xMinus1 >= 0  
&& maze[xMinus1][currPoint.getY()] == PATH ){
            return new Point(xMinus1, currPoint.getY());
        }
        return null;
    }

    private Point getUpperPoint(int[][] maze, Point currPoint) {
        int totalRows = maze.length;
        int xPlus1 = currPoint.getX() + 1;
        if (xPlus1 < totalRows 
&& maze[xPlus1][currPoint.getY()] == PATH ){
            return new Point(xPlus1, currPoint.getY());
        }
        return null;
    }

}
A runtime exception to be thrown when path not found
package com.adnan.shortestPath;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/22/13
 * Time  : 12:13 AM
 */
public class NoPathFoundException extends RuntimeException {

}
And how can I forget to write test case since I follow test driven development. I could have pasted test code first ;-)
package com.adnan.shortestPath;

import org.junit.Test;

import java.util.Stack;

import static org.junit.Assert.assertTrue;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 4:53 PM
 */
public class ShortestPathCalculatorTest {

    private ShortestPathCalculator calculator = 
ShortestPathCalculator.getInstance();

    @Test
    public void test_shortestPath() throws Exception {
        int[][] maze = {
                {1, 0, 1, 1, 1 },

                {1, 0, 1, 0, 0 },

                {1, 0, 0, 0, 1 },

                {1, 0, 1, 1, 1 },

                {0, 1, 1, 1, 1 }
        };
        Stack stack = 
calculator.getShortestPath(maze, new Point(0, 1) , new Point(2, 3));
        assertTrue(stack.size() == 5);
        Point point = stack.pop();
        assertTrue(point.getX() == 0 &&point.getY()==1);//0, 1
        point = stack.pop();
        assertTrue(point.getX() == 1 &&point.getY()==1);//1,1
        point = stack.pop();
        assertTrue(point.getX() == 2 &&point.getY()==1);//2,1
        point = stack.pop();
        assertTrue(point.getX() == 2 &&point.getY()==2);//2,2
        point = stack.pop();
        assertTrue(point.getX() == 2 &&point.getY()==3);//2,3
    }

    @Test(expected = NoPathFoundException.class)
    public void 
test_shortestPath_whenSourceDoesNotMatchWithDestination() 
throws Exception {
        int[][] maze = {
                {1, 0, 1, 1, 1 },

                {1, 0, 1, 0, 0 },

                {1, 0, 0, 0, 1 },

                {1, 0, 1, 1, 1 },

                {0, 1, 1, 1, 1 }
        };
      calculator.getShortestPath(maze, new Point(0, 1) , 
new Point(0, 4));

    }
}

Please give your precious comments and suggestions. I would be more than happy to have them.

Saturday, September 21, 2013

Reverse linked list without using any extra space.

Linked list reversal I found very common question asked in many companies. One of the easy way to implement this is, using stack and traversing whole singly linked list and dumping into stack. One list linked list finishes, start poping up and preparing new linked list. Problem gets interesting when we are not suppose to use any extra space like stack or another linked list. Here is the implementation of such. I am using java to implement this and approach is test driven development hence test cases are also attached.
The Node class that represent single node -
package com.adnan.linkedlist;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 12:02 PM
 */
public class Node {

    public Node(int value, Node node){
        this.value = value;
        this.node = node;
    }
    private int value;
    private Node node;

    public int getValue() {
        return value;
    }

    public Node getNode() {
        return node;
    }

    public void setNode(Node node){
        this.node = node;
    }
}


Service class that takes start node as input and reserve it without using extra space.
package com.adnan.linkedlist;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 11:54 AM
 */
public class SinglyLinkedListReversal {

    private static final SinglyLinkedListReversal service 
= new SinglyLinkedListReversal();
    public static SinglyLinkedListReversal getService(){
        return service;
    }



    public Node reverse(Node start){
        if (hasOnlyNodeInLinkedList(start)){
            return start;
        }
        Node firstNode, secondNode, thirdNode;
        firstNode = start;
        secondNode = firstNode.getNode();
        while (secondNode != null ){
            thirdNode = secondNode.getNode();
            secondNode.setNode(firstNode);
            firstNode = secondNode;
            secondNode = thirdNode;
        }
        start.setNode(null);
        return firstNode;
    }

    private boolean hasOnlyNodeInLinkedList(Node start) {
        return start.getNode() == null;
    }


}


  


Another logic of reversal could be a recursive approach. So replace reverse method of above class by below and it should return result in recursive manner.
 public Node reverseRecursively(Node start){
     if (start == null ){
         return null;
     }
     Node lastNode;
     if (start.getNode() == null ){
       lastNode = start;
     }else {
         lastNode = reverseRecursively(start.getNode());
         start.getNode().setNode(start);
         start.setNode(null);
     }
      return lastNode;
   }
  


And The test case that covers above scenario. Please note that you require junit jars. I am using testng.jar; you can use any whatever pleases you..
package com.adnan.linkedlist;

import org.testng.annotations.Test;

import static org.testng.AssertJUnit.assertTrue;

/**
 * User  : Adnan
 * Email : sendtoadnan@gmail.com
 * Date  : 9/21/13
 * Time  : 12:11 PM
 */
public class SinglyLinkedListReversalTest {

    private SinglyLinkedListReversal reversalService = 
SinglyLinkedListReversal.getService();

    @Test
    public void test_reverseSingleElement() throws Exception {
        Node node = new Node(1, null);
        reversalService.reverse(node);
        assertTrue(node.getNode() == null);
        assertTrue(node.getValue() == 1);
    }


    //original - Node1(1) -> Node2(2) -> Node3(3)
    //reverse - Node3(3) -> Node2(2) -> Node1(1)
    @Test
    public void test_reverseThreeElement() throws Exception {
        Node node3 = new Node(3, null);
        Node node2 = new Node(2, node3);
        Node start = new Node(1, node2);


        start = reversalService.reverse(start);
        Node test = start;
        for (int i = 3; i >=1 ; i -- ){
          assertTrue(test.getValue() == i);
            test = test.getNode();
        }


    }

    @Test
    public void test_reverseFourElement() throws Exception {
        Node node4 = new Node(4, null);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node start = new Node(1, node2);


        start = reversalService.reverse(start);
        Node test = start;
        for (int i = 4; i >=1 ; i -- ){
            assertTrue(test.getValue() == i);
            test = test.getNode();
        }
    }

        @Test
        public void test_reverse10Element() throws Exception {
            Node node10 = new Node(10, null);
            Node node9 = new Node(9, node10);
            Node node8 = new Node(8, node9);
            Node node7 = new Node(7, node8);
            Node node6 = new Node(6, node7);
            Node node5 = new Node(5, node6);
            Node node4 = new Node(4, node5);
            Node node3 = new Node(3, node4);
            Node node2 = new Node(2, node3);
            Node start = new Node(1, node2);


            start = reversalService.reverse(start);
            Node test = start;
            for (int i = 10; i >=1 ; i -- ){
                assertTrue(test.getValue() == i);
                test = test.getNode();
            }


    }

    @Test
    public void test_reverseTwoElement() throws Exception {
        Node node2 = new Node(2, null);
        Node start = new Node(1, node2);


        start = reversalService.reverse(start);
        Node test = start;
        for (int i = 2; i >=1 ; i -- ){
            assertTrue(test.getValue() == i);
            test = test.getNode();
        }


    }
}