Thursday, 29 November 2012

HTTP Response Codes - Decision chart


This is a decision chart that I found on the internet, which shows how response codes are identified. Will be helpful if someone is trying to triage response codes issues.


Please Download this image and Zoom to see the details.






Java Annotations



What are Annotations?


Annotations was introduced in J2SE 5. These are tags that help us insert metadata into the source code so that they can be processed by tools.
In the Java programming language, an annotation is used like a modifier, and it is placed before the annotated item, without a semicolon.

 

 

Types of Annotations

Standard Annotation : Are applied to regular java classes, methods and statements
Meta Annotations:  Applied to annotation definition to describe the behavior of the annotation being declared and how it can be used.

Standard Annotations

These are the Annotations that are provided by Java to help us when writing our classes

 Meta Annotations

These are annotations used when defining an annotation
@Target : Elements of the Java class to which annotation is applicable
       @Retention :   When are the annotations loaded into the JVM
         @Inherited : meta-annotation applies only to annotations for classes.  
If an Inherited meta-annotation is pre sent on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class's superclass will automatically be queried for the annotation type

This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation.

       @Inherited Example:
@Target(ElementType.METHOD, ElementType.CLASS)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface  changelog
{
    String author() default "author" ;    // Annotation member
    String date();      // Annotation member
}
  
@changelog(author="vidhya", date="30/11/2012")
public  class superclass
{
}
  
public class subclass extends superclass
{
}

When subclass is queried for ChangeLog annotation, it will be successful as the changelog annotation is @inherited.
@Documented: If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.

 How to Define an Annotation and read it


Each annotation must be defined by an annotation interface. The methods of the interface  correspond to the elements of the annotation.

@Target(ElementType.METHOD, ElementType.CLASS)
@Retention(RetentionPolicy.RUNTIME)
Public @interface  ChangeLog
{
    String author();    // Annotation member
    String date();      // Annotation member
}

3 Types of annotation Definition

1. Marker - No Parameters, just used to denote a type. @Test in Junit 1.4 onwards
2. Single Value Annotation  - This contains just one value @name("Single Value")
3. Multiple parameter annotation - has many parameters @user(id="1234", name="user1")

       Example:

//Defined Annotation 
@ChangeLog(author="user1", date="10/10/2012") 
public class MyTest
{
 @ChangeLog(author="user2", date="20/08/2012")
 @TestCase 
 public void test1()
}


// The Annotation Reader
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AnnotationTest
{
  public static void main( String[] args ) throws Exception
  {
    //access the class annotation
    Class clazz = MyTest.class;
    System.out.println( clazz.getAnnotation(ChangeLog.class ) );
   
    //access the method annotation
    Method method = clazz.getMethod( "test1" );
    ChangeLog changelog = (ChangeLog) method.getAnnotation(ChangeLog.class);
    System.out.println("--- Changelog Author:"+changelog.author()");
  }
}

Tuesday, 20 November 2012

Change Timezone in linux

Changing timezone in linux can be done using the below steps. Timezone is set using a symbolic link at /etc/localtime.


1. Check Date
     [root@vidhya-dev-vm1 ~]# date
     Tue Nov 20 14:23:51 IST 2012


2. To see how the current localtime is set
     [root@vidhya-dev-vm1 ~]# ll /etc/localtime


     lrwxrwxrwx. 1 root root 39 Nov 20 11:47 /etc/localtime -> /usr/share/zoneinfo/right/Asia/Calcutta

3. Check all the timezones
     [root@vidhya-dev-vm1 ~]# ls /usr/share/zoneinfo/
     Africa      Brazil   Egypt    GB         Hongkong     Jamaica    MST      Portugal    ROK        WET
     America     Canada   Eire     GB-Eire    HST          Japan      MST7MDT  posix       Singapore  W-SU
     Antarctica  CET      EST      GMT        Iceland      Kwajalein  Navajo   posixrules  Turkey     zone.tab
     Arctic      Chile    EST5EDT  GMT0       Indian       Libya      NZ       PRC         UCT        Zulu
     Asia        CST6CDT  Etc      GMT-0      Iran         MET        NZ-CHAT  PST8PDT     Universal
     Atlantic    Cuba     Europe   GMT+0      iso3166.tab  Mexico     Pacific  right       US
     Australia   EET      Factory  Greenwich  Israel       Mideast    Poland   ROC         UTC


4. Backup existing timezone and link new timezone
     [root@vidhya-dev-vm1 ~]# mv /etc/localtime /root/localtime_bak
     [root@vidhya-dev-vm1 ~]# ln -sf /usr/share/zoneinfo/America/Denver /etc/localtime
     [root@vidhya-dev-vm1 ~]# date
     Tue Nov 20 01:56:59 MST 2012




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
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>

Simple implementation dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.6</version>
</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);
        logger.info("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-log4j12-1.7.2.jarLOG4j
slf4j-jdk14-1.7.2.jarUtil Logging
slf4j-simple-1.7.2.jarSIMPLE
slf4j-jcl-1.7.2.jarJCL
Diagram showing SLF4J binding and respecting jars
References:
FAQs:  http://slf4j.org/faq.html

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

 
CommandDescription
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
3013**1-5

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 hours' Executes 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

Encryption

java cipher.CipherUtils -encrypt abcd

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


Decryption

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

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


Code

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
    };//"thisIsASecretKey";

    public static String encrypt(String strToEncrypt)
    {
        try
        {
            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)
        {
           e.printStackTrace();
        }
        return null;

    }

    public static String decrypt(String strToDecrypt)
    {
        try
        {
            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)
        {
          e.printStackTrace();

        }
        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");
        options.addOption(help);
        options.addOption(encrypt);
        options.addOption(decrypt);
        try
        {
            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);
            }
            else
            {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("[-h] [-encrypt ]", options);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

Dependencies: 

Required: commons-cli 1.2 and commons-codec 1.7

Eclipse Maven project to run this

https://www.dropbox.com/s/rg8tfz1mf592b92/cipher-project.zip