Wednesday, March 31, 2010

JavaScript Trick: Submitting multiple forms at once

Everyone who has worked on any web application would be quite familiar with HTML Form element. Just to give an idea, a HTML Form element is a wrapper to all HTML user input fields such as Text Field, Radio Button, and List Box etc. Once the user inputs are captured through HTML user input fields, the HTML form is submitted to the server for further processing. At the server, all the input field values are available in the request object. Using the request object interface, we retrieve the field values and apply the processing logic. This is very straight forward and works smoothly.

There is no limit of number of HTML Form element within a web page, but there is one limitation. Only one Form element can be submitted at a time. Nesting of Form elements is not restricted but they don’t serve the purpose either. If we need to submit all/multiple forms on the page, we have two workarounds. Let’s go through them using one example.

Assume we have a simple HTML page with two forms, each having one text field as below:

<html>
 <head>
  <title>Test Multi Forms</title>
 </head>
<body>
 <form name="form0" method="POST" action="abc.xyz">
  <form name="form1" method="POST" action=" abc.xyz "> 
   <input type="text" name="text1" value="value1"/>
  </form>
  <form name="form2" method="POST" action=" abc.xyz "> 
   <input type="text" name="text2" value="value2"/>
  </form>
  <input type="submit" value="submit"/>
 </form>
 </body>
</html>

If I try clicking on submit button, it doesn’t work expectedly as nesting of forms are not supported feature. If I change the submit button as <input type="button" value="submit" onclick="JavaScript:document.forms.form0.submit();"/>, the form0 looks like submitted, but in the request, I can retrieve only form1 values. This doesn’t server the purpose.

Now let’s try our workaround solutions. As these are workaround solutions, the execution/working can’t be guaranteed, but they seem to work (at least for me).

  1. Asynchronous Forms Submission: If we put our forms in flat structure (not nested as above), we can trigger both the forms in example for submission using JavaScript calls as below (same works for any number of forms in the page).

<html>
 <head>
  <title>Test Multi Forms</title>
  <script language="JavaScript">
  function fnSubmit () {
     document.forms.form1.submit();;
     document.forms.form2.submit();;
  }
  </script>
 </head>
<body>
  <form name="form1" method="POST" action=" abc.xyz "> 
   <input type="text" name="text1" value="value1"/>
  </form>
  <form name="form2" method="POST" action=" abc.xyz "> 
   <input type="text" name="text2" value="value2"/>
  </form>
  <input type="button" value="submit" onclick=" abc.xyz "/>
 </body>
</html>

This results into multiple asynchronous requests to the server; one for each form. Also the order of forms submission is uncontrolled. Second form submission request might reach to the server before first form submission request. This is applicable if we want to process each form submission request independently ignoring their sequence.

Synchronous Forms Submission: If we want to submit all forms in the page together for synchronous processing. We can exploit the DHTML capabilities by using an additional place holder form or one particular form as below:

<html>
 <head>
  <title>Test Multi Forms</title>
  <script language="JavaScript">
  function fnSubmit (){
     var form1Content = document.getElementById("form12").innerHTML;
     var form2Content = document.getElementById("form2").innerHTML;
     document.getElementById("toSubmit").innerHTML=form1Content+form2Content;
                 document.forms.toSubmit.submit();
  }
  </script>
 </head>
<body>
  <form name="form1" id="form12" method="POST" action="abc.xyz"> 
   <input type="text" name="text1" value="value1"/>
  </form>
  <form name="form2" id="form2" method="POST" action="abc.xyz"> 
   <input type="text" name="text2" value="value2"/>
  </form>
  <input type="submit" value="submit" onclick="javascript:fnSubmit();"/>
 <form name="toSubmit" method="POST" action="abc.xyz" style="display:none">
 </form>
 </body>
</html&gt;

Here at the time of submission request, I am merging the all different form contents as one hidden form content and submitting that hidden form. This way I am submitting a single form but this form contains entire content of different forms on the screen. In this case, no violation of W3C standards though the size of form contents might pose some restriction. Also this doesn’t work with nested form elements (it always ignores the first form—we might have one extra blank form if we want to do nesting though I am not sure of the need of the same).

Thursday, March 25, 2010

Search Techniques – Part 1: Overview


Since many days I am thinking about different kinds of search requirements and suitability of current available tools. Since it’s a very big topic, I am thinking to look at one search aspect at a time. In this section (part), I would be going through the overview of the search techniques and it would be followed by different search tools available today and their applicability in next sections (parts). There are two kinds of data/information retrievals. In the first kind, the user is aware of the full context of the data i.e. steps to locate the data. For example retrieving a file from a particular folder in your folder system falls into this category. In the second kind, user has some or full idea about the data he is looking for but he is not aware of its context. For example, retrieving a file from a forgotten/unknown folder of your file system falls in this kind of retrieval. By the term “search”, we often mean second kind of data/information retrieval.

