Monday, October 31, 2011

Base64 encoding and decoding in Java

What is Base 64 Encoding Scheme?
Wiki says -
"Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding."

In simple terms Base64 encoding is a Binary to ASCII text conversion technique. Other such techniques available are quoted-printable, hexadecimal, BinHex, etc.

Binary to text encoding/decoding techniques are used when there is doubt that the transmission protocol/channel might not be capable of handling the non-textual data, best examples are email sent via MIME, Usenet. For example, many browser normally convert a space in URLs to %20D or such like characters and you might be in trouble if your server doesn't reconvert them but you can't possible crack down every such possible case. So better is use an encoding scheme that converts your data to text based characters.

your data => [ Base64 Encoding System ] => Textual Data
Image      => [ Base64 Encoding System ] => Image converted to text data

Is Base64 Encoding scheme a Encryption technique? NO, don't even think like an idiot. it is simply converting data from one form to another so that no modification happens due to the limitation in my transmission protocol/channel but there is not concept of cryptography involved at all.

How Base64Encoding works? Well, look at Wiki example, it is pretty much straight forward and clear.
Same example is given below as well..
Text content M a n
ASCII 77 97 110
Bit pattern 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0
Index 19 22 5 46
Base64-encoded T W F u

Since in Base64 you can have totally 64 different characters so your output can have characters only from the set given below:
A-Z, a-z, 0-9, +, /
Note: last two character might change depending on the implementation, for example, in variant Base64 with URL and Filename Safe Alphabet (RFC 4648 'base64url' encoding) -(hyphen) and _ (underscore) are used.

There are many variants of base64 are available, Some are listed below:
  1. RFC 1421
  2. RFC 2045- org.apache.commons.codec.binary.Base64 class does encoding and decoding as per this standard.
  3. RFC 3548
See more exhaustive list here(Wiki).

Last thing we will cover in theory is padding.. Now padding is adding extra bits/bytes/characters etc. when required. In Base64encoding also, padding is required some times.

When does padding is done in Base64Encoding and what characters are inserted for padding?
I will not explain how padding is done. this is clearly explained on Wiki site of Base64(See Relevant References) here. Padding is done when the number of bytes to encode is not divisible by 3, that is there are only one or two bytes of input for the last block. The '==' sequence indicates that the last group contained only 1 byte, and '=' indicates that it contained 2 bytes (you'll like that there are implementations available which doesn't require padding at all).

There are various implementations available as I mentioned earlier but being a good developer you should open your eyes and decide which implementation to choose depending on the requirement. Some Common applications of Base64 are given below:
  1. URL:
    • To encode the URL query parameters
    • To encode data in hidden form fields
    • Just to obfuscate the URL data
  2. File names: Variant Modified Base64 for file name uses '-' instead of '/', because Unix and Windows file names cannot contain '/'.
Checkout the other applications also.

Let us jump to Base64 Encoding in Java: There are many implementations available. I will list them down first (not all):
  • Apache commons: org.apache.commons.codec.binary.Base64. Usage of this implementation is recommended.
  • Sun misc package: sun.misc.BASE64Decoder. Avoid using it as misc package is never officially released by SUN, this is one thing. Another thing is Oracle might be tempted to remove all packages with names having SUN and you see that code suddenly stopped working in future releases of Java.
  • Base64 class shipped with JAXB framework. Use this if your project is already using JAXB.
  • javax.mail.internet.MimeUtility: This class also has encode and decode methods and can do the job for you. But use them when your code is dealing with emails as this implementation follows MIME protocol guidelines.
There are many others also available. You can write your own as well (all the best if you are doing.)

Now it's time for demo code:
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

 * @author java-espresso
 * This class has two methods one encodes a string in Base64Encoding 
 * and other decodes the same.
public class CommonUtil {

