Pages

Thursday, May 3, 2012

Handling exceptions in ExtJS

Problem Statement: I struggled almost for a week to fix exception handling in ExtJS. The problem is when I make an AJAX call or make any asynchronous server side call, I was not able to read exact exception message thrown by server. I saw different ways to implement exception listeners in ExtJS but most of them didn't work for me.

Problem Solution: This is what I am using to handle exceptions in ExtJS.

var reportProxy = new Ext.data.HttpProxy({
    url : 'myReportURL',  // web URL
    method : 'post',      // HTTP method
    timeout : 180000,     // request timeout
    listeners : {         // configure listener
        exception : function(proxy, type, action, options,
                response, arg) {
            // this block is reached on any exception
            if (!response.isTimeout) {
                // check if response didn't timed out
                Ext.Msg.show({
                    title : '',
                    msg : "Oops !! There is some Internal Server Error.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            } else {
                // this block is called on response timeout
                Ext.Msg.show({
                    title : '',
                    msg : "Its taking too long. Response timed out.",
                    buttons : Ext.Msg.OK,
                    icon : Ext.MessageBox.INFO
                });
            }
        }
    }
});

Note the syntax for defining exception block, the function signature is important. I have seen different signatures for this function but this is the one that worked for me.

Tuesday, May 1, 2012

Features of Java 7


Initially Java 7 was proposed to have many new features such as
  1. Modularization
  2. Anonymous methods (closures)
  3. Simplifications in generics implementations
  4. Enhanced exception handling
  5. Strings in switch statements
  6. Dynamic languages support
  7. Simplified initialization of collections
  8. Elvis operators
  9. API changes
Out of above listed features a few were dropped from actual release of Java 7 and they are supposed to be released as part of Java 8. And they are 
  1. Anonymous methods (closures)
  2. Simplified initialization of collections
  3. Elvis operators

New features in Java 7
  1. Change in language syntax
    • Constants
      • Binary constants
      • Underscore in numeric constants
    • Strings in switch statement
    • Extended try catch
    • Multi-catch
    • Diamond operator
  2. Better support of dynamic languages
    • New bytecode  instruction
    • New dynamic linkage mechanism
  3. JDBC 4.1
    • try-with-resources statement
    • RowSet 1.1
  4. NIO 2
    • Comes with a set of views
    • New abstract class java.nio.file.Path
    • Notion of metadata
  5. Updates in Swing API
  6. Unicode 6
  7. Updates in concurrency package
  8. Automatic resource closure

Monday, April 30, 2012

Object Oriented Analysis & Design

Why object orientation ?
  1. Higher level of abstraction
  2. Seamless transition among different phases of software development
  3. Encouragement of good programming techniques
  4. Promotion of reusability


Unified Approach (UA)
Based on the Booch, Rumbaugh and Jacobson methodologies.
  1. Use case driven development
  2. Utilize the unified modeling language (UML) for modeling
  3. Object-oriented analysis
  4. Object-oriented design
  5. Repositories of reusable classes and maximum reuse
  6. The layered approach
  7. Incremental development and prototyping
  8. Continuous testing 


Objects
  1. The term object was first formally used in the Simula language.
  2. Object have properties or attributes and behaviors.
  3. Objects respond to messages. Messages essentially are nonspecific functional calls. For example, we would send a draw to a chart  when we want the chart to draw itself. A message is different from a subroutine call, since different objects can respond to same message in different ways.
Objects respond to messages according to methods defined in its class. Message is the instruction and method is implementation.


Object relationships
Association: Represents the relationship between objects and classes.
  1. Associations are bidirectional - that means they can be traversed in both directions, perhaps with different connotations.
  2. Cardinality - specifies how many instances of one class may relate to a single instance of an associated class.
Dependency: One class is dependent on other.

Generalization: One class is generalized from other. This is typically known as class inheritance in object oriented programming terms.

Realization: This brings interfaces into consideration.

Sunday, April 29, 2012

Web 3.0

The future of web is going to be lot more powerful then we see today. People already started calling it as Web 3.0. Web 3.0 is all about building the semantic web and the future of web apps is termed as "Semantic Web Applications".

There are two possible aspects to the future of Web. The first is Social networking and people centric web and the second would be Semantic nature of the web. Today's web has got hell lot of information but web by itself do not understand the relationship between the data it has got. The web technology of today focuses more on how web pages are displayed and what content is displayed, rather than on the content itself. So whatever web does today, it does with the help of human intervention, it needs someone to provide ample guidance on what to do. Web is not smart enough to predict something and react to it.

The key features of Web 3.0 will be
  1. Semantic web (meaning of data)
  2. Personalization
  3. Intelligent search
  4. Behavioral advertising
  5. Metadata
More on Web 3.0
http://www.labnol.org/internet/web-3-concepts-explained/8908/
http://computer.howstuffworks.com/web-30.htm
http://en.wikipedia.org/wiki/Web_2.0#Web_3.0

Saturday, April 28, 2012

Google Drive


Finally, Google Drive is out there in market for use and  I got it configured for myself. Currently it gives 5GB of free space. 

Note! As of now Google Drive client is not available for GNU/Linux.  After setting up all this in Mac, I gave it a try in Ubuntu also. When I login to Google Drive web application, there is no option to download client, as it's now available yet :) 

Here we go, setting up Google Drive and client in Mac.

Read more about Google Drive on their official blog.

Get started with Google Drive at drive.google.com/start
Download the Google Drive (In my case it's for Mac)
I got the .DMG file
Double click .DMG file. You will see "Install Google Drive" icon
Double click
To install it, drag Google Drive.app to Applications
Verify Google Drive in applications and click it to launch
Might get this message, allow forever
Enter userid password

You will see this icon, on click below menu pops

Sign in with your google email id / password


Click Next

Start sync

You will see this message

Google Drive is created and synched

After logging in menus does change.

Friday, April 27, 2012

Take screen shot of iPhone & iPod Touch

To capture iPhone screen as an image, press Home and Sleep button at the same time. You can see the captured image in Photos.

Press Home and Sleep button together


JavaScript to get the browser window's height and width

While working on a web application I came across a scenario where in I wanted to adjust height and width of my component as per browser's resolution. And here is the code snippet to do that in JavaScript.

function getScreenHeightWidth() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        // Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement
            && (document.documentElement.clientWidth 
                        || document.documentElement.clientHeight)) {
        // IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body
            && (document.body.clientWidth 
                        || document.body.clientHeight)) {
        // IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    window.alert('Width = ' + myWidth);
    window.alert('Height = ' + myHeight);
}

I have tested this in latest versions of all modern browsers including Chrome, Firefox, Safari and Internet Explorer. Also I have tested it in Windows 7, Ubuntu 11.10 and Mac Snow Leopard.

HTML Codes for arrow keys

In order to display left, right, up and down arrow keys in HTML we have the following codes.

Key
Code
Output
Left Arrow
←
Right Arrow
→
Up Arrow
↑
Down Arrow
↓

More HTML codes here.

Shrink and extend disk partitions in Windows 7

Its been a long time since I played with partitioning hard drives and creating and deleting volumes. Way back in Windows era, there was no way to shrink and extend disk partitions. Recently I installed Ubuntu in my machine hosting Windows 7 and found one very useful option in Disk Utility i.e. to shrink and extend volumes. Here we go.

 Here is how we can shrink a volume. This will create an empty partition or unallocated space in your disk. Inn the similar way you can extend a volume where in you can assign extra space from unallocated disk space.

My Computer → Right Click → Manage

Select Disk Management → Select the partition

Right Click → Shrink Volume

You might see this message

Enter the amount of space to shrink in MB

ExtJS 3.2 Grid and jQGrid performance

ExtJS Grid and jQGrid are really nice to have kind of UI components. Based on the preference of ExtJS or jQuery framework one can choose which one to use. As I was assigned a task of improving performance of existing web application created in ExtJS 3.2, I got to evaluate grids in ExtJS and jQuery.

To evaluate ExtJS and jQuery grids and their performance, I created separate projects for them. And of course I am using server side pagination. No server side caching, client side caching for this evaluation. 

ExtJS performance 
Data Set
Page Size
Initial Load
Avg Next
Avg Prev
Avg Last
Avg First
853
100
1.06 s
100 ms
90 ms
30 ms
30 ms
853
200
1 s
250 ms
200 ms
250 ms
250 ms
853
500
1.48 s
350 ms
350 ms
250 ms
250 ms
853
800
976ms
350 ms
350 ms
400 ms
500 ms

jQuery performance 
Data Set
Page Size
Initial Load
Avg Next
Avg Prev
Avg Last
Avg First
853
100
200 ms
50 ms
50 ms
40 ms
40 ms
853
200
3 s
150 ms
130 ms
150 ms
150 ms
853
500
913 ms
200 ms
200 ms
250 ms
250 ms
853
800
938 ms
200 ms
200 ms
40 ms
100 ms


So, with my tests I found jQuery little faster compared to ExtJS. There could be n-number of reasons for this. 

Summary: 
Finally for the shake of maintainability of existing code base, I have chosen ExtJS over jQuery. However I have also experimented plugging in jQGrid in place of ExtJS Grid and that too worked for me. Initially I was not sure whether both can work together or not but they did.

Run jetty on a specific port using Gradle

I usually start jetty using Gradle build file as given below, but it will run it on HTTP port 8080
gradle jettyRun

But to specify user defined port use -DhttpPort as given below.
gradle jettyRun -DhttpPort=9999

Know more.

Thursday, April 26, 2012

Set max connections in MySQL database

Problem Statement: I was working with MySQL database and all of a sudden my code started throwing this error.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"

The similar kind of error I got in MySQL Workbench also. Here is the snapshot.























Problem Solution: Increase the maximum concurrent connections. You can do this with the command below.

set global max_connections = 1000;

Modify parameters from ExtJS 3.2 Grid Paging next button

Problem Statement: I have a data store define in ExtJS 3.2 as given below. The problem is when clicking next button in paging bar, the agencyStatus is not passed in.

var agncGridStore = new Ext.data.Store({
    url : '/webui/advertiser/agenciesList.json',
    method : 'GET',
    autoLoad : false,
    reader : new Ext.data.JsonReader({
        root : 'agencies',
        totalProperty : 'agencyCount',
        fields : [ 'id', {
            name : 'name',
            type : 'string',
            sortType : Ext.data.SortTypes.acUCString
        }, 'address', 'status', 'currency' ]
    }),
    listeners : {
        load : function() {
            resizeGridHeight('agncGridID', 200, 300);
        }
    },
    remoteSort : true,
    sortInfo : {
        field : 'name',
        direction : 'asc' | 'desc'
    },
    baseParams : {
        'firstResult' : 0,
        'fetchSize' : pageSize,
        'searchStr' : searchText,
        'agencyStatus' : searchFilter
    }
});
agncGridStore.load();

Problem Solution: After trying different possibilities, finally I got done with the help of beforeload event.
var agncGridStore = new Ext.data.Store({
    url : '/webui/advertiser/agenciesList.json',
    method : 'GET',
    autoLoad : false,
    reader : new Ext.data.JsonReader({
        root : 'agencies',
        totalProperty : 'agencyCount',
        fields : [ 'id', {
            name : 'name',
            type : 'string',
            sortType : Ext.data.SortTypes.acUCString
        }, 'address', 'status', 'currency' ]
    }),
    listeners : {
        load : function() {
            resizeGridHeight('agncGridID', 200, 300);
        },
        beforeload : function(store) {    
            store.baseParams.agencyStatus = searchFilter;
            store.baseParams.searchStr = searchText;
        }
    },
    remoteSort : true,
    sortInfo : {
        field : 'name',
        direction : 'asc' | 'desc'
    },
    baseParams : {
        'firstResult' : 0,
        'fetchSize' : pageSize,
        'searchStr' : searchText,
        'agencyStatus' : searchFilter
    }
});
agncGridStore.load();

Use Hibernate Criteria API to Order By based on Association

Problem Statement: I am working with Hibernate to read database table. Not able to apply order by on associated object's attributes.

Problem Solution: Solution is to use criteria alias.

Sort by Cat.name.

List cats = sess.createCriteria(Cat.class)
    .addOrder( Order.asc("name") )
    .list();
In the statement below associated objects's name property is used for sorting. In this case sort will be on Cat.kittens.name
List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .addOrder( Order.asc("kt.name") )
    .list();

Read more

Friday, April 20, 2012

Opening .run file in Ubuntu 11.10

I was working with ExtJS and found Sencha Architect 2, a GUI tool for writing ExtJS. I thought of trying it and downloaded it from INTERNET. But to my surprise, I got a .run file copied to my hard drive. After searching a bit I got to know about .run file. A .run is a packaged format which contains software and a small program to install the software.

To open .run file in Ubuntu 11.10, follow below steps.
  1. Right click on the .run file
  2. Select properties
  3. Open permissions tab an make sure "Allow executing file as program" is checked.
  4. Double-click the .run file to open it. A dialog box should appear and follow on screen information.

Get the process id by its name

ps -ef | grep mysql

Installing Eclipse J2EE Indigo SR2 in Ubuntu 11.10

In this section we will see how to install Eclipse J2EE Indigo .

Installing eclipse
  1. Install .gz file from eclipse web site
  2. I will copy the .gz file to ~/softwares
  3. Unpack the .gz file
    tar -zxf eclipse-jee-indigo-SR2-linux-gtk.tar.gz
    

  4. You will have a new directory "eclipse"
  5. Create desktop shortcut by right clicking eclipse -> Copy To -> Desktop
  6. Launch eclipse from desktop

Know if you are Running 32-bit or 64-bit Linux?

Open terminal and run the below command
uname -m

If the response is i686, you have a 32-bit version of Linux.
If the response is x86_64, you have a 64-bit version of Linux.

Installing Apache Maven 3.0.4 in Ubuntu 11.10

Installing Apache Maven 3.0.4

  1. mkdir ~/softwares
  2. cd ~/softwares
  3. Get the latest release from Apache web site using the command
    wget http://mirrors.sonic.net/apache/maven/binaries/apache-maven-3.0.4-bin.tar.gz
  4. Unpack the .gz file using command
    tar -zxf apache-maven-3.0.4-bin.tar.gz
  5. Create a link to this called apache-maven as that makes easy to update new releases. Use the command below for this
    ln -s apache-maven-3.0.4/ apache-maven
  6. Set the environment variable, open /etc/environment file
    sudo vi /etc/environment
  7. Append the following to the file
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/manohar/softwares/apache-maven/bin"
    JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.06
    M2_HOME=/home/manohar/softwares/apache-maven
    MAVEN_HOME=/home/manohar/softwares/apache-maven
    M2_HOME=/home/manohar/softwares/apache-maven
  8. Log out and login again to see the effect.
  9. Test maven installation using the command
    mvn -version