There are different ways to categorize the search. We can categorize the searches based on the algorithms e.g. linear, binary etc used in the search process. Also we can categorize the search based on the search object e.g. data or content etc. Another classification could be based on the context of the search e.g. local/specified repository search or virtual space search. Let’s go over these different kinds of classifications first before moving to the different search tools available and their applicability.

Search Categories based on algorithm: There are huge number of search algorithms available today. Some of them are listed below:

1.      Linear Search: This is basic algorithm of search when we compare each source element one by one against the search element. This is simplest and well performing algorithm if the source elements are of limited number e.g. searching a particular card from a set of playing cards. Since there are 52 cards only, my best case scenario could be that I find the desired card as first card and the worst case scenario could be that the desired card is the last card in the stack. But we are not going to have more than 52 comparisons in any case.

2.      Binary: As it’s clear from the linear search section that if the size of source elements is high, performing a linear search could be very expansive. Binary search is an attempt to address the limitation of linear search and is applicable to only elements which could be sorted in some order e.g. numeric data or string based data. Binary search is a two step process. As a first step, we sort the data in a particular order. And then as a second step, we start comparing the search element against the middle element in the source list. If the middle element is bigger/smaller as per the sorting criteria, we limit the search is one half and ignore the second half of the list. This way, at each comparison, we reduce the size of the source by half. This is well performing search algorithm but not the best and also it’s applicable to only sortable elements.


3.      Hash Table Search: This is most interesting search and widely used search technique. This has proved very efficient in cases where the source elements consist of multiple fragments e.g. String, Text Files, and Web Page etc. Hash table is a structure of creating an identifier of the element and linking the element with the identifier. The identifiers are commonly referred as indexes. Under hash table search, we perform the search on identifiers and retrieve the source element of the matching identifier. I will go through it in details when I talk about various search tools.

4.      Tree Search: Tree search is an extended version of binary search. Similar to binary search, it’s a two step process. As a first steps, we arrange the source elements in form of tree (node graph) and as second step, we perform the search by traversing the tree elements and comparing with the search element. It can be further classified based on the tree nature and our traverse mechanism as below:


a.       Linear: As similar to linear search mentioned earlier, linear tree search traversal is a mechanism of traversing every node of the tree one by one starting from the root. Linear traversal can be performed in 4 ways.

                                                               i.    Depth First: This is a traversal mechanism when we visit the child nodes (vertical) before sibling (horizontal) nodes.
                                                             ii.   Breadth First: This is a traversal mechanism when we visit the sibling nodes (horizontal) before sibling nodes (vertical).
                                                            iii.   Left First: This is a traversal mechanism when we visit the left node before right nodes.
                                                           iv.     Right First: This is a traversal mechanism when we visit the right node before left nodes.

b.      Binary: Again as similar to binary search, this is applicable to the elements which can be sorted in some order. In applicable scenario, we make a tree with restriction of every intermediate node having exact two child nodes arranged in the sorted order. This arrangement is called binary tree. To perform a search, we compare the search element with root element. If not matching, we proceed to node which falls under the sorted order side and ignore the other node and hence other part of the tree completely e.g. if the tree is sorted in ascending order (left node has smaller value than right node), if searching element is smaller than intermediate node, we proceed in the left side and ignore the right side completely.

c.       Heap: Similar to binary search, heap search is also applicable to the elements which are sortable. Under this mechanism, we arrange the elements in a tree format with a condition that intermediate node is always bigger/smaller than all it descendent nodes. This way the root node is always biggest/smallest element in the tree. This property is called heap and search process using heap tree is called heap search. There are many variations of the heap search and binary search could be considered as one of its variations.


5.      Heuristic Search: This is most interesting search technique and the search technique involving artificial intelligence. Under this technique, we apply some artificial intelligence in the search process and search result is not required to be completely search criteria satisfying result. We apply extra logic during the searches and also retrieve elements partially satisfying the search criteria with mostly matching result in the top. To get a clear understanding of this process, imagine any online search, product store search. The search result may not exactly satisfy the search term but most applicable result would be on the top. There are logics involved in deriving the priority of matching results. We will go through it in details while going through different search tools. There are multiple variations of heuristic searches. Some of the variations are as follows.

a.      Pattern Matching: Under this technique, the base of heuristic search is the pattern of the searching element and search result is result of all matching and similar patterns. For example, if we are searching for term “good people”, few variations of the search term could be, full both words together, both words but not together, first full word only, and second full word only. All the results matching both words together would appear in top followed by other results. Any online search is typical example of this.

