WebSockets in HTML5 and JBoss

Hi all, its a long time i put my pen in the blog, these days got little busy with my little kid, however i took little time to write about the next-generation client(browser) server communication using WebSockets. In the advent of HTML5 technology all the modern browser are capable of talking to latest servers using WebSockets API.

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server or an Application Server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.

All the latest Web Servers and Application Servers has got implementation of WebSockets API as this is been included as part of JavaEE stack.

Let us look at the simple application which i created using JBoss Wildfly 8.1 and Maven

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.websockets</groupId>
	<artifactId>WebSocketsExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>WebSocketsExample</name>
	<description>WebSocketsExample</description>

	<dependencies>
		<dependency>
			<groupId>org.jboss.spec.javax.websocket</groupId>
			<artifactId>jboss-websocket-api_1.0_spec</artifactId>
			<version>1.0.0.Final</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

once all the required and dependent jars got downloaded, let us code with our java server side handler class.
WebSocketHandler.java

/**
 * 
 */
package com.spark.websockets.handler;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author Sony
 *
 */
@ServerEndpoint("/hello")
public class WebSocketHandler {

	@OnMessage
	public String onMessage(String message){
		System.out.println("-------------------------> Received : "+message);
		return "Response from Server ";
	}
	
	@OnOpen
	public void onOpenConnection(Session session){
		System.out.println("---------------------> Web Socket Connection Opened : "+session.getId());
	}
	
	@OnClose
	public void onCloseConnection(CloseReason closeReason){
		System.out.println("--------------> Close Reason : "+closeReason.getReasonPhrase());
	}

}

Once we are done with our java handler, let us start with our html and java script as below.
index.html

<html>
    <head>
        <title>HelloWorld Web sockets</title>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
        
        <script language="javascript" type="text/javascript">
            var wsUri = getRootUri() + "/WebSocketsExample/hello";
            function getRootUri() {
                return "ws://" + (document.location.hostname == "" ? "localhost" : document.location.hostname) + ":" +
                        (document.location.port == "" ? "8080" : document.location.port);
            }
            function init() {
                output = document.getElementById("output");
            }
            function send_message() {
                websocket = new WebSocket(wsUri);
                websocket.onopen = function(evt) {
                    onOpen(evt)
                };
                websocket.onmessage = function(evt) {
                    onMessage(evt)
                };
                websocket.onerror = function(evt) {
                    onError(evt)
                };
                websocket.onclose = function (evt) {
                	cloaseConnection();
                };
            }
            function onOpen(evt) {
                writeToScreen("Connected to Endpoint!");
                doSend(textID.value);
            }
            function onMessage(evt) {
                writeToScreen("Message Received: " + evt.data);
            }
            function onError(evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            }
            function doSend(message) {
                writeToScreen("Message Sent: " + message);
                websocket.send(message);
            }
            function cloaseConnection(){
            	writeToScreen("Closing Connection"+message);
            	websocket.close("closing socket !")
            }
            function writeToScreen(message) {
                var pre = document.createElement("p");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                output.appendChild(pre);
            }
            
            window.addEventListener("load", init, false);
        </script>
        <h2 style="text-align: center;">Hello World WebSocket Client</h2>
        <br>
        <div style="text-align: center;">
            <form action="">
                <input onclick="send_message()" value="Send" type="button">
                <input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
                <input onclick="closeConnection()" value="Close Connection" type="button">
            </form>
        </div>
        <div id="output"></div>
</body>
</html>

finally we are done with our coding part and ready for deployment, please deploy the war file in JBoss Wildfly 8.1 and hit http://localhost:8080/WebSocketsExample/ in the browser and start playing with web sockets.

Happy WebSockets, Happy Coding 🙂

Basic Concepts of Node.js (Server Side JavaScript)

As Wikipedia states: “Node.js is a packaged compilation of Google’s V8 JavaScript engine, the libuv platform abstraction layer, and a core library, which is itself primarily written in JavaScript.” Beyond that, it’s worth noting that Ryan Dahl, the creator of Node.js, was aiming to create real-time websites with push capability, “inspired by applications like Gmail”. In Node.js, he gave developers a tool for working in the non-blocking, event-driven I/O paradigm.

In this post i will demonstrate some of the basic concepts of Node.js using which you can start server side coding using javascript.this tutorial assume you have a basic knowledge of javascript. please install node.js in your system prior going through the code snippets below. once you have the environment setup save the code in “[Name].js” and to run it open the command prompt and type the following command
node [Name].js as simple as that.

