Monday, 29 October 2012

Why SLF4j

SLF4J -   Simple Logging Framework for Java
SLF4j is a wrapper for various Logging Frameworks. The Users can plugin their logging framework for their environment without much changes.  This library is most useful when developing  frameworks for other applications to use.  The framework provides logging mechanism with slf4j enabled, then whomever uses the framework can plugin their logging framework of their choice without much hurdle.

How to plugin SLF4j using Maven
You need to add slf4j-api jar to the dependency. If you have no choice of logging framework to enable, just add  slf4j-simple jar which is  the Simple logging Implementation -  Only messages of level INFO and higher are printed. This binding may be useful in the context of small applications.

The SLF4j api dependency

Simple implementation dependency

Below is the sample code to test the logging

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerTest
    public static void main(String args[])
        Logger logger = LoggerFactory.getLogger(LoggerTest.class);"Testing slf4j");

Output when you run the above code
1 [main] INFO test.LoggerTest - Testing slf4j 
How is Logback Special to slf4j?
Logback has a direct implementation of Slf4j. If we want to plug this in,  a slf4j wrapper jar file is not needed.  Logback's ch.qos.logback.classic.Logger class is a direct implementation of SLF4J's org.slf4j.Logger interface. Thus, using SLF4J in conjunction with logback involves strictly zero memory and computational overhead. 
Famous slf4j binding dependencies
To bind the logging frameworks we may have to include the slf4j binding dependencies to plugin. If you have multiple plugins, the 1st in the order of compiler dependency is picked up.   The good thing about slf4j is, it resolvs the logging plugin  at compile time.  

Below are the slf4j wrappers fof different logger
slf4j-jdk14-1.7.2.jarUtil Logging
Diagram showing SLF4J binding and respecting jars

Wednesday, 24 October 2012

Video record sessions with ScreenRecorder

Why did I need Video Recording?
When I started my work at HP. I was asked to lead an effort to revamp a 7 year old legacy Product. Being the first one to join the team and the rest of the members to join in couple of more months, my responsibility was to understand the complete system, mentor the new joiners and complete the whole revamp project in 6 months. 

The Product had a very complex architecture with little documentation. Sorry to say, even if we could find something, it was in spanish :-( The only person who knew how it works was the architect of the product.  

We had knowledge transition sessions scheduled everyday for the first month.  During the 1st transition session, I realized the complexity of the system, and the Architect was sharing his knowledge as 10 GBPS speed :-). Obviously I was completely lost, and there was no time for creating the documentation from scratch. So, I decided to record all these sessions from then on, if I had to digest the 10 GBPS information and pass it along to the team.

I tried few products to solve my purpose, and finally settled with ScreenRecorder  UtilityOnlineMarch092009_03.exe  which I found it very useful till now.

When you install the above exe, this will extract 32bit and 64bit versions of screenRecorder. You may have to pick the right version and install the actual screen recorder

How to record using screen Recorder?