b.      Behavioral Search: Under this technique, the base of heuristic search is the behavioral aspect of the search term. For example, if we are searching form term “good people”, the behavioral aspect of it is taken as basis of the search. Some of the considered behavioral aspects could be good people, good society, good locality, polite people, educated people etc. and search result could be search result of all these behavioral variations.

c.       Contextual Search: Under this mechanism, basis of heuristic search is the context of the search term/element. Other example could be a product search on a product website. Most of the good product website such as Amazon.com will perform contextual search of the desired product and return exact and all other products of the context. E.g. if we are searching for Shaving Blade, the search result might return all other products used in saving. This can be further classified in various categories; some of them are as following:

                                                               i.      Flat Search: Under this mechanism, we device the algorithm of prioritization and all search results are presented in the flat format. Some of the less popular product web sites perform this kind of search against the desired product. User is fully responsible to either refine the search term or traverse through all result elements to further narrow down.
                                                             ii.      Guided Search: Under this mechanism, the most appropriate result is presented along with a navigation/guide to narrow down the specific search object. Considering the above example, we might be presented with different Shaving blades along with some navigational categorization such as type, brand, pricing rage etc. Following the navigational categorization, the user is directed to the specific product.

Search Categories based on search object: There are various ways to classify the searches based on the search object. The most common category is as following.

1.      Data (Numeric): As it’s clear from its name, data search is a category when we perform our search logic over a certain set of data (numbers). For example, if we are maintaining details of an organization’s employees in a tabular format (database) then process of locating details of a particular employee using his employee number (numeric) falls into this category. Performing this kind of search is comparatively simpler than performing content search.

2.      String: This is little complex as compared to the numeric search. Sometimes it’s referred as String Matching Search. There are several algorithms available such as Native String Search, Rabin-Karp Search, Knuth-Morris-Pratt & Boyer-Moore; to perform string search. These all algorithms differ in a sense of comparing the search string against the string source repository elements. The complexity comes in picture because strings are not stored as a single value as compared to numeric values e.g. if I consider a numeric value e.g. “1134”, though it consists 4 digits but it’s stored as a single value while if I consider a string value e.g. “HAPPY”, its stored as 5 different characters. Therefore to perform a string search, we need to compare each character of the search string against the source string. This becomes very complex when we are performing a string search other than exact match.


3.      Content: This is highest complexity search category. As we have a got a sense from string search section, when data is stored in pieces (e.g. characters of string) and search is non-exact match search, it becomes more complex to perform the search. Content can be imagined as bigger form of string and content search is always of non-exact match search. Search a text file using some fragments of contained search falls into this category. Most of the online searches also fall under this category.

Search Categories based on search context: Again there are various ways to categorize the search based on the search context. The most common categorize are as below:

1.      Local: When all the search elements are locally available, we can categorize the search as local search. For example, searching files in files system of your computer, or search any records in your database falls under this category.

2.      Remote Space: When the search elements are remotely available but are definite and properly identified, we can classify the search as remote space search. For example, searching a flight details on service provider website falls under this category.

3.      Virtual Space: When our search domain is wide and unknown, we classify the search as virtual space search. Any online search such as Google search, Yahoo search falls under this category. This most challenging and most wide search category now days. Again we will go in details in next sections (parts).

I would like to stop here as it is pretty wide topic and I would like to start thinking about various available  search tools and their applicability. If interested in search tools, please follow the other blogs with respective details.

Wednesday, March 17, 2010

Application Design: Simple application interface is all about conquering the complexity in the application design

Many times we have listened about simple application design. Whenever I have been through such kind of discussion, the message was purely related to the application design itself and not related to the application interface at all. Often tech designers think about making the application design simple from construction and maintenance perspective which carries a little value as compared to making the application interface simple and intuitive to use. There are some tech designers who follow a different approach (fancy) of application design and use different stacks of technologies and follow all sorts of design patterns.

This makes the application overbuilt for sure and may become hard to maintain as well. In both the approaches, the real motive of application design is missing. We are building the applications for real users and not for ourselves. I strongly believe that the key goal of application design should be usability of the application and the technology or design pattern preference. Building a simple and intuitive application interface is not an easy task. It can only be achieved if we digest all sorts of complexities within the application design and leave the application interface as simple as possible.

Let’s go further and consider few examples of simple interface applications around us today. The very first example with simplest interface comes in my mind is Google website. When we visit home page of Google, all we see are a search bar, couple of buttons and few hyperlinks. Rest of the screen is empty. Looking at the interface of Google website, one can assume that it’s simply designed with simple implementation logic, which is not true. Just thinking about the functionalities supported by this simple UI gives a picture of the complexity digested in its design. Think about how it prepares its inventory which is used in the searches. Think about its search algorithm which returns most appropriate results in fraction of seconds while it performs the searches over huge inventory of data. Think about its result presentation mechanism, its simple enough for novice users as well and it satisfies majority of its users.