The below code demonstrate how to open a file from the file system and displaying its statistics. also the below code tells the given file is a file or not.

var fp = require("fs");

/**
 * getting file statistics. 
 */
fp.stat('NodeTestFile.txt',function(error,stats){
	if(error){
		throw error;
	}else{
		console.log('NodeTestFile.txt is a file:'+stats.isFile());
		console.log(stats);
	}
});

now its time for us to read a file’s content in bytes and display it in console.

/**
 * reading file content in bytes.
 */
fp.open('NodeTestFile.txt','r',function(err,fd){
	if(err){
		throw err;
	}else{
		var readBuffer = new Buffer(1024);
		bufferOffset = 0;
		bufferLength = readBuffer.length;
		filePosition = 0;
		fp.read(fd,readBuffer,bufferOffset,bufferLength,filePosition,function read(err,readBytes){
			console.log('just read ' + readBytes + ' bytes');
			if (readBytes > 0) {
			console.log(readBytes);
			}
		});
	}
});

Now if we need to read the content from file and display it con console(not as bytes), below is the code

/**
 *	reading file content
**/
fp.readFile('NodeTestFile.txt',{encoding: 'utf-8'},function read(err,data){
	if(err){
		throw err;
	}else{
		console.log(data);
	}
});

as we are done with reading of file, lets us take a chance to write back to the file, please follow the below code to write the content to the file

/**
* Writing the content back to file
**/

fp.open('NodeTestFile.txt','a',function opened(err,fd){
	if(err){
		throw err;
	}else{
		var writeBuffer = new Buffer('content from Buffer'),
		bufferPosition = 0,
		bufferLength = writeBuffer.length,filePosition = null;
		fp.write(fd,writeBuffer,bufferPosition,bufferLength,filePosition,function wrote(err,data){
			if(err){
				throw err;
			}else{
				console.log("content written to file");
			}
		});
	}
});

so here ends our concepts on file handling, now ill show how to create simple http server using node.js.

/**
 * 
 */
var http = require('http');