Start screenrecorder, then choose the window you want to record, and select the Audio check box whether you want to record the Audio from (Line-In/System's Mic)

Then pick the file to save your video as wmv.

Now, click start and you will be recording your choice of window with or without audio.

How to record audio from a phone?

I used a small mic and dropped it near the phone speaker and other end to the line-in of my laptop.  Recently I have seen people using Radioshack converters to connect from Phone to the Line-in of your computer.

How did it help us?
This tool saved lot of my time and the entire team was referring to those videos whenever we had doubts. This was one of the legacy that we left behind for the future team members of the Product.

Monday, 22 October 2012

CRON - Scheduled jobs in unix/linux

What is CRON?
Cron is a unix/linux utlity that is used to schedule tasks that run at specific intervals. The tasks that are scheduled are called cron jobs.

What is crontab? 

This is file which contains a table of scheduled jobs that drives the cron.
Multiple cron jobs can be schedule in the crontab. Ideally, each line in the file contains a cronjob information.

Crontab Commands

crontab -e edit or create a crontab file
crontab -i list the crontab contents
crontab -r remove the crontab settings
crontab -v Last time the crontab was changed

Crontab Syntax

Examples of crontab

MinHoursDayMonthDay of weekCommandDescription
3013***echo 'Executes at 1:30 PM everyday'Executes at 1:30 PM everyday
301311*echo 'Executes on Jan 01 at 1:30 PM' Executes on Jan 01 at 1:30 PM
30131**echo 'Executes on 1st of every month at 1:30 PM' Executes on 1st of every month at 1:30 PM

Executes on all weekdays(Monday-Friday) at 1:30 PMExecutes on 01 of every month at 1:30 PM
*/5****echo 'Executes every 5 mins' Executes every 5 mins
**/5***echo 'Executes every 5 hoursExecutes every 5 hours

Restart cron in Linux 

In case the timezone is changed, the CRON can be restarted using the following command

/etc/init.d/crond restart

Friday, 19 October 2012

Encryption and Decryption using AES Algorithm in JAVA

Encryption and Decryption

Encryption is the process of converting plaintext to cipher-text (had to understand) by applying mathematical transformations.  These transformations are known as encryption algorithms and require an encryption key.

Decryption is the reverse process of getting back the original data from the cipher-text using a decryption key.  In Symmetric cryptology- The encryption key and the decryption key could be the same as in symmetric or secret key cryptography, The key can different as in asymmetric or public key cryptography. 

Types of cryptography

Symmetric cryptography uses the same secret (private) key to encrypt and decrypt its data
Symmetric requires that the secret key be known by the party encrypting the data and the party decrypting the data.

Asymmetric Cryptography uses both a public and private key.  Asymmetric allows for distribution of your public key to anyone. Using the key they can encrypt the data they want to send securely and then it can only be decoded by the person having the private key

Symmetric Algorithms
Common  Algorithms

DES (Data Encryption Standard)Old Crypto algorithm. 64 Bits, 56 are effectively used, easy to break.3DES - derived from DES, works by cascading 3 instances of DES. This is slow
3DESderived from DES, works by cascading 3 instances of DES. This is slow
AES (Advanced Encryption Standard)Successor of DES. Accepts 128, 192, 256 bits. When in doubt use AES. This is supported after JDK 1.4 onwards

Symmetric key encryption/decryption uses a secret key during the process.   A String encrypted with a secret key cannot be decrypted using another secret key.   This is more effective if both the parties keep the key secret.

In our example we will be using a AES Algorithm with AES - 128 , AES has a fixed block size of 128 bits. We will be using a password based secret key. In the below table you will see the code comparison  of how encryption and decryption is easily done

Encryption CodeDecryption Code
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

 String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
return encryptedString;
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
return decryptedString;
Below is an example standalone java class which can generate a encrypted string, and decrypt a given string.  The secret-key used for encryption/decryption is "thisIsASecretKey"- converted to bytes.  The encrypted string at last encoded using Base64.encodeBase64String that gives an ascii string.  During the decryption, the ascii base64encoded string  is decoded using Base64.decodeBase64 and then decrypted using cipher.doFinal().

How to run the program


java cipher.CipherUtils -encrypt abcd

String to Encrypt : abcd
Encrypted : 0ualDZ4X/FUDjmrqLWROyw==


java cipher.CipherUtils -decrypt 0ualDZ4X/FUDjmrqLWROyw==

String To Decrypt : 0ualDZ4X/FUDjmrqLWROyw==
Decrypted : abcd


package cipher;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.codec.binary.Base64;

public class CipherUtils

    private static byte[] key = {
            0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79

    public static String encrypt(String strToEncrypt)
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            final String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
            return encryptedString;
        catch (Exception e)
        return null;


    public static String decrypt(String strToDecrypt)
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
            return decryptedString;
        catch (Exception e)

        return null;

    public static void main(String args[])

        CommandLineParser parser = new PosixParser();
        Options options = new Options();
        Option help = new Option("help", "Display help");
        Option encrypt = new Option("encrypt", true, " - string to encrypt");
        Option decrypt = new Option("decrypt", true, " - string to decrypt");
            CommandLine cmd = parser.parse(options, args);
            if (cmd.hasOption("encrypt"))
                final String strToEncrypt = cmd.getOptionValue("encrypt");
                final String encryptedStr = CipherUtils.encrypt(strToEncrypt.trim());
                System.out.println("String to Encrypt : " + strToEncrypt);
                System.out.println("Encrypted : " + encryptedStr);
            else if (cmd.hasOption("decrypt"))
                final String strToDecrypt = cmd.getOptionValue("decrypt");
                final String decryptedStr = CipherUtils.decrypt(strToDecrypt.trim());
                System.out.println("String To Decrypt : " + strToDecrypt);
                System.out.println("Decrypted : " + decryptedStr);
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("[-h] [-encrypt ]", options);
        catch (Exception e)



Required: commons-cli 1.2 and commons-codec 1.7

Eclipse Maven project to run this

Sunday, 14 October 2012

Good Programming - Crafting the code


Coding is an art. It has to be "Crafted with Passion".
Good Programming stems from your attitude. It lies in understanding the approach and always wanting to write the best software you can. Professional programmers take responsibility for the code they write. Programs should be written well, well structured and easy to read. It is not just about laziness, ignorance or lack of time but is related to skills, intelligence, aptitude and passion for the job

"Programs must be written for people to read, and only incidentally for machines to execute"
Abelson & Sussman

Characteristics of a Good Programmer
  • Passionate - Good Programmers have the tendency to write code even if they are not paid for it.
  • Progressive learning - Technology and tools advances daily. What a good programmer does is learn. He/She is open to self learn and rapidly improve his/her proficiency in their skill.
  • Master in few with breath of Technology Knowledge-  As good programmers love to learn as result of passion, it is fun in trying their hands on variety of technologies and programming languages. Ultimately they will end up as experts in few of them.
  • Smart  and Intelligent - Their breath of knowledge helps them in having great coversations on variety of topics.