Saturday, November 12, 2011

Blackberry backup Parser

I have published this extractor to help people to develop both open source and commercial solution which involves reading Blackberry backup extraction. This extractor retrieves BB phone backups (Contacts and SMS) into CSV file. Share your comments, feedback and Questions, I'm listening :-)

To download the binary and source, please access-

Saturday, October 15, 2011

Its about Bytes in Java

I have seen people struggle in handling data in Java when it reaches at the byte level. As Java doesn't support any concept of Un-signed data type, so it makes things more complex. So thought lets share my understanding.

Java stores negative values in 2's complement format and to get absolute value of any negative number you need to type cast variable with higher byte value datatype. In simple word, to get absolute value of -ve byte data type variable it need to type cast/upgrade to some other date type (e.g. short/int) having more number of bytes and.
Example,
byte mSample = 142;
If you print its value, it will show -114. So, why does the JVM shows -114 ?
Binary of 142 : 1 0 0 0 1 1 1 0. The left most bit is Signed bit, so JVM considers this number as -ve value and converts it into 2's Complement, which means, 0 1 1 1 0 0 1 0 = - 114. So, its simple, right ?
So, to get absolute value of mSample, we need to type cast it to higher byte enabled data type e.g. int.
int abmSample = 0xFF & (int) mSample;
Why do I need to do AND operation with 0xFF ?
0xFF makes remaining bits apart from first 1 byte value to 0. So, you get absolute value i.e. 142.

I have written an utility Class ByteUtils.java which provides methods to convert byte array to Hexadecimal values, Integers and Long. This sample also considers byte ordering i.e. Little and Big endian. Hope this small write up helps people in understanding byte level data handling in Java.

Thursday, October 6, 2011

Excel Column Sequence Algorithm

One of my friend came up with a question..."How do you find out the sequence of MS Excel column ?", lets put this in an another way, If I tell you one Excel Sheet column sequence e.g. ABA how do you find out the index of the column e.g. AA is 27th column, AB is 28th column.

So, I thought to put this as an Algo; with this if you have any sequence, you will be able to compute the column number-

Column Number = Alphabet Seq Number (right most) + Alphabet Seq Number * 26 + Alphabet Seq Number * (26*26) + .......... + Alphabet Seq Number (left most) * (p-1 times multiplication of 26)

Where,
Alphabet Seq Number = 1-26, (A = 1 and Z = 26)
p = number of Alphabets in the Column Sequence e.g. for "ABC", p = 3. Here  is C at position 1, B at 2 and A at 3.

So, with the above formula, Column number for ABC = C + B * 26 + A * (26 * 26)  
= 3 + 2 * 26 + 1* (26*26) = 731

So, what about doing the reverse i.e. generate the sequence from column number. To do this, we need to divide the number by 26 and consider the reminders to pick the Alphabet. The sequence of reminders that we get from 731 are 3 (C), 2(B), 1(A), so the Column sequence is "ABC" (last reminder value at the first).

Please find the CalculateExcelColumn.java to generate Column sequence from Column number. Hope the Algo helps...:-)

Thursday, August 4, 2011

What WebView can do in Android ?

Well, the answer is, WebView can help to create wonderful Mobile UI without the pain of Android's Layouts. Sometime simple is not that simple! Before even I know about WebView, to me Android's XML based UI option was the simplest in the world. But Android can go beyond that....It provides the amazing WebView which lets you to develop UI in World's most simple language i.e. HTML/JavaScript. So, simple can be that simple..what do you think :-)

As I'll move on and start describing more about WebView, probably few questions already started hovering....How do I call my Android Activity or Java classes from my WebView ? or How do I call a JavaScript method from my Android Activity ? These are valid questions and answer is, both of them are possible with WebView and I'll explain both of them. So, its cool right!!

WebView is the same programming construct which runs behind Android's browser. So "ideally" you can run everything on WebView which you can on Android browser i.e. Flash, HTML. JavaScript, JQuery, Mobile JQuery etc. It helps in-terms of reducing the development effort while replicating UI of Web platform to Mobile.

Let's start with coding. WebView is a sub-class of View so you can set an instance of it on the screen by calling setContentView() of your Activity class. I'll first create and initialize an WebView instance-



Now set the HTML/Flash Web resource to WebView (local stored in asset folder or remote resource hosted on Server)-

There will be a loading delay depending upon whether it is a Local or Server resource, moreover there will be rendering delay as well. To know when page loading is over, we can set callbacks-


While WebView process the page, you can show helpful progress dialog to users. shouldOverrideUrlLoading() method makes sure all HREF link clicks gets resolved by WebView instead of launching Android Browser.

Now, you can set the mWebView on the screen and that's it!!

Lets do a bit more interesting stuff. I'll put a button on my HTML page which will Call a JavaScript method and that method indirectly Call a Java Method. Java method will show a progress dialog and then call another JavaScript method to update text of some HTML DIV element. Please find the attached sample code, AndroWebView.zip.

To make a Java Class's methods accessible to JavaScript code, we need to register an instance of the class with a constant name which we'll refer as JavaScript object-



To call methods of this Java class from JavaScript, you first need to check whether it supports "native_java" object and if it supports, you can call its methods (getDataFromJava() is defined in JSImp.java),

Here one thing you need to keep in mind while calling Activity/View instance from JavaScript; JavaScript/WebView runs in a different thread, so any Activity/View specific calls should be performed using Handler running on UI Thread.

Now, lets check how to call a JavaScript method from Java. It is simple, but you need to just make sure, you call a JavaScript method only when page loading is done by WebView.


