^ Click Here

Tuesday, January 1, 2013

Java: Generate random password -- with different combinations like characters, numbers, capital letters, special characters.

Alright...I feel that one of the biggest challenge in making computer like humans is the human's unique capacity of being random......Computer mostly do calculations and has to follow some set patterns....however in much programming language there is some way for getting random values.

In web application we often needs to generate random key, number, password or patterns. I thought to write a program which could be a solution to much of the demands, but what it primarily does is to provides you a random password (which was the initial idea) based on the need and pattern we provide.

First the program then the description......

/**
 * 
 */
package com.see.proj.app.util;

/**
 * @author Rahul
 *
 */
public class PassUtil {
 
 private static String ALPHABETS ="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
 private static String CAPITAL_LETTERS = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
 private static String NUMBERS = "1,2,3,4,5,6,7,8,9,0";
 private static String SPECIAL_CHARACTERS = "~,!,#,$,%,^,&,*,?,-,=,_,+";
 private static int DEFAULT_PASSWORD_LENGTH = 8;
 
 public static String getRandomPassword(int passwordLength, boolean alphabets, boolean numbers, boolean capitalLetters, boolean specialCharacters, String prefix, String suffix, boolean mustContain){
  StringBuilder passContainer = new StringBuilder("");
  
  int desiredTypes = 0;
  //filtering the password possibility string according to option
  passContainer = alphabets?passContainer.append(","+ALPHABETS):passContainer;
  passContainer = numbers?passContainer.append(","+NUMBERS):passContainer;
  passContainer = capitalLetters?passContainer.append(","+CAPITAL_LETTERS):passContainer;
  passContainer = specialCharacters?passContainer.append(","+SPECIAL_CHARACTERS):passContainer;
  
  //If no types are allowed i.e. all desired types options are false
  if("".equals(passContainer.toString())){
   throw new IllegalArgumentException("There must be some type out of small letters, capital letters, numbers or special character must be allowed");
  }
  //typically for mustContain option
  desiredTypes = alphabets?(desiredTypes+1):desiredTypes;
  desiredTypes = numbers?(desiredTypes+1):desiredTypes;
  desiredTypes = capitalLetters?(desiredTypes+1):desiredTypes;
  desiredTypes = specialCharacters?(desiredTypes+1):desiredTypes;

  //getting all the characters which can be in the password as an array
  String[] passContainerArr = passContainer.toString().substring(1).split(",");
  
  //validating the suffix and prefix
  String passPrefix = prefix ==null?"":prefix;
  String passSuffix = suffix ==null?"":suffix;
  
  //typically for mustContain option
  String externalPass = passPrefix+passSuffix;
  boolean haveAlphabet = ("").equals(externalPass)?false:containsSmallLetter(externalPass);
  boolean haveCapitalLetters = ("").equals(externalPass)?false:containsCapitalLetter(externalPass);
  boolean haveNumbers = ("").equals(externalPass)?false:containsNumber(externalPass);
  boolean haveSpecialCharacter = ("").equals(externalPass)?false:containsSpecialCharacter(externalPass);

  
  //validating password length
  int passLength = passwordLength==0?DEFAULT_PASSWORD_LENGTH:passwordLength;
  int passLengthToFillIn = passLength - (passPrefix.length()+passSuffix.length());
  if(passLengthToFillIn == 0){
   return passPrefix+passSuffix;
  }
  else if(passLengthToFillIn < 0){
   throw new IllegalArgumentException("Password prefix : "+passPrefix+" and suffix : "+passSuffix+" adds up to more than the password length : "+passwordLength+" provided");
  }
  
  if(mustContain && passLengthToFillIn < desiredTypes){
   throw new IllegalArgumentException("password cannot contain all the character since desired type : "+desiredTypes+" is more than password length : "+passLengthToFillIn+" to fill in");
  }
  StringBuilder pass = new StringBuilder("");
  //creating the password sans prefix and suffix in a loop
  for(int midPass=0; midPass<passLengthToFillIn; midPass++){
   //this part is optional and experimental with must include all the desired character : Start
   if(mustContain && desiredTypes >= (passLengthToFillIn - midPass)){
    if(alphabets && !haveAlphabet && !containsSmallLetter(pass.toString())){
     pass.append(getSingleRandomSmallLetter());
     haveAlphabet = true;
     continue;
    }
    if(capitalLetters && !haveCapitalLetters && !containsCapitalLetter(pass.toString())){
     pass.append(getSingleRandomCapitalLetter());
     haveCapitalLetters = true;
     continue;
    }
    if(numbers && !haveNumbers && !containsNumber(pass.toString())){
     pass.append(getSingleRandomNumber());
     haveNumbers = true;
     continue;
    }
    if(specialCharacters && !haveSpecialCharacter && !containsSpecialCharacter(pass.toString())){
     pass.append(getSingleRandomSpecialCharacter());
     haveSpecialCharacter = true;
     continue;
    }
   }
   //End
   
   //the actual creation of password string
   int randomIndex = (int) Math.floor(Math.random()*passContainerArr.length);
   //appending a random character from password array
   pass.append(passContainerArr[randomIndex]);
  }
  //final password
  String totalPass = passPrefix+pass.toString()+passSuffix;
  return totalPass;
 }
 
 private static boolean containsSmallLetter(String stringToCheck){
  return stringToCheck.matches("(.*)[a-z](.*)");
 }
 
 private static boolean containsCapitalLetter(String stringToCheck){
  return stringToCheck.matches("(.*)[A-Z](.*)");
 }
 
 private static boolean containsNumber(String stringToCheck){
  return stringToCheck.matches("(.*)[0-9](.*)");
 }
 
 private static boolean containsSpecialCharacter(String stringToCheck){
  String[] spChArray = SPECIAL_CHARACTERS.split(",");
  for(String spCharacter : spChArray){
   if(stringToCheck.indexOf(spCharacter) >= 0){
    return true;
   }
  }
  return false;
 }
 
 private static String getSingleRandomSmallLetter(){
  String[] alphabetArr = ALPHABETS.split(",");
  return alphabetArr[(int) Math.floor(Math.random()*alphabetArr.length)];
 }
 