Take another example of Amazon’s widely used online store. Though it’s not as simple as Google, but still it’s simple enough to be used by all categories of its users. A user visiting Amazon’s site doesn’t need any application training and also he/she ends up visiting various online help pages. Still he/she is able to fulfill his/her need at the time easily. The only reason of that success is it’s simple and intuitive enough to be used.

These are not the only examples; all popular websites can be found following similar pattern. Also this is not only applicable to a website design; it’s applicable to every design work whether it’s any kind of tool, appliance, product or even presentation.

Now let’s look at the thinking behind applications having fancy interfaces and simple designs. First reason comes in my mind is about doing some thing unique. May times, we overload the application interface by populating it with all sorts of look and feel and also over crowding it with tons of details. This is obviously achieved at the cast of application usability. Next thing is probably about the starting point itself. At many occasions we are fancied about some particular technology/behavior and we try to fit in the applications falling in the way. Learning or ambition should not derive the application design at all but it should be other way round. We should learn and adapt everything which makes the user’s life easier. Last and most important thing I think of, is about our momentarily success. While working on a design, most of the time we tend to adopt the simpler and easy to achieve approach to complete the task easily without many hurdles. Also I have experienced hard negotiations from tech designer’s side to compromise on the usability aspect of the application as it becomes challenging to achieve. If business/user community gives up the battle, we come up with simply designed/build applications with huge number of user training materials. This helps in achieving the pseudo goal and celebrating the success momentarily. All the joy is gone when we start getting user reactions.

All those applications, which were built, sacrificing the user’s experience; they may have been designed/implemented in time/before time. They might have resulted in whole lot of savings of resources (cast and effort). But all applications have failed after a little time just because if user interests. Users tend to find simpler ways to achieve their objective and so called simple designed applications failed to deliver.

The key to success is ease in usability. A user is never concerned of the application/product design and its complexity. Complexity of the application can’t be reduced at any time. A simply designed application is all about shifting the complexity on the user’s side. An application automatically becomes simple to use when all the complexities are conquered in the application design/construction itself. It’s always beneficial to pay an extra price early and write new chapters in success stories. Whenever it will be a matter of choice, I would always go for a simple application user interface than simpler application design. It would be best if I can achieve the simple application interface by having simple design in place. But I would never make user’s life challenging to make my own life simpler. 

Application Design/Implementation: Writing Modular and Clean

Some time back, I was going through a piece of Java code written by someone (my apologies, no wrong intention/no offence). My objective was to find out scenario specific details by looking at the code (a kind of small reverse engineering job). When I started, I thought it was a simple task assuming it’s a Java class and it would be quite modular and clean enough to understand. As soon as I opened the class file, all my assumptions were gone. First, it was a class file with around 2000 lines. Just for curiosity, I looked at some other class files in the application and found that there are class files up to approximately 10000 lines of code. It looked like; there was a prize for generating biggest class file.

Keeping the size aspect aside, I started looking at the class file of my interest. At this point I was bit relaxed that at this class file is relative much smaller as compared to other class files in the project. As soon as I started looking at the methods, I was lost. There were only few methods in the class (4 or 5) and the method of interest was of around 1000 lines. We can simply assume that 1000 lines of code couldn’t be straight forward and sequential. This method/class was no different. I couldn’t make out any thing about the flow of the logic. After scratching my head for couple of hours and drawing few interesting sketches about the flow, somehow I made a conclusion and handed over my summary.

Once this task was done, I started thinking about Object Oriented Analysis & design (OOAD) principles. When I think about OOAD, the very first thing I think of a modular and clean design. Even if I ignore the OOAD aspect and think about standard code quality aspect, this kind of code clearly falls in poorest design/implementation category. This code is not at all maintainable, as it’s hard to understand. I am sure, if the original developer looks at this code after some gap, he can’t make much from it himself. I can’t think of a single reason of writing such a code which makes our own life tough.

Writing a modular, cleaner and simple code is not a big magic. If we follow some simple design/implementation principles in mind, we will always result into nice, clean and modular code without doing anything especially for it. Let’s look at some of the key design/implementation principles and its applicability through an example of student result calculator functionality. I am considering Java class in the example, but this concept can be easily applied in other programming languages as well such as PL/SQL, C/C++ etc.

1. Complete Picture of the functionality: This is the first task to start with. Get a clean picture of the class/module required functionality. This helps significantly in identifying the design/implementation approach.