 public static String base64Encode(String stringToEncode){
  byte [] stringToEncodeBytes = stringToEncode.getBytes();
  return Base64.encodeBase64String(stringToEncodeBytes);
 public static String base64Decode(String stringToDecode){
  byte [] decodedBytes = Base64.decodeBase64(stringToDecode);
  return new String(decodedBytes);
Test class for the above code:
public class TestBase64 {

  * @param args
 public static void main(String[] args) {
  String testString1 = "test String"; //Total bytes=11 divide by 3  and 2 bytes are in remainder so '=' is appended in the encoded string
  String testString2 = "TestString"; //Total bytes=10 divide by 3  and 1 bytes are in remainder so '==' is appended in the encoded string
  String testString3 = "Test string."; // Total bytes=12 divide by 3  and 0 bytes are in remainder so nothing is appended
  String encoded1= CommonUtil.base64Encode(testString1);
  String encoded2= CommonUtil.base64Encode(testString2);
  String encoded3= CommonUtil.base64Encode(testString3);
  System.out.println("====== Encoded Strings =======================================");
  System.out.println(testString1+" > Encoded > "+encoded1);
  System.out.println(testString2+" > Encoded > "+encoded2);
  System.out.println(testString3+" > Encoded > "+encoded3);
  System.out.println("====== Decoded Strings =======================================");
  System.out.println(encoded1+" > Decoded > "+CommonUtil.base64Decode(encoded1));
  System.out.println(encoded2+" > Decoded > "+CommonUtil.base64Decode(encoded2));
  System.out.println(encoded3+" > Decoded > "+CommonUtil.base64Decode(encoded3));

output on executing the above code:
====== Encoded Strings =======================================
test String > Encoded > dGVzdCBTdHJpbmc=
TestString > Encoded > VGVzdFN0cmluZw==
Test string. > Encoded > VGVzdCBzdHJpbmcu
====== Decoded Strings =======================================
dGVzdCBTdHJpbmc= > Decoded > test String
VGVzdFN0cmluZw== > Decoded > TestString
VGVzdCBzdHJpbmcu > Decoded > Test string.
Please find the source of the application attached here.
Related Article

Relevant References

Thursday, October 13, 2011

Threads Part1: An introduction

A thread in computer science is short for a thread of execution. A thread is a single sequential flow of control within a program (i.e., process). Threads are a way for a process to split itself into multiple simultaneously running tasks. Threads are lightweight processes because they run within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment. Threads are similar to process, but differ in the way that they share resources.
Java virtual machine can support many threads of execution at once. These threads independently execute code that operates on values and objects residing in a shared main memory. Threads may be supported by having many hardware processors (where threads are executed on separate processors), by time-slicing a single hardware processor (where a single processor switches between different threads giving the illusion that they are all executing at the same time), or by time-slicing many hardware processors. There is always at least one thread within every Java program: the main() method of the class which was given as a parameter to the Java interpreter.

Difference between a user thread and daemon thread. The daemon threads purpose is to give services to the user threads which are created by the user to perform the long running task (mostly for not blocking the ui or to do something in background ).The main() method of the application is a user thread. Threads created by a user are user thread ,you can also create the Daemon thread by explicitly calling the setDaemon(true) on a Thread object.One important point here is that setDaemon() method must be called before the thread is started .Once all the user threads are terminated then only JVM will terminate not in the other way if there are Daemon threads running but no user threads then JVM will close the running application .There should be atleast one user thread(main thread is a user thread )running for the JVM not to close the application.

There are two ways of implementing threading in JAVA
1) By extending java.lang.Thread class, or
2) By implementing java.lang.Runnable interface.
Before we go into implementation details I just like to cover when we use thread? so we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.
Actually public void run () method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically.

//implementing Thread by extending Thread class
class MyThread extends Thread{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());

//implementing Thread by implementing Runnable interface
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
//starting Thread
Thread mythread = new MyThread();
Thread myrunnable = new Thread(new MyRunnable(),"T2");

Thread will not start until you call the start() method of java.lang.Thread class. When we call start () method Java Virtual machine execute run () method of that Thread class into separate Thread other than calling thread. Anybody guess what will happen if we call the run() method directly instead of calling start() method ?
run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start () method twice in same Thread object e.g

mythread.start();// this line will throw IllegalThreadStateException

Difference between mythread.start() &
• If we call mythread.start(), it will create a new Thread and that thread is responsible for execution of run().
• If we call, no new thread will create, the main thread only will execute run(), just like a normal method.
• In case of mythread.start() output we can’t expect
• In case of output first it ll run the code in the run function in the main thread .
Thread class start():-

public void start()
1. Registering our thread with the thread scheduler then only thread scheduler allocate CPU and memory type of resources for this new thread also.
2. calls run() // you can think of it as a call back invoked by the jvm

The thread is in the "new" state, once it is constructed. In this state, it is merely an object in the heap, without any system resources allocated for execution. From the "new" state, the only thing you can do is to invoke the start() method, which puts the thread into the "runnable" state. Calling any method besides the start() will trigger an IllegalThreadStateException.

The start() method allocates the system resources necessary to execute the thread, schedules the thread to be run, and calls back the run() once it is scheduled. This put the thread into the "runnable" state. However, most computers have a single CPU and time-slice the CPU to support multithreading. Hence, in the "runnable" state, the thread may be running or waiting for its turn of the CPU time.
The thread enters the "not-runnable" state when one of these events occurs:
The sleep() method is called to suspend the thread for a specified amount of time and yield control to the other threads.

The wait() method is called to wait for a specific condition to be satisfied.
The thread is blocked and waiting for an I/O operation to be completed.
For the "non-runnable" state, the thread becomes "runnable" again:
If the thread was put to sleep, the specified sleep time expired or the sleep was interrupted via a call to the interrupt() method.
If the thread was put to wait via wait(), its notify() or notifyAll() method was invoked to inform the waiting thread that the specified condition had been fulfilled and the wait was over.
If the thread was blocked for an I/O operation, the I/O operation has been completed.
A thread is in a "dead" state, only when the run() method terminates naturally and exits.

The method isAlive() can be used to test whether the thread is alive. isAlive() returns false if the thread is "new" or "dead". It returns true if the thread is "runnable" or "not-runnable".
JDK 1.5 introduces a new Thread.getState() method. This method returns an enum of type Thread.State, which takes a constant of {NEW, BLOCKED, RUNNABLE, TERMINATED, WAITING}.
NEW: the thread has not yet started.
BLOCKED: the thread is blocked waiting for a monitor lock.
TIMED_WAITING: the thread is waiting with a specified waiting time.

Methods in Thread Class
The methods available in Thread class include:
public void start(): Begin a new thread. JVM calls back the run() method of this class. The current thread continues.
public void run(): to specify the execution flow of the new thread. When run() completes, the thread terminates.
public static sleep(long millis) throws InterruptedException: Temporarily suspend the thread and yield control to other thread for the given milliseconds. Method sleep() is thread-safe as it does not release its monitors. The method throws InterruptedException if it is awaken before the specified timing (via a call to interrupt() method). This is a static method and commonly used to pause the current thread so that the other threads can have a chance to execute. For example:
try {
// suspend for 0.1 sec and give other threads a chance to run
} catch (InterruptedException ex) {}
public void interrupt(): Interrupt the sleep() method.
public boolean isAlive(): Return false if the thread is new or dead. Returns true if the thread is "runnable" or "not runnable".
public void setPriority(int p): Set the priority-level of the thread, which is implementation dependent.
public void yield(): suspend the current thread to allow other threads to run.
The stop(), suspend(), and resume() methods have been deprecated in JDK 1.4, because they are not thread-safe, due to the release of monitors. See JDK API documentation for more discussion.

What is the difference between implementing Runnable and extending Thread?
One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same object instance.
"Which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.
Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface.

public class Espresso {
public static void main (String[] args) {
Runner r = new Runner();

Thread t1 = new Thread(r, "Thread A");
Thread t2 = new Thread(r, "Thread B");
Thread s1 = new Mythread("Thread C");
Thread s2 = new Mythread("Thread D");



class Runner implements Runnable {
private int counter;
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
catch(InterruptedException e) {

class Mythread extends Thread {
private int counter;
Mythread(String name) {
public void run() {
try {
for (int i = 0; i != 2; i++) {
System.out.println(Thread.currentThread().getName() + ": "
+ counter++);
catch(InterruptedException e) {

Thread A: 0
Thread B: 1
Thread C: 0
Thread D: 0
Thread C: 1
Thread B: 2
Thread A: 3
Thread D: 1

Tuesday, October 11, 2011

JQuery Tutorial 1: Showing alert popup

Let me put the code first then we will do the post mortem

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src=""></script>
<input type="button" value="Trigger Alert" id="btn_trig">
<script type="text/javascript">
/* $('#btn_trig') gives reference to the html element whose id is passed,
 * similiar to getElementById() function. On that reference a callback function is defined
 *  syntax of callback functions is like this event( function(){ //thing you want to do on event happening}). Callback functions are called when event happens.
 alert("Hello World!");

Try for yourself: