Showing posts with label Web. Show all posts
Showing posts with label Web. Show all posts

Friday, September 7, 2007

Accelerating AJAX based Web Client Development with JSON and GWT

With the rise of Web 2.0, web client are doing more than parsing and displaying HTML. Web Client are powerful than ever before. There is a shift in programming paradigm with servers providing services and serving data and Clients parsing data, managing state information over and above powerful AJAX UIs. Servers are now proposed to be built the REST way. Server may return data in different format. AJAX has been associated with XML response but response can be in any format. One such format which makes Web 2.0 client development really easy is JSON.

JSON is very similar to XML. It is also text based. Server side objects can be easily serialized into JSON text format using frameworks like TurboGears.

For example, a library application might provide a Web service that yields books in this XML format:


<book>
  <author>
     <fullname>Vishal Jain</fullname>
     <org>Consulting</org>
  </author>
  <chapters>
     <chapter page="'10'">Chapter 1</chapter>
     <chapter page="'20'">Chapter 2</chapter>
  </chapters>
</book>

With JSON, it looks like this:


{
   "author" : {
   "fullname": { "value" : "Vishal Jain" } ,
   "org": { "value" : "Consulting" }
   }
   "chapters": {
      "chapter" : [
        { "page" : "10", "value" : "Chapter 1" } ,
        { "page" : "20" , "value" : "Chapter 2" }
      ]
   }
}

Working with JSON is Javascipt is very easier. In Javascript, we can access information about chapter 2 as

var book = eval('(' + req.responseText + ')');
inputBox.value = book.chapters.chapter[1].value;

An example of JSON response from a real world service can be seen here.
http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=potato&results=2&output=json

Working with JSON using GWT

GWT provides an elegant way of client side programming where developer codes in Java and Java code is converted into Javascript by GWT.

GWT comes with API which make working with JSON easier.

A typical cycle will include:

  • Sending HTTP GET/POST request for JSON response.
  • Parsing JSON response in Response Handler
  • Extracting Data and displaying it as appropriate.
Lets take them one by one.

Sending HTTP GET/POST request for JSON response

HTTPRequest.asyncGet(, new JSONResponseTextHandler())

Parsing JSON response in Response Handler

Implement a response handler extending ResponseTextHandler

private class JSONResponseTextHandler implements ResponseTextHandler {
    public void onCompletion(String responseText) {
      try {
        JSONValue jsonValue = JSONParser.parse(responseText);
        displayJSONObject(jsonValue);
      } catch (JSONException e) {
        ...
      }
   }
}

Extracting Data and displaying it as appropriate

  private void displayJSONObject(JSONValue jsonValue) {
    JSONObject book;
    
    if ((book = jsonValue.isObject()) != null) {
        JSONValue chapters = book.get("chapters");
        if(chapters != null) {
            JSONArray chapterArray;
            if ((chapterArray = chapters.isArray()) != null) {
                JSONObject chapter = chapterArray.get(1).isObject();
                inputBox.setText(chapter.get("value"));
            }
        }
    }
}

That's it!!!

A demo of JSON/GWT is available here.

The source of this demo comes bundled with Google Web Toolkit.

Wednesday, September 5, 2007

Web Developer - Awesome Extension for firefox

I was looking for web developer tool for firefox which aids in designing web pages especially with monitors of different resolutions. I knew about a developer toolbar provided by Microsoft for IE but I was looking for a similar extension for firefox when I stumbled upon Web Developer extension for firefox.

I just downloaded the latest version for Mozilla firefox.
It's awesome!!!



A decent summary of features:

  • Dynamic updating of css of a given page
  • Images: show their paths, sizes, point out images with no 'alt' attributes, etc.
  • All types of page info (cookies, headers, more...)
  • Utils to clear cache, session cookies, javascript debugger
  • Helpful outlining: like outlining all block elements
  • Resize the browser window to various resolutions
  • Validation : HTML/XHTML, css, validating of link...
  • Disabling of images, javascript, ...
  • Links to specifications: css1, css2, HTML, XHTML, DOM...
  • Manipulating Forms ... various utilities