http.createServer(function handler(req, res) {
		
	res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end("Hello Node JS\n");
    
}).listen(1337, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1337/');

once the above code is saved in file please run from command prompt and open the browser and hit the url you will be seeing “Hello Node JS” in the browser. there is little to take about the code above as you see the very first statement “require(‘http’)” is called the module loading by node.

so far we have covered node.js interacting with file system and http requests by creating http server, now its time for us to make node.js to interact with database.

/**
 * New node file, with database connectivity and handling
 */
var db = require('mysql');
var connection = db.createConnection({
	host : "localhost",
	user : "username",
	password : "password"
});

connection.connect(function(error, result) {
	if (error) {
		console.log('Connection Error: ' + error.message);
		return;
	}
	console.log('Connected to MySQL Database');
	clientReady(connection);
});

clientReady = function(connection) {
	connection.query("use test", function(error, result) {
		if (error) {
			console.log('Connection Error: ' + error.message);
			return;
		}
		console.log('Ready to fetch the results...');
		fetchResults(connection);
	});
};

fetchResults = function(connection) {

	var strQuery = "select * from country";
	connection.query(strQuery, function(err, rows) {
		if (err) {
			throw err;
		} else {
			console.log(rows);
		}
	});
};

thats all folks on the basics of node.js.
Happy coding Node.js 🙂

AngularJS a modern JavaScript

Hi all, i was doing some weekend research on the modern JavaScript frameworks and i felt there are lot many awesome features in the latest JavaScript frameworks. so now i wanted to start a series of articles which describe Angular in its vanilla flavour. Any one with basic Javascript, HTML background can start working in AngularJS without any hassle.

Let us dive into the world of AngularJS and see what it is.
AngularJS-icon

AngularJS is an open-source JavaScript framework, developed by Google . Its main aim is to incorporate browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

google maintain Angular CDN at:

<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="ISO-8859-1">
<title>Angular JS Tutorial</title>
<script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
	 Write some text in textbox:
    <input type="text" ng-model="sometext" />
 
    <h1>Hello {{ sometext }}</h1>
</body>
</html>

please run this and u will notice that view and model are bound together, when ever u change the model value, the view gets automatically changes.

here is the online demo: Demo

Happy AngularJS 🙂

JavaScript Templating

Hi all as said in my previous post here i am to explain you how to write the java script templating and render UI with content dynamically.
sincere thanks to John Resig for his micro templating.
well the template engine is simple and it converts the dynamic scripts into pure javascript at runtime and the code is as follows. Please add the below script to a file and name it as “templating.js”

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function() {

    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ? cache[str] = cache[str]
                || tmpl(document.getElementById(str).innerHTML) :
                // Generate a reusable function that will serve as a template
                // generator (and which will be cached).
                new Function("obj",
                "var p=[],print=function(){p.push.apply(p,arguments);};"
                +
                // Introduce the data as local variables using with(){}
                "with(obj){p.push('"
                +
                // Convert the template into pure JavaScript
                str.replace(/[\r\t\n]/g, " ").split("<%").join("\t")
                .replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(
                /\t=(.*?)%>/g, "',$1,'").split("\t")
                .join("');").split("%>").join("p.push('")
                .split("\r").join("\\'")
                + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();

After this my index page looks like this:

<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
        <script type="text/javascript" charset="utf-8"
        src="js/templating.js"></script>
        
    </head>
    <body>
        <div id="TempalateHolder"></div>
	<div id="PageHolder"></div>
    </body>
</html>

In the “TemplateHolder” div all the templates gets loaded and dymanically the content gets loaded in “PageHolder” div.
and my templates look like this, and name the file as templates.html

<script type="text/html" id="displayDates_tmpl">
    
    <% for(i=0;i<10;i++){ %>
        <h4>Sample <%=i%> .</h4>
    <% } %>
</script>

now inorder to render this template in the page please add the below script to the templating.js file as follows.

var ObjectManager = {
    Version: '1.0',
    init: function() {
        $(document).ready(function() {
            try { // fix IE background image flicker (credit:
                // www.mister-pixel.com)

                $(document).ready(function() {
                    // Load Templates here to store all template in
                    // TempalateHolder Div
                    $("#TempalateHolder").load("Templates.html", function() {
                        ObjectManager.ShowDatesPage();

                    });

                });

            } catch (err) {
                console.log(err);
            }
        });
    },
    ShowDatesPage: function() {
        this.ShowPage("displayDates", "");
    },
    ShowPage: function(PageName, DataObject) {
        var TemplateContent = tmpl(PageName + "_tmpl", DataObject);
        $("#PageHolder").html(TemplateContent);
    }
};

ObjectManager.init();

Happy Coding 🙂

CustomDate.js open-source JavaScript Date library

It’s a long time i made a post in the blog,I was completely busy working on a project where i should render the dynamic data into HTML and the data is in JSON format.. I started using JavaScript Templating (from JavaScript Micro-Templating) ref: JavaScript Micro-Templating.I will post a topic on JavaScript Templating in my next post, Here i am going to give you a JavaScript which i developed for my project. This script contain all useful functions of Date.

I made this script Open Source(GPL v3), please copy the below script in a file and name it as “CustomDate-1.0.js” and include in your HTML document as shown “<script type=”text/javascript” src=”js/CustomDate-1.0.js” >” and start using all the functions of the file.Netbeans > 7.x provide the API Assistance of the script once included into the project.

/**
 * @author Mantha Pavan Kumar
 * @version 1.0
 * 
 * @description 
 * Copyright (C) 2013 - 2014 SparkSoftware
 * 
 * This script is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 *
 */
var CustomDateObject = {
    /**
     * @returns {Date}
     * @description
     * Returns the current date as Date Object.
     */
    today: function() {
        return new Date();
    },
    /**
     * 
     * @returns {String}
     * Returns the current date as String date in the format 'mm/dd/yyyy'.
     */
    getSysDate: function() {
        var d = new Date();
        var strDate = (d.getMonth() + 1) + "/" + d.getDate() + "/"
                + d.getFullYear();
        // alert(strDate);
        return strDate;
    },
    /**
     * 
     * @param {type} date 
     * date parameter can be a date object or mm/dd/yyyy format.
     * @returns {String} The day of the date passed
     */
    getDay: function(date) {
        var d_names = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
        var l_date = new Date(date);
        return d_names[l_date.getDay()];
    },
    /**
     * 
     * @param {type} date
     * date parameter can be a date object or mm/dd/yyyy format.
     * @returns {String} The Month of the date passed
     */
    getMonth: function(date) {
        var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
        var l_date = new Date(date);
        return m_names[l_date.getMonth()];
    },
    /**
     * @description function under development.
     * @returns {undefined}
     */
    getDayNumberFromName: function() {

    },
    /**
     * 
     * @param {String} monthName
     * @description pass the month name as 'jan' | 'JAN' | 'january' | 'JANUARY'
     * @returns {Number}, The month number.
     */
    getMonthNumberFromName: function(monthName) {
        var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
        var month = "";
        if (monthName === "jan" || monthName === "JAN" || monthName === "january" || monthName === "JANUARY") {
            month = "Jan";
        } else if (monthName === "feb" || monthName === "FEB" || monthName === "february" || monthName === "FEBRUARY") {
            month = "Feb";
        } else if (monthName === "mar" || monthName === "MAR" || monthName === "MARCH" || monthName === "march") {
            month = "Mar";
        } else if (monthName === "apr" || monthName === "APR" || monthName === "april" || monthName === "APRIL") {
            month = "Apr";
        } else if (monthName === "may" || monthName === "MAY" || monthName === "May") {
            month = "May";
        } else if (monthName === "jun" || monthName === "JUN" || monthName === "june" || monthName === "JUNE") {
            month = "Jun";
        } else if (monthName === "jul" || monthName === "JUL" || monthName === "july" || monthName === "JULY") {
            month = "Jul";
        } else if (monthName === "aug" || monthName === "AUG" || monthName === "august" || monthName === "AUGUST") {
            month = "Aug";
        } else if (monthName === "sep" || monthName === "SEP" || monthName === "september" || monthName === "SEPTEMBER") {
            month = "Sep";
        } else if (monthName === "oct" || monthName === "OCT" || monthName === "october" || monthName === "OCTOBER") {
            month = "Oct";
        } else if (monthName === "nov" || monthName === "NOV" || monthName === "november" || monthName === "NOVEMBER") {
            month = "Nov";
        } else if (monthName === "dec" || monthName === "DEC" || monthName === "december" || monthName === "DECEMBER") {
            month = "Dec";
        }

        var monthNumber = m_names.indexOf(month);
        return monthNumber + 1;
    },
    /**
     * 
     * @param {number} year
     * @param {number} month
     * @returns {number} no of days in month
     * @description Pass the month and year in number format
     */
    getDaysInMonth: function(year, month) {
        return new Date(year, month, 0).getDate();
    },
    /**
     * 
     * @param {type} date, format{Date Object | 'mm/dd/yyyy'}
     * @returns {Array} of Start and End date of the week with respect to parameter passed
     * If date is null the function consider sysdate.
     */
    getStartandEndDates: function(date) {
        start = 0;
        if (date === undefined) {
            var today = new Date();
            var day = today.getDay() - start;
            var date = today.getDate() - day;

            var StartDate = new Date(today.setDate(date + 1));
            var EndDate = new Date(today.setDate(date + 5));
            var startingDate = (new Date(StartDate).getMonth() + 1) + "/" + new Date(StartDate).getDate() + "/" + new Date(StartDate).getFullYear();
            var endingDate = (new Date(EndDate).getMonth() + 1) + "/" + new Date(EndDate).getDate() + "/" + new Date(EndDate).getFullYear();
            return [startingDate, endingDate];
        } else {
            var today = new Date(date);
            var day = today.getDay() - start;
            var date = today.getDate() - day;

            var StartDate = new Date(today.setDate(date + 1));
            var EndDate = new Date(today.setDate(date + 5));
            var startingDate = (new Date(StartDate).getMonth() + 1) + "/" + new Date(StartDate).getDate() + "/" + new Date(StartDate).getFullYear();
            var endingDate = (new Date(EndDate).getMonth() + 1) + "/" + new Date(EndDate).getDate() + "/" + new Date(EndDate).getFullYear();
            return [startingDate, endingDate];
        }

    },
    /**
     * 
     * @param {type} date1 format: Date object | 'mm/dd/yyyy'
     * @param {type} date2 format: Date object | 'mm/dd/yyyy'
     * @returns {Number}
     * @description this function returns 1 if d1 > d2,-1 if d1 < d2
     * else returns 0 if d1 = d2
     */
    compareDates: function(date1, date2) {
        var d1 = new Date(date1).getTime();
        var d2 = new Date(date2).getTime();
        var result = 0;
        if (d1 < d2) {
            result = -1;
        } else if (d1 > d2) {
            result = 1;
        } else {
            result = 0;
        }
        return result;
    },
    /**
     * 
     * @param {type} date1 format: Date object | 'mm/dd/yyyy'
     * @param {type} date2 format: Date object | 'mm/dd/yyyy'
     * @returns {Number}
     * @description this function returns 0 if d1 = d2
     */
    isEqual: function(date1, date2) {
        var d1 = new Date(date1).getTime();
        var d2 = new Date(date2).getTime();
        var result = false;
        if (d1 === d2) {
            result = true;
        }
        return result;
    },
    /**
     * 
     * @param {number}
     * @returns {boolean} true | false
     * @description this function returns true | false
     */
    isLeapYear: function(year) {
        var days = new Date(year, 2, 0).getDate();
        if (days === 29) {
            return true;
        } else {
            return false;
        }
    },
    /**
     * 
     * @param {type} date
     * @returns {Date}
     * @description function takes date object or 'mm/dd/yyyy' as parameter and returns the next date of that.
     */
    nextDate: function(date) {
        var nextDate;
        nextDate = new Date(new Date(date).getFullYear(), new Date(date).getMonth(), new Date(date).getDate() + 1);
        if (date instanceof Date) {
            return nextDate;
        } else {
            return (new Date(nextDate).getMonth() + 1) + "/" + new Date(nextDate).getDate() + "/" + new Date(nextDate).getFullYear();
        }
    },
    /**
     * 
     * @param {type} date
     * @returns {Date}
     * @description function takes date object or 'mm/dd/yyyy' as parameter and returns the previous date of that.
     */
    previousDate: function(date) {
        var previousDate;
        previousDate = new Date(new Date(date).getFullYear(), new Date(date).getMonth(), new Date(date).getDate() - 1);
        if (date instanceof Date) {
            return previousDate;
        } else {
            return (new Date(previousDate).getMonth() + 1) + "/" + new Date(previousDate).getDate() + "/" + new Date(previousDate).getFullYear();
        }
    },
    /**
     * 
     * @param {type} pattern
     * @returns {undefined}
     * Sample : {'days':5,'months':2,'years':6,'date':new Date()} | {'days':5,'months':2,'years':6,'date':"mm/dd/yyyy"}
     */
    add: function(pattern) {

        days = pattern.days;
        months = pattern.months;
        years = pattern.years;
        date = pattern.date;

        var modifiedDate;

        if (date === undefined || date == "" || date == null) {
            alert("date is mandatory !");
        } else {
            if (days === undefined || months === undefined || years === undefined) {
                alert("nothing to add for given date !")
            } else {
                var temp_date = new Date(date);
                var temp_year = temp_date.getFullYear() + years;

                var yearChange = new Date(temp_year, temp_date.getMonth(), temp_date.getDate());
                var yearChange_monthChange = new Date(new Date(yearChange).getFullYear(), new Date(yearChange).getMonth() + months, new Date(yearChange).getDate());
                modifiedDate = new Date(new Date(yearChange_monthChange).getFullYear(), new Date(yearChange_monthChange).getMonth(), new Date(yearChange_monthChange).getDate() + days);

                return modifiedDate;
            }
        }
    },
    /**
     * 
     * @param {type} date
     * @param {type} noOfDays
     * @returns {Date}
     */
    addDays: function(date, noOfDays) {
        return new Date(new Date(date).getFullYear(), new Date().getMonth(), new Date(date).getDate() + noOfDays);
    },
    /**
     * 
     * @param {type} date
     * @param {type} noOfMonths
     * @returns {Date}
     */
    addMonths: function(date, noOfMonths) {
        return new Date(new Date(date).getFullYear(), new Date().getMonth() + noOfMonths, new Date(date).getDate());
    },
    /**
     * 
     * @param {type} date
     * @param {type} noOfyears
     * @returns {Date}
     */
    addYears: function(date, noOfyears) {
        return new Date(new Date(date).getFullYear() + noOfyears, new Date().getMonth(), new Date(date).getDate());
    },
    /**
     * 
     * @param {type} date | can be of a Date Object or 'mm/dd/yy' format
     * @returns {number} first date of the month
     */
    getFirstDayofMonth: function(date) {
        var x = new Date(date);
        var year = x.getFullYear();
        var month = x.getMonth();
        var day = x.getDate();

        var monthFirstDay = new Date(year, month, 1);
        return monthFirstDay;
    },
    /**
     * 
     * @param {type} date | can be of a Date Object or 'mm/dd/yy' format
     * @returns {number} last date of the month
     */
    getLastDayOfMonth: function(date) {

        var x = new Date(date);
        var year = x.getFullYear();
        var month = x.getMonth();
        var day = x.getDate();

        var monthLastDay = new Date(year + (month == 12 ? 1 : 0), (month == 1 ? 12 : month + 1), 0);
        return monthLastDay;
    }
};

Suggestions are welcome on the API.
soon source code will be available on Github …

Wait for my next post on JavaScript Templating
Happy Coding 🙂