 private static String getSingleRandomCapitalLetter(){
  String[] alphabetArr = CAPITAL_LETTERS.split(",");
  return alphabetArr[(int) Math.floor(Math.random()*alphabetArr.length)];
 }
 
 private static String getSingleRandomNumber(){
  String[] alphabetArr = NUMBERS.split(",");
  return alphabetArr[(int) Math.floor(Math.random()*alphabetArr.length)];
 }
 
 private static String getSingleRandomSpecialCharacter(){
  String[] alphabetArr = SPECIAL_CHARACTERS.split(",");
  return alphabetArr[(int) Math.floor(Math.random()*alphabetArr.length)];
 }
 
 
 private static String generateRandomNumberCode(int lengthOfDigit){
  //mustContain option is meaningless since only number option is to be there in the code/password
  return getRandomPassword(lengthOfDigit,false,true,false,false,null,null,false);
 }
 
 private static String getRandomPasswordStartingWithCapitalAndEndingWithNumber(int passwordLength){
  String prefix = getSingleRandomCapitalLetter();
  String suffix = getSingleRandomNumber();
  return getRandomPassword(passwordLength, true, true, true, true, prefix, suffix, false);
 }
 
 private static String getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter(int passwordLength){
  String prefix = getSingleRandomCapitalLetter();
  String suffix = getSingleRandomSpecialCharacter();
  return getRandomPassword(passwordLength, true, true, true, true, prefix, suffix, false);
 }
 
 private static String getRandomAlphaNumericPasswordStartingWithNumber(int passwordLength){
  String prefix = getSingleRandomNumber();
  return getRandomPassword(passwordLength, true, true, false, false, prefix, null, false);
 }
 
 public static void main(String[] args){

  //must contain all types
  String allPassMustContain = getRandomPassword(4,true,true,true,true,null,null,true);
  System.out.println("allPassMustContain : "+allPassMustContain);
  //all options could be there in the password
  String allPass = getRandomPassword(10,true,true,true,true, null,"99",false);
  System.out.println("allPass : "+allPass);
  //only small letter alphabet and number
  String alphaNumeric = getRandomPassword(10,true,true,false,false,null,null,false);
  System.out.println("alphaNumeric : "+alphaNumeric);
  //alphabet including capital letter and numbers
  String alphaNumericWithCapital = getRandomPassword(10,true,true,true,false,null,null,false);
  System.out.println("alphaNumericWithCapital : "+alphaNumericWithCapital);
  //numbers only
  String numberOnly = getRandomPassword(16,false,true,false,false,null,null,false);
  System.out.println("numberOnly : "+numberOnly);
  //random number only
  System.out.println("generateRandomNumberCode : "+generateRandomNumberCode(5));
  //Methods with a pattern
  System.out.println("getRandomPasswordStartingWithCapitalAndEndingWithNumber : "+getRandomPasswordStartingWithCapitalAndEndingWithNumber(8));
  System.out.println("getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter : "+getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter(8));
  System.out.println("getRandomAlphaNumericPasswordStartingWithNumber : "+getRandomAlphaNumericPasswordStartingWithNumber(8));
 }
}

before we move further let me show you what it actually prints on running

allPassMustContain : aS2_
allPass : uFttRDOm99
alphaNumeric : nqalid32i5
alphaNumericWithCapital : 7r4uCYFxCY
numberOnly : 2779697529864423
generateRandomNumberCode : 09154
getRandomPasswordStartingWithCapitalAndEndingWithNumber : J#kUpsg8
getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter : TU0Ab&f~
getRandomAlphaNumericPasswordStartingWithNumber : 2w7uqwpw

 // in a nutshell
First one  allPassMustContain is a 4 letter random password which must contains a small letter, a capital letter, a number and a special character
Second allPass is a 10 letter random password which can contain small letters, capital letters, numbers and special characters and always ends with 99.
Third is  alphaNumeric a 10 letter random password which contains small letters and numbers only
Fourth  alphaNumericWithCapital is a 10 letter random password which contains letters (small and capital) and numbers only
Fifth numberOnly is a 16 digit random number.
Sixth generateRandomNumberCode is 5 digit random number.
Seventh getRandomPasswordStartingWithCapitalAndEndingWithNumber defines itself  8 character random password starts with capital letter and end with numbers.
so is with getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter 8 character random password starts with capital letter and end with special character.
And the last Ninth getRandomAlphaNumericPasswordStartingWithNumber one produces 8 character random password which always starts with a number.