Tuesday, September 4, 2007

Deploy GWT using external application server like JBoss

I wanted to use GWT with external application server. It is really easy to use GWT with embedded tomcat server. But, I needed advanced services provided by managed application servers like JBoss. After figuring out how to use GWT with external web servers, I am posting the details with an example web application.

Environment:
I am using GWT version 1.4.1. Instructions have changed from previous releases of GWT.

I expect the following system variables are set:

GWT_HOME
JAVA_HOME
JBOSS_HOME

Step 1: Create sample application using GWT scripts.

This will use embedded tomcat in step 1. Later on we will change it to use external web app server.

1) cd %GWT_HOME%

2) projectCreator.cmd -eclipse gwtjboss -out ..\gwtjboss

3) applicationCreator.cmd -eclipse gwtjboss -out ..\gwtjboss com.gwtjboss.client.GwtJbossTry

4) Now verify that the generated application is working with embedded tomcat using GwtJbossTry-shell.cmd
Note the URL in hosted browser http://localhost:8888/com.gwtjboss.GwtJbossTry/GwtJbossTry.html

5) Also try to bring up the hosted browser using GWT Eclipse launch configuration. It can be accessed from Run -> Debug... -> click GwtJbossTry under Java Application tree node.



Step 2: Change to use external application server

1) Run GwtJbossTry-compile.cmd script and copy the following files from 'www' output directory to %JBOSS_HOME%/server/default/deploy/gwtjboss.war

com.gwtjboss.GwtJbossTry\GwtJbossTry.html
com.gwtjboss.GwtJbossTry\history.html
com.gwtjboss.GwtJbossTry\com.gwtjboss.GwtJbossTry.nocache.js
com.gwtjboss.GwtJbossTry\hosted.html

2) Update GwtJbossTry-shell.cmd.
@java -cp "%~dp0\src;%~dp0\bin;%GWT_HOME%/gwt-user.jar;%GWT_HOME%/gwt-dev-windows.jar" com.google.gwt.dev.GWTShell -noserver -port 8080 -out %JBOSS_HOME%/server/default/deploy/gwtjboss.war %* gwtjboss/com.gwtjboss.GwtJbossTry/GwtJbossTry.html

We have made the following changes to *-shell.cmd:

  • Added -noserver to tell GWTShell not to start embedded tomcat.
  • Added -port 8080 because external server (JBoss here) is running on port 8080.
  • Changed output directory to D:\jboss\server\default\deploy\gwtjboss.war so that clicking compile button in hosted browser will automatically update the deployed application. Note that in complex application, we may need complex packaging mechanism to deploy application. So this compile feature may not be very helpful in complex application. [Not necessary]
  • Updated the path to HTML page.
To debug the client side code, we need to update the eclipse launch configuration too.
  • Go to Run -> Debug... -> click GwtJbossTry under Java Application tree node.
  • Update arguments.

3) Now set a breakpoint inside GwtJbossTry class and play around the page. If you hit the breakpoint, you are done.

This is all we need to do to use external server.
We we will hit the URL http://localhost:8080/gwtjboss/com.gwtjboss.GwtJbossTry/GwtJbossTry.html (assuming JBoss running on port 8080)from hosted browser, GWT's hosted browser will intercept Javascript calls and runs the corresponding Java code in its classpath.

Note the change in URL. We have added gwtjboss to URL. This is because of the fact that we have deployed the application gwtjboss.war

The directory listing of deployed application is:

D:\JBOSS\SERVER\DEFAULT\DEPLOY\GWTJBOSS.WAR
+---com.gwtjboss.GwtJbossTry

        com.gwtjboss.GwtJbossTry.nocache.js
        GwtJbossTry.html
        history.html
        hosted.html

The modified application is available at googlecode.
svn checkout https://gwt-external-server-jboss.googlecode.com/svn/tags/simple-gwt-jboss
simple-gwt-jboss
or simply download gwtjboss_v01.zip