Let’s consider our example of deciding result and calculating marks percentage of a student. Assume there are 3 subjects with max score of 100 each and 40 is the passing mark in each subject. This gives a clear picture of required functionality at high level.

2. Core vs. Secondary responsibility of the class: Before starting with the code, get a clean understanding of primary vs. core responsibility of the class. Only primary responsibility should be implemented as part of the current class. The secondary responsibility should be implemented in a helper/util class.

In our example, validating that all subjects have corresponding marks should be implemented as validator helper class (e.g. MarksValidator); calculating the percentage should be implemented as util class (e.g. MarksUtil) class and the core flow of the responsibility remains in the primary class (e.g. StudentResult). Thus we will have three classes instead of one with clear defined responsibilities.


3. Resolution of not having bigger methods/classes: Looking at the application functionality, we should make a resolution of not designing/implementing classes/methods of more lines than a predefined size. Typically any class shouldn’t exceed more than 100 lines and any method shouldn’t exceed more than 10 lines. We can defined out own limits but it should definitely be small (e.g. a class shouldn’t go in 1000 lines and method in 100 lines)

4. Top-down Design/Implementation: Once we have identified classes with defined responsibilities, we can start implementing the functionality following top-down approach. By top-down, I mean start implementing higher level steps in primary method and support each/applicable steps with secondary methods.

In our example, let consider StudentResult class. We can have high level implementation of the class as below:

            public class StudentResult{
                        private Student student;
                       private List subjects;
                     
                      public void declareResultAndPercentage(){
                             String result= getResult();
                             System.out.println(“Result=”+ result);
                            Double percentage = getPercentage();
                            System.out.println(“Percentage=”+ percentage);
                     }
          }
If we look at the class, it’s very straight and self descriptive. In my main flow, I have two helper method calls with clear expectation.

5. Incremental Design/Implementation: By incremental, I mean that unwind the steps in incrementally. We should not jump on the entire method functionality and implement in one method itself as I mentioned in the beginning. Rather unwind the functionality one level at a time. Sub level logic should move to a next level method class.

Considering our example, our first level method has only two high level steps e.g. finding the result and calculating the percentage. Now let’s move to second level method implementation as below.

            public String getResult(){
                 String result = failed;
                 boolean isAllMarksAvailable=
MarksValidator.isAllMarksAvailable(subjects);
    boolean isPassedInEverySubject=
 MarksValidator. isPassedInEverySubject(subjects);

                if(isAllMarksAvailable && isPassedInEverySubject ){
                        result = “Passed”;
            }
            return result;
        }
      
Similarly I can unwind my second method as below:
           
public double getPercentage(){
        List marks = getAllMarks();
       Double percentage = MarksUtil.calculatePercentage(marks);
      return marks;
}

At this point of time, we are not done but completed another level of implementation. I can look back and see, there are some next level unimplemented methods (i.e. getAllMarks()) in the same class and some in secondary classes (i.e. isAllMarksAvailable(subjects) & isPassedInEverySubject(subjects) in MarksValidator class and calculatePercentage(marks) in MarksUtil class). We can follow the same pattern until we are done.

Advantage: Needless to say, a modular code is more clean, readable and maintainable (less error prone). If a developer wants to refer a particular part of functionality, he can pin point it very easily without spending much time or looking for big documentation. Scope of any fix is limited and impact can be clearly identified.

Monday, March 15, 2010

Starting with Google Web toolkit (GWT) in Eclipse


