Configuring Multi Node Cassandra Cluster on Windows Machine.

Hi All, These days we hear a lot of buzz in and around the IT industry regarding the BigData and NoSql. Here in this post i wanted to show you how to setup multi node cluster on single machine(Windows).

In Windows machine please navigate to “C:\Windows\System32\drivers\etc” and edit the “hosts.etc” file and add the following content as below.

#cassandra cluster nodes
127.0.0.1 127.0.0.2 
127.0.0.1 127.0.0.3 
127.0.0.1 127.0.0.4 
127.0.0.1 127.0.0.5 
127.0.0.1 127.0.0.6 

once we add the cassandra nodes to hosts.etc file, please download the latest version of Apache Cassandra from the following sitedownload cassandra once downloaded please extract that to one of the folders as “appache-cassandra-2.1.6-node1″(similarly, extract 3 different copies of the same zip file to 3 different folders).

once you are ready with Cassandra folders now its time to modify the cassandra config file located in /conf/cassandra.yaml file.
please edit the following values in the config file

cluster_name: 'DemoCluster'

Provide the seed nodes for each cassandra.yaml file as 127.0.0.1 and 127.0.0.2 etc.;

seed_provider: # Addresses of hosts that are deemed contact points. 
# Cassandra nodes use this list of hosts to find each other and learn 
# the topology of the ring. You must change this if you are running 
# multiple nodes! - class_name: org.apache.cassandra.locator.SimpleSeedProvider parameters: 
# seeds is actually a comma-delimited list of addresses. 
# Ex: "<ip1>,<ip2>,<ip3>" 
- seeds: "127.0.0.1,127.0.0.2"

Note: You need to ensure that the following values are changed for each node
directories where Cassandra should store data on disk

data_file_directories: - /training/node1/var/lib/cassandra/data 

# commit log 
commitlog_directory: /training/node1/var/lib/cassandra/commitlog 

# saved caches 
saved_caches_directory: /training/node1/var/lib/cassandra/saved_caches

make sure you also change the follwing listen address and rpc address for every node of cassandra.

listen_address: 127.0.0.1 
rpc_address: 127.0.0.1

finally your configuration should look as
Node 1 = 127.0.0.1
Node 2 = 127.0.0.2
Node 3 = 127.0.0.3
Node 4 = 127.0.0.4
Node 5 = 127.0.0.5

Thats it, we have configured the multi node cassandra cluster and its ready to run.
Please post me if you face any problem in the configuration and setup related issues.

Happy Configuring Cassandra. πŸ™‚

Calling C Code from Java

Hello All, over this week end one of my friends asked me to call a C Code from Java, As C has got its own advantages in programming domain, in fact i am a java developer but personally feel “C is Powerful than Java in some aspects”.
Now in this below tutorial i will demonstrate how to call “C code”(Native code) from java Using one of the popular API of java called “JNI”(Java Native Interface).

First of all lets start with the java code as below.

public class JavaToC {
	
	public native void helloC();
 
    static {
        System.loadLibrary("HelloWorld");
    }
 
    public static void main(String[] args) {
        new JavaToC().helloC();
    }
}

Once we have java code let us follow the below steps:

  • Lets make use of the standard tool provided in jdk called ‘javah’, used for generating the header file from java code
  • use the generated header file in the subsequent C code
  • before generating the header file, please compile the java file
  • use : javah JavaToC

the generated header file looks as below.

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JavaToC */

#ifndef _Included_JavaToC
#define _Included_JavaToC
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JavaToC
 * Method:    helloC
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JavaToC_helloC
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Now its time for us to code the C source file as below.

#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
  printf("Hello World: From C");
  return;
}

Please note the below are few points regarding the above C Code.

  • stdio.h is the standard C header file include.
  • jni.h is the bridge header file between the java and C languages, also its available in standard jdk
  • Please note that you can see JavaToC.h file after you issue javah JavaToC command

Now, the major thing comes here, to access C Code from java we need to make the C Code as a shared Lib, inorder to do this we need to hava C Compiler already installed in our system. There are many C Compilers available in market as Turbo C, Cygwin MingW, Tiny C etc, for now i used Tiny C in this example. Here are the instruction to Download and generate the Shared Lib using Tiny C.

  • Please Download the Tiny C from here
  • Unzip the file and set OS path to tcc.exe
  • tcc HelloWorld.c -I D:\Java8\jdk1.8.0_05\include -I D:\Java8\jdk1.8.0_05\include\win32 -shared -o HelloWorld.dll
  • The above command is used for generating the shared Lib (.dll), also the above command is argumented with two folders which contain jni.h and jni_md.h file from standard jdk

Thats all folks, if you are set and every thing went smooth, now its time to call Java code using “Java JavaToC”.
finally the output is as follows.
OP

Happy JNI πŸ™‚

LINQ to SQL in c# .Net

Hello folks, for a change in the week end i started reading .Net, as a programmer i should appreciate both the legendary languages(Java, .Net) some have i was attracted to the beauty of one of the .Net’s feature called LINQ.
so here is a small post where i will demonstrate how to link up our front end with database using LINQ(Language Integrated Query). This is my simple attempt to write a .Net post(apologies if anything is wrong and please give your precious feedback)

prior to create our application let us create the database table as follows

USE [TestDatabase]
GO
/****** Object:  Table [dbo].[Details]    Script Date: 04/27/2014 20:28:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Details](
	[id] [int] NOT NULL,
	[FirstName] [varchar](50) NULL,
	[LastName] [varchar](50) NULL,
	[Age] [int] NULL,
 CONSTRAINT [PK_Details] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF

after creating the database from the visual designer of the VisualStudio please create the following screen.
FrontEnd

inside the “CSharp” class behind this UI double click the submit button it will create the following method

private void SaveDetailsButton_Click(object sender, EventArgs e){
    // code to save the details and retrieve the details using LINQ
}

now its time to create the LINQ class inside the project create a file called “LINQ to SQL” and drag and drop the table in this file and it looks as below.
dbml_file

Once this is done the VisualStudio automatically create the following code


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.4984
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SampleApplication
{
	using System.Data.Linq;
	using System.Data.Linq.Mapping;
	using System.Data;
	using System.Collections.Generic;
	using System.Reflection;
	using System.Linq;
	using System.Linq.Expressions;
	using System.ComponentModel;
	using System;
	
	
	[System.Data.Linq.Mapping.DatabaseAttribute(Name="TestDatabase")]
	public partial class DetailsClassDataContext : System.Data.Linq.DataContext
	{
		
		private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
		
    #region Extensibility Method Definitions
    partial void OnCreated();
    partial void InsertDetail(Detail instance);
    partial void UpdateDetail(Detail instance);
    partial void DeleteDetail(Detail instance);
    #endregion
		
		public DetailsClassDataContext() : 
				base(global::SampleApplication.Properties.Settings.Default.TestDatabaseConnectionString, mappingSource)
		{
			OnCreated();
		}
		
		public DetailsClassDataContext(string connection) : 
				base(connection, mappingSource)
		{
			OnCreated();
		}
		
		public DetailsClassDataContext(System.Data.IDbConnection connection) : 
				base(connection, mappingSource)
		{
			OnCreated();
		}
		
		public DetailsClassDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
				base(connection, mappingSource)
		{
			OnCreated();
		}
		
		public DetailsClassDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
				base(connection, mappingSource)
		{
			OnCreated();
		}
		
		public System.Data.Linq.Table<Detail> Details
		{
			get
			{
				return this.GetTable<Detail>();
			}
		}
	}
	
	[Table(Name="dbo.Details")]
	public partial class Detail : INotifyPropertyChanging, INotifyPropertyChanged
	{
		
		private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
		
		private int _id;
		
		private string _FirstName;
		
		private string _LastName;
		
		private System.Nullable<int> _Age;
		
    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnidChanging(int value);
    partial void OnidChanged();
    partial void OnFirstNameChanging(string value);
    partial void OnFirstNameChanged();
    partial void OnLastNameChanging(string value);
    partial void OnLastNameChanged();
    partial void OnAgeChanging(System.Nullable<int> value);
    partial void OnAgeChanged();
    #endregion
		
		public Detail()
		{
			OnCreated();
		}
		
		[Column(Storage="_id", DbType="Int NOT NULL", IsPrimaryKey=true)]
		public int id
		{
			get
			{
				return this._id;
			}
			set
			{
				if ((this._id != value))
				{
					this.OnidChanging(value);
					this.SendPropertyChanging();
					this._id = value;
					this.SendPropertyChanged("id");
					this.OnidChanged();
				}
			}
		}
		
		[Column(Storage="_FirstName", DbType="VarChar(50)")]
		public string FirstName
		{
			get
			{
				return this._FirstName;
			}
			set
			{
				if ((this._FirstName != value))
				{
					this.OnFirstNameChanging(value);
					this.SendPropertyChanging();
					this._FirstName = value;
					this.SendPropertyChanged("FirstName");
					this.OnFirstNameChanged();
				}
			}
		}
		
		[Column(Storage="_LastName", DbType="VarChar(50)")]
		public string LastName
		{
			get
			{
				return this._LastName;
			}
			set
			{
				if ((this._LastName != value))
				{
					this.OnLastNameChanging(value);
					this.SendPropertyChanging();
					this._LastName = value;
					this.SendPropertyChanged("LastName");
					this.OnLastNameChanged();
				}
			}
		}
		
		[Column(Storage="_Age", DbType="Int")]
		public System.Nullable<int> Age
		{
			get
			{
				return this._Age;
			}
			set
			{
				if ((this._Age != value))
				{
					this.OnAgeChanging(value);
					this.SendPropertyChanging();
					this._Age = value;
					this.SendPropertyChanged("Age");
					this.OnAgeChanged();
				}
			}
		}
		
		public event PropertyChangingEventHandler PropertyChanging;
		
		public event PropertyChangedEventHandler PropertyChanged;
		
		protected virtual void SendPropertyChanging()
		{
			if ((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, emptyChangingEventArgs);
			}
		}
		
		protected virtual void SendPropertyChanged(String propertyName)
		{
			if ((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}
}

now copy and paste the following code snippet into the button handling method as shown below.

 DetailsClassDataContext detailsClassDataContext = new DetailsClassDataContext();

            Detail detail = new Detail();
            detail.id = Int32.Parse(IdtextBox.Text.ToString());
            detail.FirstName = firstNametextBox.Text.ToString();
            detail.LastName = lastNametextBox.Text.ToString();
            detail.Age = Int32.Parse(agetextBox.Text.ToString());
            try
            {
                detailsClassDataContext.Details.InsertOnSubmit(detail);
                detailsClassDataContext.SubmitChanges();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

           
            var data = from a in detailsClassDataContext.Details select a;
            dataGridView1.DataSource = data;

Also in the Form_load method please write the following code as below. this helps to query the database at the application load time and populate the DataGrid.

     private void Form1_Load(object sender, EventArgs e)
        {
            DetailsClassDataContext detailsClassDataContext = new DetailsClassDataContext();
            var data = from a in detailsClassDataContext.Details select a;
            dataGridView1.DataSource = data;
        }

Finally aour application is ready to use and this looks as below.
FinalScreen

Happy Coding in LINQ to SQL with C# πŸ™‚

James Gosling grades Oracle’s handling of Sun’s technology

Gosling says Oracle has done ‘surprisingly well’ with Java

With the four-year anniversary of Oracle’s Sun Microsystems acquisition looming, we reached out to Java founder James Gosling to rate how Oracle has done in shepherding Sun technology.
Gosling gives Oracle eyebrow-raising grades, lauding Oracle’s handling of Java,despite his past acrimony toward Oracle over Java, and giving Oracle a flat-out failing grade on what has become of Solaris OS.
Gosling was a longtime Sun technologist and, briefly, a CTO at Oracle right after Oracle bought Sun in January 2010. He is considered the father of Java, which was founded at Sun in 1995. Asked how different technologies have faired under Oracle’s stewardship, Gosling graded Oracle and offered his own perspectives:
sample

These days, Gosling is chief software architect at Liquid Robotics, which develops ocean-based robotics. After leaving Oracle in 2010, Gosling stopped presenting at the JavaOne technical conference, but he reappeared onstage at the event in October 2012.

Credits : directly taken from “www.infoworld.com”
Java is great…

Configuring memcached and Servlet Client

After some research I found that there is a Win32 binary version of memcached available here.

So go there and download win32 binary version to your computer. When downloaded, extract the file to folder memcahced on your C partition.

You should get only one file named memcached.exe. Now we need to install this as a service, as memCached is daemon and should be run only as service.

To install Memcached as a service, follow these steps (please change all forward slashes to backslashes):

1.If you’re running Vista, you should set memcached.exe to Run as administrator,Install the service using the command:
2.Install the service using the command:

c:/memcached/memcached.exe  -d install

3.Start the server from the Services or by running one of the following commands:

c:/memcached/memcached.exe -d  start

or

net start "memcached Server"

That is it, now your memcached server is installed and is listening to port 11211. There is one more thing left to do. By default, server is set to 64Mb memory limit, which is too small.

Once the configuration is done its time for us to create a client, that will interact with memcached server.

package com.spark.javaee6.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.spy.memcached.MemcachedClient;

/**
 * Servlet implementation class Javaee6Servlet
 */
@WebServlet("/Javaee6Servlet")
public class Javaee6Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Javaee6Servlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		MemcachedClient c=new MemcachedClient(
			    new InetSocketAddress("localhost", 11211));

			// Store a value (async) for one hour
			c.set("sample_key", 3600, "sample_value");

		PrintWriter printWriter = response.getWriter();
		printWriter.println("session key: sample_key, session value: sample_value");
	}

}

in the line 45 the cache is storing a key,value pair. Now if want to retrieve it the following code has to be integrated.

MemcachedClient c=new MemcachedClient(
			    new InetSocketAddress("localhost", 11211));

			// Store a value (async) for one hour
		String value =  (String)c.get("sample_key");

That is it.
Happy Coding πŸ™‚

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 πŸ™‚