Monday, December 14, 2009

Gwt 2.0 : Uibinder example using Eclipse

There many exciting and productive features got released with GWT 2.0. UiBinder is one of them which allows you to create UI using declarative XML files. You need to write very less code in comparison to previous versions of GWT.

Lets start with simple project which show how to use UiBinder.


Create first web application : Select File > New > Web Application Project from Eclipse menu. In the New Web Application Project wizard, enter a name of your project (UiBinderTest) and a java package name com.example.uibindertest. Please don't select Use Google App Engine option. Click Finish. Your project is ready.

Run the application : Follow the instruction given in Running Your Web Application Locally section.

Lets convert this application and use UiBinder.

Create UiBinderTest.ui.xml file in com.example.uibindertest.client directory. Please have a look at the code in this document. We created DockLayoutPanel first and added all the elements to it. Now look the corresponding java code UiBinderTest.java in the same document. Its very small and clear, isn't it?. With the help of UiBinder we are able to write compact, faster code easily.

Now lets create a dialog box using UiBinder. Please create ResponseDialog.ui.xml file in com.example.uibindertest.client directory. Look at the code in the document. Now create corresponding java file ResponseDialog.java file in the same package. Look at the code in the document. Please note that in ResponseDialog.java we do not need to code initWidget() method because DialogBox put itself to DOM.

If you want to read more about UiBinder please read http://code.google.com/webtoolkit/doc/latest/DevGuideUiBinder.html

We are done with the changes. Run the application again.

Please write comment if you have any doubts.

Sunday, December 13, 2009

Import Gwt Sample Projects into Eclipse

Many sample projects comes with GWT SDK. Many programmers don't know how to import these sample projects into Eclipse. Here are the easy steps to import such projects into eclipse.
Lets take example of Mail projects which comes with GWT SDK.
  1. cd <download dir>/gwt-2.0.0/samples/Mail
  2. run 'ant eclipse.generate' command in the directory
  3. In eclipse go to the File menu and choose: File -> Import -> Existing Projects into Workspace and select Mail directory. Click on finish button.
  4. To launch your web app in GWT development mode, go to the Run menu and choose: Run -> Open Debug Dialog. Under Java Application, you should find a launch configuration named "Mail". Select and click "Debug".
Please let me know if you have any problems.

Saturday, September 19, 2009

Observer Pattern in Java

We should use observer pattern when one object (say Subject) changes state and we would like to notify/update all its dependents (say Observers). Observer pattern achieve this objective without making classes tightly coupled (NOTE: Tightly coupled classes reduces the reusability of the classes.)

Lets look at the example : We would like to present application data in many formats i.e table, graph, chart etc. So as and when application data changes, all the presentation should be notified.


(image source : IBM reasearch)

Java provides Observable class and Observer interface to implement Observer pattern easily.

Subject class should extends Observable class. Whenever state changed, subject call setChanged() method and notifyObservers() method. These method do all the work for you. You do not need to iterate over all the observers and call method of observers.

import java.util.Observable;

public class Subject extends Observable {
  public void stateChanged(String i) {
    setChanged();
    notifyObservers(i);
  }
}

Lets look at the observer's code now. Observer need to implements update method.

import java.util.Observable;
import java.util.Observer;

public class Observer1 implements Observer {
  public void update(Observable arg0, Object arg1) {
    if (arg1 instanceof String) {
      System.out.println("Observer1  " + (String)arg1);
    }
  }
}

We need to add observers to the subject. Lets look at the MainClass which does this. Also assume we created one more observer class name Observer2.

public class MainClass {
  public static void main(String[] args) {
    Subject source = new Subject();
    Observer1 one = new Observer1();
    Observer2 two = new Observer2();
    source.addObserver(one);
    source.addObserver(two);
    source.stateChanged("Hello");
    source.stateChanged("world");
  }
}

As you noticed, we added observer to subject class. When we call stateChanged method of Subject class it notifies all the observers class. Output of the class looks like this.

Observer2  Hello
Observer1  Hello
Observer2  world
Observer1  world

Enjoy Design Patterns !!!

Friday, September 4, 2009

Add Google Translation Widgets to Your Site


Google's widget uses a machine translation system developed by Google, that's available for 29 language pairs. The widget works in most browsers and it's actually a Google gadget loaded in an iframe. Its gives ability to your reader to read your site in their preferred language.

Google translation widgets looks like this.

It is very easy to add this gadget to your website. Add following script to your website:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/translatemypage.xml&up_source_language=en&w=160&h=60&title=&border=&output=js"></script>

Lets look at the example once some one clicks on any language (i.e. Hindi). Original site looks like this http://ayurvedictipofaday.blogspot.com/ . After clicking on Hindi language the site looks like this.



Enjoy Google Translation ...

Saturday, August 29, 2009

ThreadPool in Java

Thread pools address two different problems.
  1. They usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead.
  2. They provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.
Lets look at simple program which gives better understanding of how ThreadPool works in Java.


class Workers implements Runnable {
private final int value;
Workers(int value) {
this.value = value;
}
public void run() {
System.out.println("Value = " + value);
}
}

public class ThreadPoolExample {
public static void main(String[] args) {
// The Executors class provides factory methods for the executor services provided
// by java.util package.
// newFixThreadPool creates a thread pool that reuses a fixed set of threads
// operating off a shared unbounded queue. If any thread terminates due to
// a failure during execution prior to shutdown, a new one will take its place
// if needed to execute subsequent tasks.
ExecutorService executors = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {
// Submits a Runnable task for execution and returns a Future
// representing that task.
executors.submit(new Workers(i));
}

// An ExecutorService can be shut down, which will cause it to stop
// accepting new tasks. After being shut down, the executor will
// eventually terminate, at which point no tasks are actively executing,
// no tasks are awaiting execution, and no new tasks can be submitted.
executors.shutdown();
try {
// Blocks until all tasks have completed execution after a shutdown request,
// or the timeout occurs, or the current thread is interrupted, whichever
// happens first.
executors.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Result of the program might differ from this result.
Value = 0
Value = 2
Value = 3
Value = 4
Value = 5
Value = 7
Value = 8
Value = 9
Value = 1
Value = 6

Monday, June 22, 2009

Safari : open targeted links in new tabs

One of the things I find most annoying when browsing the web is when a link opens a new window. It completely disrupts my workflow when a new window pops up.

For Safari, however, there is no such setting to be found when you look through its preferences window. But the setting does exist, though you have to use Terminal.app to enable it:
  • Quit Safari
  • Open Terminal.app
  • Enter defaults write com.apple.Safari TargetedClicksCreateTabs -bool true and press enter
  • Open Safari
  • Notice that links that used to open in a new window will now open in a new tab