There are few limitations like, you can only exchange primitive data type values from JavaScript-to-Java and vice verse. So, to avoid this limitation, you can convert complex object structure to JSON string and pass them as String argument between JS-Java.

With the latest JavaScript frameworks like JQuery Mobile you can create fancy Mobile UI using just HTML (or HTML5) and JavaScript. This reduces significantly the development effort and the complexity of UI layouts.
So, next time when you start to design Android UI, you can give a thought to create that in HTML/JavaScript and with WebView....:-) with this I'm signing off and hope it helps....

Monday, June 13, 2011

Multi-Threaded Execution Control

In this tutorial I'll explain mechanism to control multiple thread execution sequence. To explain the concept, I'll consider a sample execution scenario where a set of operations execute in sequence, but each operation runs in different threads. Lets consider content download scenario, Login to the Content Server -> Browse Content -> Download Content. 3 Threads will execute each of these operations and these operations are inter dependent and will follow the order, login - browse - download.

Let's jump into the implementation, we'll have Synchronized blocks for 3 different functions and we'll do thread execution control using wait()/notifyAll() methods. To determine the order of execution we'll use one variable state which can hold 3 different values- Login, Browse and Download.

Synchronization blocks will be locked with a Private Object lock. This is more effective and fail proof then using the this as Object lock. All 3 functions will share same lock, so any thread can execute only one function at a time.
When one thread is done with its execution, it needs to notify all other threads by calling lock.notifyAll() and release the lock by calling lock.wait(). Apart from this the currently executing thread should also change the value of state which will indicate who will be the next thread or function to execute.
I have written 3 functions, login(), browse() and download() as part of Operation class and all these 3 functions share lock of same private object. MyThread class is a thread implementation and there are 3 thread instances, each executes only one of the 3 functions.

Output of the following code-

login....
login.....[DONE]
browse....
browse.....[DONE]
download....
download.....[DONE]
login....
login.....[DONE]
browse....
browse.....[DONE]
download....
download.....[DONE]


package com.ds.thread;

/**
 * Multi-Threaded sequential execution control.
 *
 * @author prasanta
 *
 */
public class SequentialThreadAccess {

      /**
       * Operation class executes 3 different functions- Login -> Browse -> Download
       * Note:
       * Make sure you run wait() and notifyAll() on the Object, whose lock
       * you are using. In this case, Object lock, so
       * lock.wait() and lock.notifyAll().
       *
       * @author prasanta
       *
       */
      private static class Operation {
           
            public static final int LOGIN = 0;
            public static final int BROWSE = 1;
            public static final int DOOWNLOAD = 2;
           
            int state = LOGIN;
           
            // My Lock object
            private final Object lock = new Object();
           
            public void login()
            {
                  synchronized (lock) {
                        while(true){
                              while(state != LOGIN){
                                    try {
                                          // Release the Lock
                                          lock.wait();
                                    } catch (InterruptedException e) {
                                          e.printStackTrace();
                                    }
                              }
                             
                              System.out.println("login....");
                              try{
                                    // some processing delay
                                    Thread.sleep(1000);
                              }catch(Exception ex){}
                              System.out.println("login.....[DONE]");
                             
                             
                              // I'm done, let Browsing to run
                              state = BROWSE;
                              lock.notifyAll();
                        }
                  }// Synchronized Section- END
            }
           
            public void browse()
            {
                  synchronized (lock) {
                        while(true){
                              while(state != BROWSE){
                                    try {
                                          // Release the Lock
                                          lock.wait();
                                    } catch (InterruptedException e) {
                                          e.printStackTrace();
                                    }
                              }
                             
                              System.out.println("browse....");
                              try{
                                    // some processing delay
                                    Thread.sleep(1000);
                              }catch(Exception ex){}
                              System.out.println("browse.....[DONE]");
                             
                              state = Operation.DOOWNLOAD;
                              // I'm done, let Downloading to run
                              lock.notifyAll();
                        }
                       
                  }// Synchronized Section- END
            }
           
            public void download()
            {
                  synchronized (lock) {
                        while(true){
                              while(state != DOOWNLOAD){
                                    try {
                                          // Release the Lock
                                          lock.wait();
                                    } catch (InterruptedException e) {
                                          e.printStackTrace();
                                    }
                              }
                             
                              System.out.println("download....");
                              try{
                                    // some processing delay
                                    Thread.sleep(1000);
                              }catch(Exception ex){}
                              System.out.println("download.....[DONE]");
                             
                              state = LOGIN;
                              // I'm done, let Login to run
                              lock.notifyAll();
                        }
                  }// Synchronized Section- END
            }
      }
     
      public static class MyThread extends Thread
      {
            int opCode = Operation.LOGIN;
            Operation op;
           
            public MyThread(String name, int opCode, Operation op){
                  super(name);
                  this.opCode = opCode;
                  this.op = op;
            }
           
            public void run(){
                  while(true){
                        switch(opCode){
                        case Operation.LOGIN:
                              op.login();
                        break;
                        case Operation.BROWSE:
                              op.browse();
                        break;
                        case Operation.DOOWNLOAD:
                              op.download();
                        break;
                        }
                  }
            }
      }
      public static void main(String[] args){
            //fiboSeq(15);
           
            Operation op = new Operation();
           
            MyThread th1 = new MyThread("TH1", Operation.LOGIN, op);
            MyThread th2 = new MyThread("TH2", Operation.BROWSE, op);
            MyThread th3 = new MyThread("TH3", Operation.DOOWNLOAD, op);
           
            th1.start();
            th2.start();
            th3.start();
      }
}