Alright the idea was to create one static method which is flexible and capable of providing the random password with different needs so first of all I chose four factors - small letters (a-z), Capital letters (A-Z), numbers (0-9), Special characters (#,% etc.) hence there are four static variable with comma(,) separated values :

 private static String ALPHABETS ="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
 private static String CAPITAL_LETTERS = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
 private static String NUMBERS = "1,2,3,4,5,6,7,8,9,0";
 private static String SPECIAL_CHARACTERS = "~,!,#,$,%,^,&,*,?,-,=,_,+";
 private static int DEFAULT_PASSWORD_LENGTH = 8;

the last one DEFAULT_PASSWORD_LENGTH is little unimportant right now, now initially the function I came out was :

public static String getRandomPassword(int passwordLength, boolean alphabets, boolean numbers, boolean capitalLetters, boolean specialCharacters, String prefix, String suffix){
  StringBuilder passContainer = new StringBuilder("");
  
  //filtering the password possibility string according to option
  passContainer = alphabets?passContainer.append(ALPHABETS):passContainer;
  passContainer = numbers?passContainer.append(NUMBERS):passContainer;
  passContainer = capitalLetters?passContainer.append(CAPITAL_LETTERS):passContainer;
  passContainer = specialCharacters?passContainer.append(SPECIAL_CHARACTERS):passContainer;
  
  //getting all the characters which can be in the password as an array
  String[] passContainerArr = passContainer.toString().split(",");
  
  //validating the suffix and prefix
  String passPrefix = prefix ==null?"":prefix;
  String passSuffix = suffix ==null?"":suffix;
  
  //validating password length
  int passLength = passwordLength==0?DEFAULT_PASSWORD_LENGTH:passwordLength;
  int passLengthToFillIn = passLength - (passPrefix.length()+passSuffix.length());
  if(passLengthToFillIn == 0){
   return passPrefix+passSuffix;
  }
  else if(passLengthToFillIn < 0){
   throw new IllegalArgumentException("Password prefix : "+passPrefix+" and suffix : "+passSuffix+" adds up to more than the password length : "+passwordLength+" provided");
  }
  StringBuilder pass = new StringBuilder("");
  //creating the password sans prefix and suffix in a loop
  for(int midPass=0; midPass<passLengthToFillIn; midPass++){
   int randomIndex = (int) Math.floor(Math.random()*passContainerArr.length);
   //appending a random character from password array
   pass.append(passContainerArr[randomIndex]);
  }
  //final password
  String totalPass = passPrefix+pass.toString()+passSuffix;
  return totalPass;
 }

In most cases this method itself was enough to tackle the problem, the parameter it takes is
 > passwordLength : Simple enough, the (int) length of password which is needed (it's the final length including prefix and suffix provided)
 > alphabets : the boolean which specifies if the password should/can consist alphabet or not (if true it can).
 > numbers : same as alphabets i.e. if numbers should be considered or not.
 > capitalLetters : capital letters or not.
 > specialCharacter : make a wild guess :) .
 > prefix : if any special prefix (at the beginning) you want to provide in your password like 'P1' etc.
 > suffix : at the end

Now based on the provided options (the boolean value) first of all I created a string of all the comma separated value which can be there and with that created an array of single characters of all those character by splitting that.
checked for the validity of passwordLength, prefix and suffix and calculated actually how many random characters we need barring the prefix and suffix.

simply ran the loop that many time and got a random character from the array and added it to create a middle password and finally returned the total password with adding prefix and suffix it in the start and end respectively.

and it was done. Mission Accomplished!!

all you need to do is provide your options for ex.

int PasswordLength = 9; 
boolean containsAlphabet = true;
boolean containsNumber = true;
boolean containsCapitalLetters = false;
boolean containsSpecialCharacters = false
String suffix = null;
String prefix = "7";
String randomPassword = PassUtil.getRandomPassword(passwordLength, containsAlphabet , containsNumber , containsCapitalLetters , containsSpecialCharacters , prefix, suffix);

Yeah I know initiating that much variable is unnecessary but I did that on purpose because it makes the code readable and easy to understand. if I simply write

PassUtil.getRandomPassword(9, true, true, false, false, "7", null);

after few months I myself won't know what the hell those true, false and null stands for until I further go into that very method and try to recollect.

anyway either way it would return you a 9 character password starting with 7 and will contain small letters and numbers (i.e.alphanumeric). So we can try different combinations.

But there is a problem, a-z is 26 character and 0-9 is only 10 character, there are possible chances that your password may contain all the letters only and no number after all it's a random selection. In fact there might be a chance that the random password may contain only numbers and no character. If we include A-Z then there are 26 more characters making the letter to 52 and numbers 10 and special character well 13 i.e unequal proportion.

Obviously there is a scenario where we need that our password must contain at least one character or numbers or any option we have allowed in our password that is where it got bit complicated as I introduced a new boolean value mustContain which forces the method to put atleast one of each type. (look at the final method at the top)

Of course it's a added burden on the very method because now I need to check for all the allowed types in the password and then check that let's say when few minimum password is needed to be added and when there is not even a single character of the desired type I am putting a random value and continuing the loop, obviously it needs to be done before it puts a character from the collection of all desired types array. I have introduced some extra boolean values (haveNumbers, haveCapitalLetters etc) so that once we put the character of a certain type it does not check for the same type again.

Finally we can define our own pattern specific random password generator for example  getRandomPasswordStartingWithCapitalAndEndingWithSpecialCharacter

 All we need to do is to use the different combinations of the core method :
getRandomPassword(int passwordLength, boolean alphabets, boolean numbers, boolean capitalLetters, boolean specialCharacters, String prefix, String suffix, boolean mustContain)

Ohh and don't forget to check your password strength in  -->>here<<--

Hope it helps somebody.

 P.S - Please have a long password with at least one of each type character. :)

Friday, September 14, 2012

Sending HTML (as) Mail through Java (Spring)

[This is basically an extension of the earlier post Sending Simple Mail through Java (Spring) ]

In this mail we will try to send HTML(and CSS) as mails.....please refer to the earlier post about simple mail as there is no point in repeating things, Moreover this would contain an example which would build on earlier post example. Just to make sure we don't miss anything.

So basically no changes in the Spring application context Spring.xml file.

<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender">
    <property name="host" value="smtp.gmail.com">
    <property name="port" value="587">
    <property name="username" value="username">
    <property name="password" value="password">
    <property name="javaMailProperties">
       <props>
           <prop key="mail.smtp.auth">true</prop>
           <prop key="mail.smtp.starttls.enable">true</prop>
       </props>
    </property>
</bean>
But to send HTML in mail SimpleMailMessage won't work. That is actually too simple for the task. Hence for this we would need a MimeMessage. MimeMessage is very much different from SimpleMailMessage however one of the biggest and more likable advantage we have with MimeMessage is MimeMessageHelper.


package mimeSendMail;

import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MimeSendMail
{

 @Autowired
 private JavaMailSender mailSender; 

public void sendMimeMessage(String from, String[] to, String subject, String msg) throws Exception{
  MimeMessage mime = this.mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(mime, true);
  helper.setFrom(from);
  helper.setTo(to);
  helper.setSubject(subject);
  String htmlText = "<div style='background:#00FA9A;text-align:center;"+
                "font-size:12pt;font-weight:bold;color:#800000;padding:10px;'>"+
                "That feeling when......<br /><br />"+
                "You miss your spectacles while looking for your spectacles....<br /><br />"+
                "The person whom you secretly dislike, helps you......<br /><br />"+
                "The person whom you have crush on seems happy all the time....<br /><br />"+
                "the beggar recognizes you and stops asking for penny from you since you have never given....<br /><br />"+ 
                "</div>";
    helper.setText(htmlText,true);
    this.mailSender.send(mime);
    }
}

I guess this should do it. Yes, the HTML and inline css really looks nasty but I didn't find any way to transfer the css file to the mailing server and I doubt if there are any. Hence we have to live with inline css also a blessing in disguise about inline css is that it overrides other pre-defined css properties.

Here we saw that  from the JavaMailSender we create a MimeMessage and with that in turn we create MimeMessageHelper which does various task( much beyond rendering HTML text).

Now we are ready to give it a test.

package mimeSendMail;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mimeSendMail.MimeSendMail;

public class SendMailTest {

  @Test 
 public void mailTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("mimeSendMail/SpringMail.xml");

        MimeSendMail mm = (MimeSendMail) context.getBean("mimeSendMail");
        mm.sendMail("sender@gmail.com",
        new String[]{"recepient1@gmail.com","recepient2@rediffmail.com"},
        "Hello Friend", 
        "This is a test mail");
 } 
}

(Yeah I know the parameter msg is not being used and its redundant, you can get rid of that.)
Hope this helps.

Saturday, September 1, 2012

jQuery : Showing the text in typing (typewriter) effect

I was trying for it and came out with an idea so that we can show the text and messages as someone is typing it (of course that's an illusion like much of other things).

So here it goes. You have a text message and you want to show it with the effect, first of all we need to break the sentence for each single letter or alphabet and then would need to put it one after another with certain time-difference. the logic seems simple.

So here is the primary function for it :-

function demoTypeWriting(){
  var text = "Our whole theory of education is based on the absurd notion that we must learn to swim on land before tackling the water."
  var textArray = text.split("");
  $('div#resultDiv').append('<div id="typeText"></div>');
  timer = setInterval( function(){writeText(textArray)}, 500 ); 
}

Once it's done, I would provide for the function which will actually execute the task of typing the text :-

function writeText(textArray){
    if(textArray.length > 0){
    console.log(textArray[0]);
    $('div#newText').focus().append(textArray[0]);
    textArray.splice(0,1);
    }
    else{
        clearInterval(timer);
    }
}

So as you can see I am doing nothing great I am putting first element into the designated div and since it's already has been put, I am removing it from the array, So that next element can be put. Finally when array is empty I am stopping the timer. 

Try it here :-

Your Text:
Time Difference :

Result : -

Sunday, August 26, 2012

Sending Simple Mail through Java (Spring)

Seriously, there are plenty of examples for this available on net and mine isn't any different in that respect (well not this one). So here we go...

I am using a maven project but you can do it without that also though it would be bit pain to download the jar by yourself and putting them in buildpath.....still the concept that matters.

so first of all the dependency needed to be added is (I assume there is already a spring core, context and junit test dependency available).

<!-- Java Mail API -->
    <dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4.5</version>
    </dependency>

Secondly, since I am using maven and spring, I would define a bean in the Spring configuration xml file.

<bean class="org.springframework.mail.javamail.JavaMailSenderImpl" id="mailSender">
    <property name="host" value="smtp.gmail.com">
    <property name="port" value="587">
    <property name="username" value="username">
    <property name="password" value="password">
    <property name="javaMailProperties">
       <props>
           <prop key="mail.smtp.auth">true</prop>
           <prop key="mail.smtp.starttls.enable">true</prop>
       </props>
    </property>
</bean>

Now our java mail sender bean is ready (I don't need to tell that put your username and password value in the properties) we have define a gmail host smtp.gmail.com and port is 587 because that's the port gmail uses for smtp (though 25 is a default port for smtp). also we need to turn on few properties like auth and tls. but that's about configuration.

Now we will prepare for using this mailSender bean to send a simple message.

So here is my class for that -

package simpleSendMail;
 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
 
@Component
public class SendMail
{
    @Autowired
    private MailSender mailSender;
 
 public void sendMail(String from, String[] to, String subject, String msg) {
  SimpleMailMessage message = new SimpleMailMessage();
  message.setFrom(from);
  message.setTo(to);
  message.setSubject(subject);
  message.setText(msg);
  mailSender.send(message); 
 }
}

As you see I have autowired the mailSender bean to be used here, instead of it you very well can define this class as a bean and in xml configuration file link mailSender bean to the property of this one....if that is the case don't forget to put a setter......maybe this will help.

So as you can see there is a method which takes parameter for from, to addresses and subject and text to be sent then initiates the object of SimpleMessage class , sets the value and with our mailSender it sends that SimpleMessage

below is the Test class for that.

package simpleSendMail;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendMailTest {

  @Test 
 public void mailTest(){
    ApplicationContext context = new ClassPathXmlApplicationContext("simpleSendMail/SpringMail.xml");

       SendMail mm = (SendMail) context.getBean("sendMail");
           mm.sendMail("sender@gmail.com",
        new String[]{"recepient1@gmail.com","recepient2@rediffmail.com"},
        "Hello Friend", 
        "This is a test mail");
 } 
}

Again in test method you will provide valid mail addresses for to and from option

This might( and most surely) would fail if you are behind some proxy or firewall which doesn't let you use the specified port directly and blocks it considering it a threat. (Solution? I am still trying to find out.)

Thursday, August 9, 2012

[fixed] jQuery UI datepicker showing calendar when setting date.

For showing, choosing date jQuery UI datepicker is a great plugin, it provides a lot of functionality. However I feel it's little short on events, yet enough to fulfill almost all need of a basic application.

I was using that however I found an issue......with a few logic I was updating a date field which have a date picker when another field with datepicker was updated.

Problem : the primary datepicker was is visible and secondary is well say gets visible only when user wants. Since I was updating the secondary even when it was hidden.....it popped a calendar at the bottom of the page which of course was an annoying issue since it didn't use to disappear until and unless user clicks on some other datepicker enabled field.

I figured it out that the problem was with datepicker setDate function...I was using

$('.date-pick').datepicker('setDate', newDate)  //where date is a js date object.

I found that there is a hide function in datepicker, I tried that but it couldn't solve the problem

$('.date-pick').datepicker('setDate', newDate).datepicker('hide')   //failed miserably.

Hence I started to google it out......but didn't really got a satisfactory solution, but found out that few other people were facing the same problem. I got a hint from some site then I started looking into the datepicker js (I certainly am not a js expert).

there in the _setDateDatepicker function after setting the date value in the target it was calling _updateDatepicker which I assumed was popping the datepicker calendar but since the target was hidden it couldn't get the exact position hence it showed the calendar on the bottom left of the page.

So I commented that _updateDatepicker function out and it stopped popping the calendar while setting the date.



Monday, June 25, 2012

Creating a table in MySQL

Frankly, lots of tutorials and you can easily gather info regarding this with google......

Still I am putting it simply with an example and then defining the parts in it so that it can be understood easily.......Suppose you have to create a table 'employee' in MySQL......

CREATE TABLE IF NOT EXISTS EMPLOYEE (
        id INT(20) NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
 email VARCHAR(50) NOT NULL UNIQUE,
 PASSWORD VARCHAR(40),
 NAME VARCHAR(50),
 dob DATETIME DEFAULT NULL,
 sex ENUM("M","F","N") DEFAULT "N",
 STATUS ENUM("Single","Married","Complicated","Divorced","Relationship","Widowed","Engaged","Undisclosed") DEFAULT "Undisclosed",
 TYPE ENUM("Admin","Registered","Unregistered","Anonymous") DEFAULT "Registered",
 department_id INT(20),
 is_deleted ENUM("True","False") DEFAULT "False",
 created_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',
 modified_date TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
 
 FOREIGN KEY (department_id) REFERENCES department(id)
) ENGINE = INNODB;

Now Let's see it line by line

CREATE TABLE IF NOT EXISTS EMPLOYEE
          - it is self-explanatory this only creates the table when there is no table in the database with the same table name, if we just use CREATE TABLE tableName and suppose we already have a table in the database with the same table name, it will throw an error. Hence using 'IF NOT EXISTS' we prevent that error and also its a nice practice.

id INT(20) NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
             - id is the column name its of type int with range 20 i.e. an int with 20 digit. the id should not be null i.e. insuring a legitimate value,
AUTO_INCREMENT is assigning MySQL to take care of increasing the id automatically so that we don't have to insert id explicitly and it vanishes the chance of duplicacies of id as while manually entering you might try to enter an id which is already there.
UNIQUE is used to ascertain that for each employee there should be a unique id however with AUTO_INCREMENT we are already fulfilling that condition yet from a developer's point of view its desirable to apply such condition.
PRIMARY KEY is used to tell that this column would be used as the primary key for this table.

email VARCHAR(50) NOT NULL UNIQUE,
              -email is the name of the column. the type is varchar which is short form of variable character, variable character can contain number or special character like @ which is needed while storing email with domain name. NOT NULL again make sure that no employee data should be there without an email. UNIQUE is to make sure that all employee should have a unique email id, hence this constraint is legitimate and necessary here since it helps us in having an organized, transparent and clean data in the table.

dob DATETIME DEFAULT NULL,
             -dob is short for date of birth, the data type is DATETIME and if no value is specified while insertion, by default it would take NULL as value. note that even if we don't specify it will take null as a default.

sex ENUM("M","F","N") DEFAULT "N",
             -for column sex we are using ENUM which contains three values "M" short for Male, "F" short for Female and "N" for Not Provided. Default is "N" hence when sex is not specified for an employee, it would by default take "N" as value.

created_date TIMESTAMP DEFAULT '0000-00-00 00:00:00',
        -created date should be a time stamp type and if not specified it would take 0000-00-00 00:00:00 value. note that while inserting you can use sysdate() in the query as it is to put the timestamp while creating the row.

modified_date TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
            -modified_date same like created_date should be a timestamp type and has a default 0000-00-00 00:00:00 value. however it has an extra clause ON UPDATE CURRENT_TIMESTAMP. This take the tough task of automatically updating the timestamp whenever the row is updated so that we don't have to specify that in query. An important point to note that you can't have more than one instance where you can use CURRENT_TIMESTAMP i.e. only one column will have this clause of ON UPDATE CURRENT_TIMESTAMP.

FOREIGN KEY (department_id) REFERENCES department(id)
             -department_id is a column in the table with type int, with this line we are assuring that department_id is actually a FOREIGN KEY which references the 'id' column of 'department' table in the same database. Hence it is actually linking of the employee table with department table where each employee's department data can be retrieved by mapping the department_id with the id in department table. Not only it links and makes it more organized it makes sure that you don't delete a row from department table if that row id is being used in employee table for any employee, hence it helps us from committing accidental deletes and makes the tables clean and healthy.

 ENGINE = INNODB;
              -not much on this it specifies as which MySQL engine to use for this table. More on MySQL engines here.

Hope this helps.

Thursday, March 29, 2012

get a random element from Set or Map

To get a random element from a list is quite easy......you just have to get the element t the nth position where n is a random number. But A Set is an unordered collection so there is no question of any definite element at definite position.

In this situation the way to get a random element from a Set might not have a straightforward way.......But the thing that can be done is iterate through the set and get the nth element where n is a random number. Conceptually it's the same as getting a random element from a List or array.


public String getRandomId(Set<String> idSet){
  int Size = idSet.size();
  int item = new Random().nextInt(Size);
  return (String) idSet.toArray()[item];
 }

 
Above method will return a random String from a Set of String........

Now suppose there is a Map with a String type as key and anything else say an Object as value...for example


Map<String,User> userMap = new HashMap<String,User>();

where User  is a Class and userMap holds the map between String id as key and user object as value.......to get a random user from this map we will use the above method in the example


String randomId = this.getRandomId(userMap.keySet());
User randomUser = userMap.get(randomId);

Hence we can get a random elements through this method. we just got a set of String of keys of the map and then used the previous getRandomId method to get a random key and got the corresponding value from the map.

Hope it helps.....

Saturday, March 17, 2012

Autowiring with annotation and autodiscovering Example

We have seen the examples where Autowiring (with .xml) was done. It's sort of magical comprehensibility of Spring Framework where it by itself chooses the proper candidate and connect it to the respective beans

In last example it was autowiring with configuration in xml file, Now we will see it with annotation and autodiscovering. Autodiscovering is meant to be the setting where beans are auto discovered by Spring Framework through Classes and the annotations are used for setting the value and autowiring.

I made a package named "annotationAutowire" and inside that I put the same Classes which were there in the previous example of Spring Basic. The only difference that this time the classes are annotated.

the Class Person.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Person {
 @Value("Rahul")
 private String name;
 private IAnimal animal;
 
 public void setName(String name) {
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public IAnimal getAnimal() {
  return animal;
 }
 @Autowired
 @Qualifier("dog")
 public void setAnimal(IAnimal animal) {
  this.animal = animal;
 }
 public String toString() {
  return name+" has a "+animal.toString();
 }
}


the interface IAnimal.java

package annotationAutowire;

public interface IAnimal {
 public void play();
}

the Class Dog.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Dog implements IAnimal {
 @Value("Doug")
 private String name;
 public void play() {
  // TODO Auto-generated method stub
  System.out.println("Playing with "+name);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String toString() {
  return " Dog with name "+name;
 }
}

the Class Cat.java

package annotationAutowire;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Cat implements IAnimal {
 
 private String name;
 public void play() {
  // TODO Auto-generated method stub
  System.out.println("Playing with "+name);
 }
 public String getName() {
  return name;
 }
 @Value("jejebel")
 public void setName(String name) {
  this.name = name;
 }
 public String toString() {
  return " Cat with name "+name;
 }
}


The annotation used are

@Component - use for declaring the instance of the class as bean, equivalent to bean tag in .xml file
@Autowired - declares that the element is autowired, equivalent to "autowire" attribute in xml file. The autowiring rules are unchanged. It could be placed at the declaration in the class as well as at the setter method.
@Qualifier - this annotation is used to tell that which component would qualify for autowiring, It can be related to autowire-candidate attribute in .xml file. it's safe to provide one to help in avoiding later conflicts.
@Value - this annotation is used to pass the value as String, it is the equivalent of property and p namespace equivalent in .xml file and can be placed at declaration as well as at setter method.

the config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<context:component-scan base-package="annotationAutowire"></context:component-scan>
</beans>


the context:component-scan is used for autodiscovering it will discover all the component (through @Component annotation) in the explicitly directed base-package annotationAutowire and while creating bean through those component it will do the job of autowiring with the help of @Autowired and @Qualifier annotations
Hence like earlier examples we didn't need to define bean and pass the values through property and p namespace. This all was taken care by annotations.
Element : component-scan
Scans the classpath for annotated components that will be auto- registered as Spring beans. By default, the Spring-provided @Component, @Repository, @Service, and @Controller stereotypes will be detected. Note: This tag implies the effects of the 'annotation-config' tag, activating @Required, @Autowired, @PostConstruct, @PreDestroy, @Resource, @PersistenceContext and @PersistenceUnit annotations in the component classes, which is usually desired for autodetected components (without external configuration). Turn off the 'annotation-config' attribute to deactivate this default behavior, for example in order to use custom BeanPostProcessor definitions for handling those annotations. Note: You may use placeholders in package paths, but only resolved against system properties (analogous to resource paths). A component scan results in new bean definition being registered; Spring's PropertyPlaceholderConfigurer will apply to those bean definitions just like to regular bean definitions, but it won't apply to the component scan settings themselves.
Content Model : (include-filter*, exclude-filter*)

the test Class PersonTest.java

package pkg;

import annotationAutowire.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
 @Test
 public void vehicleTest(){
  ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
  Person person = (Person) context.getBean("person");
  System.out.println(person);
 }
}

The Structure finally is


junit test result without doubt should be "Rahul has a  Dog with name Doug". because the qualifier is set to "dog".......and it can be changed to "cat" to get the autowiring of animal with cat component/bean.

Hope it helps.
 

Thursday, March 15, 2012

Spring Autowiring types with examples

 [ All the examples in this post are basically an extension from the previous post of Spring Basic ]

Autowiring is a feature in Spring through which we can pass the reference of any dependent bean automatically.......This is a step where we are telling the Spring framework to take care of the dependencies.
In that case when Application Context is created the Spring Framework will search for the beans on which it is dependent on according to set guidelines and if and when it finds the bean it will inject that automatically hence we no further need to take care of passing the reference.
Controls whether bean properties are "autowired". This is an automagical process in which bean references don't need to be coded explicitly in the XML bean definition file, but rather the Spring container works out dependencies. There are 4 modes: 1. "no" The traditional Spring default. No automagical wiring. Bean references must be defined in the XML file via the element (or "ref" attribute). We recommend this in most cases as it makes documentation more explicit. Note that this default mode also allows for annotation- driven autowiring, if activated. "no" refers to externally driven autowiring only, not affecting any autowiring demands that the bean class itself expresses. 2. "byName" Autowiring by property name. If a bean of class Cat exposes a "dog" property, Spring will try to set this to the value of the bean "dog" in the current container. If there is no matching bean by name, nothing special happens. 3. "byType" Autowiring if there is exactly one bean of the property type in the container. If there is more than one, a fatal error is raised, and you cannot use byType autowiring for that bean. If there is none, nothing special happens. 4. "constructor" Analogous to "byType" for constructor arguments. If there is not exactly one bean of the constructor argument type in the bean factory, a fatal error is raised. Note that explicit dependencies, i.e. "property" and "constructor-arg" elements, always override autowiring. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per concrete bean definition

What did I mean by "set guidelines"?? for Spring Framework to find the correct bean we must set some rules.............well nothing speaks better than example....Hence going with our previous example

Our config.xml file will be

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="byType">   
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel"> 
 </bean></beans>
Note that the autowiring is "byType" , it simply means in the Person Class the type of "animal" is IAnimal......Hence the Spring framework in the Application Context will search for all beans with type IAnimal and will inject(connect) it to the animal and hence it's autowired. We don't need to explicitly pass the reference of any bean for animal property as in Spring Basic Example.

Now the question arises what if it finds more than one bean which have type IAnimal as in our case "Dog" and "Cat" both are of type IAnimal.........It certainly would throw an error due to indecision for which bean to use something like - "org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [config.xml]: Unsatisfied dependency expressed through bean property 'animal': : No unique bean of type [pkg.IAnimal] is defined: expected single matching bean but found 2: [Dog, Cat]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [pkg.IAnimal] is defined: expected single matching bean but found 2: [Dog, Cat]".

If we would have used byName this problem won't have been there since two beans can't have same name(id) more on it later.........but we are not using that.
the solution is using an autowire-candidate property on beans as the bean "Dog" have autowire-candidate as false which simply means that this bean is not available for autowiring that simply means that only bean "Cat" is available for autowiring.
Indicates whether or not this bean should be considered when looking for matching candidates to satisfy another bean's autowiring requirements. Note that this does not affect explicit references by name, which will get resolved even if the specified bean is not marked as an autowire candidate.

Now when we run our test class it will give an output "Rahul has a  Cat with name Jejebel" 

It could be tedious to provide the kind of autowire for many beans specially when you are following a definite norm.......like you want all the beans to be autowired with "byName". Spring has provided the facility, all you need to do is in the configuration xml file set the default autowire as "byName". point to keep in mind that it will only work for one configuration file (you can have multiple) and not for the full application context. So you can organize all your same type autowired bean in one configuration file and set the default for that very xml file

test will again give you the same result .

But what If you need to have a default-autowire as "byType" in your configuration file but there are a few exceptions which needs to be autowired as "byName". Well in that case you can override the default autowiring just by specifically declaring it for the respective bean as "byName".

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd"
          default-autowire="byType">
   
<bean class="pkg.Person" id="person" p:name="Rahul">  
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

Not just that you still can use the (older style) property with ref attribute for passing the dependency even if you are using an autowire tag on it. Hence its flexible.

Let's talk about the kind of autowiring

What we saw in the earlier example was "byType". have a look at the whole bunch :-

 > no - no autowiring should be done on the particular bean and the dependency
must be passed explicitly through "ref" attribute.

 > byNameAttempts to match all properties of the autowired bean with beans
that have the same name (or ID) as the properties. Properties for which there’s
no matching bean will remain unwired.

 > byTypeAttempts to match all properties of the autowired bean with beans
whose types are assignable to the properties. Properties for which there’s no
matching bean will remain unwired.

 > constructorTries to match up a constructor of the autowired bean with
beans whose types are assignable to the constructor arguments.

 > autodetectAttempts to apply constructor autowiring first. If that fails,
byType will be tried.


We have already seen the example of autowire as "byType"

now let's see an example with autowire equal to "byName"

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="byName">  
</bean>
<bean class="pkg.Dog" id="animal" p:name="Doug"></bean>
<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

run the test again and it will output "Rahul has a  Dog with name Doug".

Thing to notice is that the name of bean "Dog" has been changed to "animal" on purpose, this way the the IAnimal type "animal" variable of class Person is mapped with the bean named "animal" and hence the dependency is autowired by Spring Framework according to the name.

Hence when the application context is created the framework search for the bean named "animal" and inject it into the bean "person" since the autowiring is "byName"

Now let's see the autowiring by constructor......to display this I would need to alter the class as I need to add a constructor to the Person class

the Person Class

public class Person {
 private String name;
 private IAnimal animal;
 
 public Person(IAnimal animal) {
  this.animal = animal;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public IAnimal getAnimal() {
  return animal;
 }
 public String toString() {
  // TODO Auto-generated method stub
  return name+" has a "+animal.toString();
 }

changes are that there are no setter for IAnimal type animal.......instead it is set with the constructor.....in the constructor the reference is passed as an argument.

config.xml

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<bean class="pkg.Person" id="person" p:name="Rahul" autowire="constructor">  
</bean>
<bean class="pkg.Dog" id="Dog" p:name="Doug" autowire-candidate="false"></bean>

<bean class="pkg.Cat" id="Cat" p:name="Jejebel">
</bean></beans>

Run the test and it will print "Rahul has a  Cat with name Jejebel".

Hence it is clear that when autowire is constructor.......Spring framework will search for the constructor with argument type as IAnimal and then will search for the bean type "IAnimal" and then passes that bean to set animal.

autowire-candidate="false" is used for the same reason as for it was used in autowire byType.

I am not providing any example of autowire as "autodetect" since this is nothing but a combination of autowire by constructor and byType respectively i.e. it looks for constructor with argument type and if there is none it looks for the type and searches the bean accordingly.


Well this is not all.....we still have "autowire with annotation" and autodiscover features....................but that in other post......

Thursday, March 8, 2012

Sticky columns/headers (Freeze pane) in tables through jQuery

Many times you have seen that the columns or headers freezes when you scroll horizontally or vertically respectively in a table. It looks rather cool but more than that its very useful hence nowhere you loses the track on any cell as which column and which header it belongs to irrespective of where the cell is in large table.
Let's see what can be done

the css


#resultTable{
    width:1000px;
    height:500px;
    clear:both;
    overflow:auto;
    position:relative;
}
.sticky-col-table{
    background-color: #eee;
    margin-left:0px !important;
}
.sticky-row-table {
    background-color: #eee;
    margin-top:0px !important;
}

.scrollTable{

    border:1px solid red;
    margin-top:5px;
    text-align:center;
}
.scrollTable td,.scrollTable th{
    width:60px;
    padding:5px;
    border:1px solid green;
}
now in the body let's put this structure


<div id="condDiv">
Columns : <input type="text" id="inputColumn" value="50"/> <br />
Rows : <input type="text" id="inputRow" value="50"/><br />
<input type="button" value="Create Table" onclick="return val_table();"/>
</div><br />
<div id="resultTable"  onscroll="movestickyColumn(this)">
<div id="sticky-column" style="position:absolute;display:none;"> </div>
<div id="sticky-row" style="position:absolute;display:none;"> </div>
</div>
let me describe it a bit in condDiv div I have two input elements where a person can provide the number of rows and columns for creating a dynamic table by clicking on the create Table button

the resultTable div is the div which will hold the dynamic table created and on scrolling of the div the function movestickyColumn(this) is called with passing the div object to it.

also note that it holds two empty and hidden div sticky-column and sticky-row (idea is to hold the frozen part of table in these divs).

Now the script part one by one, first for creating dynamic table we will have functions as follow

 validations -


function val_table(){
    var row= $('#condDiv #inputRow').val();
    var column = $('#condDiv #inputColumn').val();
    if(typeof row == "undefined" || row == null || row == "" || row <= 0 || isNaN(row) || typeof column == "undefined" || column == null || column == "" || column <= 0 || isNaN(column)){
        alert("Please provide valid positive value for rows and columns");
        return false;
        }
    else if(row>500 || column>500){
        alert("The column or row can not be more than 500");
        return false;
    }
    else{
        if($("#resultTable #myTable").length > 0){
            $("#resultTable #myTable").remove();
            }
        $("#resultTable").append(create_table(column,row));
        stickyColumnNew(2);
        stickyRow();
        }
}

first of all I am validating the number of row and columns provided in the input field, if it is I am calling three functions

for creating table


function create_table(column,row){
    var tableArray = [];
  
    var tableHead = [];
    var tableBody = [];
    tableHead.push("<thead><tr>");
    tableBody.push("<tbody>");
    var count = 0;
    for(ro=0; ro<row; ro++){  
        tableBody.push("<tr>");
            for(col=0; col<column; col++){
                if(ro==0){
                        tableHead.push("<th>Head "+(col+1)+"</th>")
                    }
                if((count%column) == 0){
                tableBody.push("<td> cell-"+(count+1)+" row-"+(ro+1)+"</td>");
                }
                else{
                    tableBody.push("<td> cell-"+(count+1)+"</td>");
                    }
                    count++;
                }
        }
    tableHead.push("</tr></thead>");
    tableBody.push("</tbody>");
    tableArray.push("<table id='myTable' class='scrollTable'>"+tableHead.join("")+tableBody.join("")+"</table>");
    return tableArray.join("");
}

then for getting the frozen columns to be formed in the sticky-column div, function stickyColumnNew(2) is called. note that I am passing 2 as an argument to freeze first 2 columns, you can pass more or less.


function stickyColumnNew(col) {
    $("#sticky-column").html('');
    // var trlength = $('table.table_sorter tbody tr').length;      
    var documentFragment =[];
    documentFragment.push('<table class="sticky-col-table scrollTable">');
    var docHead = [];
    docHead.push("<thead><tr>");
    var docBody = [];
    docBody.push("<tbody>")
    var count = 0;
    $("#myTable thead tr th").each(function(){
        if(count < col){
        docHead.push("<th style='height:"+$(this).outerHeight()+";'>"+$(this).html()+"</th>");  //use outerHeight() to get the height with padding, border and margin
        }
        count++;
    });
    docHead.push("</tr></thead>");
    $("#myTable tbody tr").each(function(){
    docBody.push("<tr>")
        if(col >= 1){
            docBody.push("<td style='height:"+$(this).find('td:first').outerHeight()+";'>"+$(this).find('td:first').html()+"</td>");
        }
        if(col >= 2){
        for(val=2; val<=col; val++){
            docBody.push("<td>"+$(this).find('td:nth-child('+val+')').html()+"</td>");
            }
        }
        docBody.push("</tr>")
    });
    docBody.push("</tbody>");
    documentFragment.push(docHead.join("")+docBody.join("")+'</table>');
    $("#sticky-column").append(documentFragment.join(''));  
    }

Basically I am creating a dummy table with only the 2 columns I have to freeze, It's cell should have the same height and content as the original table and I am simply putting that table in sticky-column div

In the same fashion I will create the table with dummy header with function stickyRow


function stickyRow() {
    $("#sticky-row").html('');
    // var trlength = $('table.table_sorter tbody tr').length;      
    var documentFragment =[];
    documentFragment.push('<table class="sticky-row-table scrollTable">');
    var docHead = [];
    docHead.push("<thead><tr>");
    $("#myTable thead tr th").each(function(){
      
        docHead.push("<th style='height:"+$(this).outerHeight()+";'><div style='width:"+$(this).width()+";'>"+$(this).html()+"</div></th>");  //use outerHeight() to get the height with padding, border and margin
      
    });
    docHead.push("</tr></thead>");
    documentFragment.push(docHead.join("")+'</table>');
    $("#sticky-row").append(documentFragment.join(''));
    }

Now the only part left is the movestickyColumn on the div


function movestickyColumn(tableDiv) {
    posX = tableDiv.scrollLeft;
    posY = tableDiv.scrollTop;
    if(posX > 50) {
        $('table.sticky-col-table,#sticky-column').css('display','block');
        $('table.sticky-col-table,#sticky-column').css('left',posX+'px');
    }
    else{
        $('table.sticky-col-table,#sticky-column').css('display','none');
        }
      
    if(posY > 50){
    console.log(posY);
        $('table.sticky-row-table,#sticky-row').css('display','block');
        $('table.sticky-row-table,#sticky-row').css('top',posY+'px');
    }
    else{
        $('table.sticky-row-table,#sticky-row').css('display','none');
    }  
}

So actually I am checking that as soon as the vertical or horizontal scroll crosses the 50px margin I am displaying the sticky-row and sticky-column divs respectively and accordingly.

feel free to play, customize or enhance upon it

hope it helps.

Try it here : -

[As far as I have checked there is some problem as in firefox header row width is not aligned and in chrome the columns height are not aligned. I guess some conflict with blogger css and css I am using. Trying to find the solution. However independently I have checked in both browser as working fine.]  



Columns :
Rows :