In this simple example we haven't deployed any servlet and made call to that servlet from GWT client code. Doing that is also easy. We just need to copy compiled client + server code to WEB-INF\classes, gwt-servlet.jar to WEB-INF\lib and update web.xml. More on GWT with servlet deployed in JBoss (external server) later.

Monday, September 3, 2007

JBoss - JasperException in JSP using generics and 'for each'

JBoss 4.2.0 throws the following exception while using generics in JSP even if java version is 1.5 or greater

Syntax error, parameterized types are only available if source level is 5.0
Syntax error, 'for each' statements are only available if source level is 5.0

The workaround for this issue is to add the following XML configuration to
${jboss.home}/server/default/deploy/jboss-web.deployer/conf/web.xml

Add

<init-param>
<param-name>compilerSourceVM</param-name>
<param-value>1.5</param-value>
</init-param>
<init-param>
<param-name>compilerTargetVM</param-name>
<param-value>1.5</param-value>
</init-param>

inside <servlet> tag with <servlet-name>jsp</servlet-name> inside it.
(Note that there are many servlet tags in this web.xml, so be careful)

Tuesday, August 7, 2007

Why should I use Google Web Toolkit (GWT) ?

Google Web Toolkit (GWT) was launched by Google in May 2006 and the toolkit is being evaluated by web developers around the world. GWT enables AJAX based web applications to be coded in Java language. GWT will then convert Java code written for client side (browser) to JavaScript which can run on any Javascript enabled browser (most modern browsers are).

Pros:

  • Java Developers can easily develop AJAX based web apps without learning JavaScript.
  • JavaScript generated by GWT is browser independent. So it saves the headache of supporting multiple browsers.
  • Coding in Java increases the testability of source code since Java is type-based language. GWT also provides JUnit integration for writing test cases for client side code.
  • GWT helps manage browser back button easily which is usually ignored in AJAX web apps.
  • And above all.. DEBUGGING. Client side Java code can be debugged using any Java debugger such as Eclipse, Netbeans etc. Once the developer is sure that client Java code is working fine, then it can be converted to JavaScript.
  • To support debugging, GWT supports 2 browsing modes. Hosted mode and web mode. In hosted mode, a special browser shipped with GWT is used to running client code as Java (i.e. without conversion to JavaScript). In web mode, any browser can be used and compiled JavaScript is run. It also provides scripts to run hosted mode.
  • How to exchange data with client side? GWT helps here by serializing data b/w client and server side using GWT-RPC. In simple words, the server side code creates a Java object of client side Java class (which has been translated and equivalent JavaScript code also exists on client side). GWT serializes the object and populates the equivalent JavaScript code on client side. Diagram... The serializable classes can be any primitive Java type, their wrappers, String, Date, class implementing IsSerializable interface and Arrays of objects of serializable classes (including Arrays of Arrays). Note: GWT-RPC is tailored RPC protocol for communication b/w Java and JavaScript. It should not be confused with standard RPC.
Cons:

  • Java 1.5 or above are not supports on client side code. Hence user can't use features like annotations, generics in client side code. This doesn't mean that you can't use Java 5.0 or 6.0 JDK. Only the source code need to comply with JDK 1.4.2.
  • CSS is used to styling so user still got to play around CSS. This is also good from Java code point of view as style information is not getting deeply hard coded in Java. Only style names are coded in Java. These styles are defined in CSS. GWT provides default styles for most of the widgets.
  • No support for other languages. But people are working on it. Find out more...
http://www.gwtsite.com/?m=200605&paged=2
http://www.gwtpowered.org/#Resources
Google Project Search with label GWT

Overall GWT materializes a great idea. For Java developers, its a great gift from Google. For guys from non-Java background, it will be hard to use and play around initially. Just a bunch of scripts and mainly 3 jars to play around with.
  • gwt-user.jar - While coding in Java and hosted mode.
  • gwt-dev-{OS_NAME}.jar - Debugging in hosted mode.
  • gwt-servlet.jar - To be used in web app container as some client side Java code is also used on server side.
Useful Links:
Documentation
FAQs