Google Web Toolkit (GWT) is a web development toolkit is an AJAX framework developed by Google. It’s a very good initiative from Google to provide a niche way to implement an AJAX based web application. More details about GWT can be found at Google web site (http://code.google.com/webtoolkit/). To know usability and limitations of GWT, please refer “GWT: Uses and Limitations”.

Installing GWT SDK and Eclipse plug-in is pretty straight forward which is apparent from the steps below.

GWT SDK Installation (optional):

  1. Download GWT SDK from Google website (http://code.google.com/webtoolkit/download.html)
  2. Extract (unpack) the GWT-x.x.x.zip archive file contents to some folder in the files system e.g. C:\GWT
  3. Add the above folder i.e. C:\GWT into the path variable.
  4. This completes GWT SDK installer. To verify the installation, try opening a command prompt and run the command “webAppCreator”. If it asks for arguments, the installation can be considered as done for now.

Eclipse plug-in Installation:

  1. Open the eclipse editor.
  2. Go to Help ->Install New Software
  3. Add GWT plug-in update site as http://dl.google.com/eclipse/plugin/3.3 or http://dl.google.com/eclipse/plugin/3.4 or http://dl.google.com/eclipse/plugin/3.5 depending on the eclipse version.
  4. Select the above site and follow the instructions to install GWT plug-in in eclipse. Select the appropriate GWT version in intermediate screen.
  5. At this point, we would be able to see extra icons (Google Compile, Create GWT Web application) in Eclipse command bar.
  6. If at any point of time, we want to change the GWT SDK version to its standalone version, we can change by following two simple steps.
    1. In eclipse, go to Window ->Preferences -> Google -> Web Toolkit
    2. Click on add, and select the GWT installation directory such as C:\GWT and check the check box in front of it.

Creating first GWT Application:

  1. To create a GWT application, simply create on icon in Eclipse Command bar to create GWT Web Application.
  2. In the new dialogue screen, provide the details as below:
    1. Project Name: Name of the project e.g. MyFirstProject
    2. Package: the starting package for the web application e.g. com.first.myproject
    3. Check the check box for GWT SDK and make sure the right version is selected.
    4. Uncheck the checkbox for “Google App engine” and click finish.
  3. At this point, “MyFirstProject” is created in the workspace with all required class path defined and a default entry point class named “MyFirstProject.java” in com.first.myproject package.
  4. Right click “MyFirstProject” in workspace and select Google -> GWT compile. It should open a new dialogue showing “MyFirstProject” as entry point. Make sure it’s selected. If required change the logging options, and output style. Click on compile.
  5. It should compile the “MyFirstProject” project without any error and “Compilation succeeded” should appear in workspace console.
  6. To run the application, right click on “MyFirstProject” in work space and select Run As-> web Application. It should start the application in hosted mode. We should see two new windows open. One window is for GWT inline server console and other has the application start page having welcome message and “Click Me” button.
  7. If all above steps passed successfully, congratulations!! Our first GWT web application is created and running in hosted mode at this point.
  8. To run the application on any other web server such as Tomcat, just add the project to the server (if server is running within eclipse) or export the project as WAR file and deploy it on the web server.

Now let’s go through the most important section which is about understanding the GWT application components. We will consider above project as our example.

Understanding the GWT Application components:

  1. If the above created project “MyFirstProject” is opened in navigator view, we can see following files.
    1. Under “src” folder of the project, there will be full package structure i.e. com/first/myproject
    2. Under the last folder i.e. mypoject, we should see two folders namely “client” and “public” and one xml file named as “MyFirstProject.gwt.xml”.
  2. Client package a very important package and it’s used in the client module of the application. All the classes within this package should be self contained and shouldn’t have any reference to classes not available to client server including the server side code of the MyFirstProject project.
  3. MyFirstProject.gwt.xml is the configuration file for the MyFirstProject project and all GWT specific configurations are to be made in the file including the constructs to include certain external files/components into client application.
  4. Public package contains the generated HTML/JavaScript and is used as the starting page of the MyFirstProject application.
  5. MyFirstProject.java extends com.google.gwt.core.client.EntryPoint class implements the method onModuleLoad () which is the starting point of the application.

To understand client/server concept of GWT, let’s create one simple dummy service and make use of it in the section below.

Working with GWT:

  1. Assuming the GWT is installed and first application is successfully created, let’s enhance the “Click Me” button functionality to retrieve the greeting message from the server.
  2. To achieve the above functionality, create an interface called GreetingService in com.first.myproject.client package @RemoteServiceRelativePath ("greet").
  3. Add a method signature as below in GreetingService.java
public String getGreetMessage ();
  1. Create another interface named GreetingServiceAsync in com.first.myproject.client package with a method signature as below:
public void getGreetMessage (AsyncCallback < String > callback);
  1. Create a new package as com.first.myproject.server
  2. Create a GreetingService implementation class named GreetingServiceImpl with a method as below:
public String getGreetMessage () {
      String welcomeMessage=”Welcome to the GWT world”;
 return welcomeMessage;
}
Note: Service interface and Service Async interface is created in client package while service implementation is created in server package.
  1. Now open previously created entry point class named “MyFirstProject” and change implementation of button.addClickListener(new ClickListener() {.. as below:
button.addClickListener (new ClickListener () {
   public void onClick (Widget sender) {
          GreetingServiceAsync greetingService = (GreetingServiceAsync)GWT.create(GreetingService.class);
greetingService. getGreetMessage(new AsyncCallback() {
      public void onFailure(Throwable caught) {
            label.setText("server call failed!");
           }
          public void onFailure(String messageFromServer) {
            label.setText (messageFromServer);
           }

}
  1. This completes the implementation of first asynchronous service call the server on click if “Click Me” button.
From the above example, it’s clear that in GWT application, there is a clear separation on client and server side code. Above all, every call to server is an asynchronous call and all the UI components are created in Java using style elements except the welcome page.

Google Web Toolkit (GWT): Uses and Limitations

Google Web Toolkit (GWT) is a web development toolkit is an AJAX framework developed by Google. It’s build using Java as baseline language and allows J2EE developers to implement AJAX behavior in their web application without being expert in
XmlHTTPRequest /JavaScript. GWT comes with it own compiler called GWTCompiler.  All the application development including UI is done using GWT libraries. Once the application is compiled using GWTCompiler, it produces the HTML, JavaScript as part of client side component.

Going little further in deep, an application is divided into tow parts namely client and server components. All the calls made from client to server are asynchronous. Please refer “Starting with GWT” for more details on GWT basic architecture.

Coming to its uses and limitations aspects, let’s go through its uses first and then the limitations.

Usage of GWT:

  1. GWT framework usage Java as baseline language and hence can be easily integrated into Java applications.
  2. Since programming constructs are very similar to Java, learning curve is very small.
  3. By default, all the requests made by client is asynchronous, the application with much complex client server interaction becomes much more efficient without much effort investment.
  4. GWT has plug-ins available for major IDE such as Eclipse, IntelliJ IDEA etc.
  5. GWT comes with its own testing server (Tomcat) called Hosted mode, and provides feature to quickly validate the functionality implemented right through the IDE itself.
  6. Since the application can be run in Hosted Mode from the IDE itself, debugging the application becomes very easy especially the UI components.
  7. Entire application including UI is developed using Java and Style sheets. No JavaScript, HTML is involved in a typical web application developed using GWT.
  8. All the internal URLs of the applications are hidden from the user/hackers and can't be accessed directly bypassing the entry point of the application.
  9. It supports custom calls of native JS functions if any, though not recommended ant not easy.
  10. Other features such as Internationalization (i18n), logging are well supported in GWT.
  11. GWT compiler optimizes the UI code automatically. It removes any dead code during compilation time. Also by setting split-points in the code, it can also segment any download into multiple JavaScript fragments, splitting up large applications for faster startup time.

This is only the first side of the GWT. Let’s look at the other side of it i.e. limitations of using GWT.

Limitations of GWT:

  1. All the client code should be clearly bundled with client package. If any server class is referenced in the client code, results into GWT compilation issue without a very clear message. This becomes trickier as both client and server java files are part of the same source code structure.
  2. GWT compiler output is not very clear and results into very high level compilation errors messages resulting into more effort into finding the root cause of the compilation error.
  3. Every call in GWT application is asynchronous so if there are any synchronous calls required, they have to be grouped in a single call otherwise need to be tricked with group of asynchronous calls.
  4. While writing client side code having multiple asynchronous calls involved, it becomes very tricky to uses out put of the first call into second call.
  5. It becomes more error prone when multiple asynchronous calls are involved in one user request. Developer uses class level variables to pass the details from one call to the other. This way the coding is done without any compilation error. Since the calls are asynchronous, we can’t guarantee the request processing time of individual calls. This leads into inconsistent behavior in the application. If not properly handled, the application may work/may not work as expected depending on the sequence of various individual asynchronous calls processing.
  6. Entire UI is developed using Java (GWT) and Style Sheets. This leads into same issues as servlets (UI elements tightly coupled in Java) and eliminates the advantage of having JSPs.
  7. If the code is running fine in hosted mode, but not running properly in real application deployment, it becomes very difficult to troubleshoot the code as the generated code from the GWTCompiler (which is actually running in production mode) is not very readable.
  8. All the UI is created using generated JavaScript; it becomes very sluggish in case of complex screens. Sometimes it even becomes unresponsive depending on the browser capabilities.
  9. Since all the calls are made asynchrous using JavaScript and also the application page is created using JavaScript, it results into browser alerts quite often stating the page performance.
  10. Creating a screen with complex page layout becomes very tricky as not all HTML elements are supported through GWT.
  11. Novice users result into excessive use of the UI components (various panes e.g. Horizontal Pane, Vertical Pane) and later get confused about their positions and usage as they can be instantiated at any place in the code but only appear in UI at place where added to the base component.
  12. No assistance from UI editors such as Macromedia Dreamweaver.
  13. Generated UI can’t be inspected for its UI components using any current UI inspectors such as IEInspector as all the UI is painted using DHTML/JavaScript.

To summarize, GWT is a very useful framework for application having simple UI with lot of client server interactions involved (where AJAX is a required/applicable feature). It’s not suitable for an application with few requests (one or two) per screen and especially if the screen layout involves huge number of screen components. Many of the times, I have seen wrong usage of GWT where we bear with its limitations but not able to utilize its capabilities. Hence before going for GWT in any application, its applicability should be critically evaluated.

Friday, March 12, 2010

HOT deployment setup from Eclipse to Weblogic server

When we are working on an enterprise application which consists of various modules and in big size, most of our development time is spent in building the application and redeploy on the Weblogic server to validate our changes. While we are updating one or two files at a time, still we are repeating the above steps all the time. This repeating deployment is resulting into slow validation and hence less productivity.

Below is the list of steps, if followed enables the hot deployment of our source code (useful in most of our working scenarios) without affecting any existing processes in place.

Weblogic Side Configuration:
1. Undeploy current enterprise application from Weblogic server.
2. Stop the Weblogic server
3. Create a folder named "MyEar" <Enterprise App Name> in applications folder in your Weblogic domains folder e.g. "C:\bea\user_projects\domains\mydomain\applications\"
4. Open the application ear with some zip utility and extract all the files into "MyEar" folder created in step2.
5. Create a blank file with the name as "REDEPLOY" in MyEar/APP-INF/META-INF folder.
6. Create a folder name "classes" in MyEar/APP-INF folder.
7. Extract the application web module(s) into a folder named "<Web Module Name>.war" in MyEar folder and remove the war file(s) from the folder.
8. Start the Weblogic Server, open admin console, and deploy MyEar<Enterprise application> Application by selecting MyEar<Enterprise application> folder.
9. If the deployment fails detailing any particular module, please open the respective module and correct the MANIFEST.MF file entries.

Eclipse Configuration:
1. Open Eclipse IDE
2. In each java module folder in workspace, create a file named as moduleBuild.xml <we can provide any name of our choice> with details below:

<project name="MyModule" default="hotDeploy" basedir=".">
<property file="build.properties"/>
<target name="hotDeploy">
<delete dir="${dl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes"/>
<mkdirdir="${wl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes"/>
<copy todir="${wl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes">
<fileset dir="${service.project.dir}/${build.dir}/classes"/>
</copy>
<touch file="${wl.dm.dir}\applications\${dep.ear.folder}\META-INF\REDEPLOY"/>
</target>
</project>


3. Create a file named build.properties with entries below(update the values as the local settings):
service.project.dir=../MyService
build.dir=build
dep.ear.folder=MyEar
wl.dm.dir=C:\bea\user_projects\domains\mydomain\applications


4. In each web module folder in workspace, create a file named as moduleBuild.xml <we can provide any name of our choice> with details below:

<project name="MyModule" default="hotDeploy" basedir=".">
<property file="build.properties"/>
<target name="hotDeploy">
<delete dir="${dl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes"/>
<mkdirdir="${wl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes"/>
<copy todir="${wl.dm.dir}\applications\${dep.ear.folder}\APP-INF\classes">
<fileset dir="${web.project.dir}/${build.dir}/classes"/>
</copy>
<copy todir="${wl.dm.dir }/applications/${dep.ear.folder}/${dep.war.folder}/jsp/${jsp.dir}">
<fileset dir="${web.project.dir}/WebContent/jsp/${jsp.dir}"/>
</copy>
<copy todir="${wl.dm.dir }/applications/${dep.ear.folder}/${dep.war.folder}/js/${js.dir}">
<fileset dir="${workspace.web.project.dir}/WebContent/scripts/${js.dir}"/>
</copy>
<touch file="${wl.dm.dir}\applications\${dep.ear.folder}\META-INF\REDEPLOY"/>
</target>
</project>


5. Create a file named build.properties with entries below(update the values as the local settings):
web.project.dir=../MyWeb

web.project.dir=../MyWeb
build.dir=build
dep.ear.folder=MyEar
dep.war.folder=MyWar.war
jsp.dir=myJsp
js.dir=myJs
wl.dm.dir=C:\bea\user_projects\domains\mydomain\applications


6. Right click each modules (including both Java and Web Modules)
7. Select properties from the menu
8. Select builds from the properties screen, and click on the "New" button in right side
9. In new screen, select Ant builder and hit "OK"
10. It opens "Edit Launch Configuration" screen.
11. Put any suitable name is the name field
12. In the main tab, browse the respective build xml file (moduleBuild.xml) from the project folder in workspace
13. go to targets tab, set the default target available in first three sections namely "After a Clean", "Manual Build" and "Auto Build"
14. Click Apply and OK to close the window
15. Click OK to close the other underlying window.
16. Once Steps 6-15 are completed for each module; restart your eclipse.


Now you are all set. If you are working on any jsp/js/java file (except EJBBean interface) through your eclipse IDE, your files are hot deployed on the Weblogic server in few seconds. Don’t forget to update Base Module JAR files in deployed MyEar<Enter

Hope this will be helpful in your development activities.