Sunday, February 14, 2010

GWT and UIBinder Password Asteriser/Fader

This tutorial shows how to fade the password into asterisks when the user mouses out of the password field. Instead of using a password input type, we would use a text input type with the asterisation/deasterisation performed algorithmically on Mouseout and Mouseover events.

Some user authentication techniques has a [Show Password] checkbox, which when checked would show the password you are keying in rather than hiding it. After you have keyed in your password and visually verified its correctness, if you are really diligent, you might uncheck it to asterise it (turn it back into a string of asterisks/stars).

However, isn't it better if the password field asterises itself when the user moves focus away from the password field. Here is how you could do it, using GWT.

If you don't want to use GWT, you could translate the asteriser routine documented here into javascript.

The tutorial is found at Google code svn
under the namespace

The UIBinder pwfade.ui.xml
<!DOCTYPE ui:UiBinder SYSTEM "">
  <g:VerticalPanel horizontalAlignment="ALIGN_RIGHT" ui:field="allFields">
    <g:Label>Enter Name and Password, then click [Log in]</g:Label>
     columnCount='2' rowCount='3'>
      <g:TextBox ui:field="name" width="15em"/>
      <g:TextBox ui:field="password" width="15em"/>
      <g:Button ui:field="logIn" text="Log in"/>

The UIBinder bean as well as the module entry point
public class PasswordAsteriser
  implements EntryPoint

  private static PasswordAsteriserUiBinder uiBinder =

  interface PasswordAsteriserUiBinder
    extends UiBinder<Widget, PasswordAsteriser>

  VerticalPanel allFields;
  TextBox name, password;

  private String passwordString;

Here is where the asterising/deasterising action is
//on Mouseout asterise the field and deasterise on Mouseover
  @UiHandler ("password")
  public void asteriseOnMouseOut(MouseOutEvent event){
    this.passwordString = password.getText();
    String masked = "*****";
    for(int i=5; i<this.passwordString.length(); i++)
      masked += '*';
  @UiHandler ("password")
  public void deasteriseOnMouseOver(MouseOverEvent event){

  void onClick(
    ClickEvent e){
    Window.alert("Name:"+name.getText() + "\nPassword:" + this.passwordString);

  public void onModuleLoad(){

Unfortunately, UIBinder is not too mature currently to have a well provisioned layout policy. You have to extend Grid class to provide add(Widget) method for the benefit of the ui.xml.

Here, UIGrid extends Grid. Note that the constructor for UIGrid is annotated with @UiConstructor so that the arguments rowCount and columnCount are associated with UIGrid's ui xml attributes of the same name rowCount and columnCount.

  static public class UIGrid
    extends Grid
    public @UiConstructor UIGrid(
      int rowCount,
      int columnCount)
      this.resize(rowCount, columnCount);
    public void setRowCount(int n){
      this.numRows = n;
    public void setColumnCount(int n){
      this.numColumns = n;
    public void add(Widget w){
      int row = this.count/this.numColumns;
      int col = this.count - row*this.numColumns ;
      if (this.numRows<row)
      this.setWidget(row, col, w);

    public void add(String t){
      int row = this.count/this.numColumns;
      int col = this.count - row*this.numColumns;
      this.setText(row, col, t);
    protected int count=0;

The layout classes in UIBinder (like Grid and Flextable) should also be further enhanced to work directly with the ui.xml and not require us having to create extension classes. The very idea of using UIBinder is to reduce coding not increase it.

Here is the GWT launching html.
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link type="text/css" rel="stylesheet" href="pwfade.css">
    <title>Password Asteriser Example</title>
    <script type="text/javascript" language="javascript" src="pwfade.nocache.js"></script>
    <h1>Password Asteriser Example</h1>
    <div id="allFields"/>

Toyota and the Normalization of Human Relations

What has fr#$@%^&*kin happened to Toyota? Did it not used to be the pride of technologists' example company of developing methodologies for and doing things the right way, knowing the right goals, having the right people, defining the right problem, achieving the right quality, using the right tools, having the right approach and so on?

Steve Wozniak and many others have been complaining of their Prius having unwanted cruise acceleration problems -

Toyota spokespersons keep stonewalling customers by claiming, it's not our fault, or that we have done our homework and have solved the problem and there's no possibility of any other cause because you know what, we are the best auto company in the whole gdamnedded world and you nitwits have no expertise or qualifications or any insight to the actual issues involved.

A Toyota of the 1980s would have invited Steve to bring his Prius in for free checkup and coffee klatch and then problem identified and Steve would have gone home happily telling the world that Toyota is the world's best and most customer attentive company in the world.

But not the Toyota of today. Nor the Sony.

The fault lies with information technology. More precisely, due to information technologists and our success at doing our jobs. The ideology at fault is called data and information normalization.

Normalization is buying a portfolio of stocks where many might individually be bad buys but when statistically normalized the portfolio on the whole would present annual growth of 12-15%.

Normalization is advertisement placement on a portfolio of selected media and target audience that many in their individual channels would present publicity risks but as a portfolio would grow the popularity of a product 18-35% every quarter.

Normalization is when a newbie to a technology forum asks an innocent question but the answer is already found behind thousands of confusing lines of the manual and the gurus and high ranking clergy of the forum votes the question down, flames the question and tells the newbie go read the faqqing faq.

Normalization is the uniform treatment and the reduction of diversity so that you could throw a stone and kill a thousand birds. Normalization is the streamlining of relations within entities so that one and only one channel exists between entities. Normalization is the efficient use of human attention to details and the minimalist reductionism of details by abstraction of details into empiricals.

Normalization is the search engine giving answers that are acceptable to 96.5% of the audience. The other 3.5% are non-profitable outliers.

In quantum electronics is the phenomenon called tunnelling - the exploitation of the capability of events of near zero probabilities to perform major functions by growing the volume of those events.

But Toyota, and to some extent Honda, seems to have forgotten that it was their relentless exploitation on the tunnelling phenomenon of outliers and then growing the size of outliers, which when having caught American and European automakers by surprise, it was too late for them Americans and Europeans to react.

The triumph of Japanese technologists over American and European was their return to basics to having the proper perspective of information normalization. And the Japanese happily and proudly shared and preached their perspective. Today, sadly, they seem to have lost that perspective. Their semiconductor business have lost ground to the Koreans, Taiwanese and Americans.

Normalization is complacency. OK, actually normalization is good but obsessive normalization is evil complacency. Even we, information technologists know that. The holy grail of Boyce Codd Normal Form is at best an idealism - for performance' sake we normally settle for 2.5 normalization.

I wish Kia, Ford and the new General Motors well in exploiting the weakness of the Japanese technologists of late and run the race as good underdogs because normally the good underdogs are the ones who provide the best service to win the race.

Just remember, consumers perform well as normalizable statistics in the short-term, with their individuality unresolved, but in the long run, they are humans who can collectively extinctify your products or even your company.

Wednesday, February 10, 2010

Tutorial: GWT RPC Stub modified with UIBinder

GWT RPC is a very significant reason to use GWT. GWT RPC sets up a http channel between a web page with the server so that the web page and the web server could transmit data to each other without the web page being refreshed or flipped.

The Google plugin for Eclipse creates a stub GWT RPC example whenever we choose to create a new GWT project. This tutorial modifies that stub in a few points.
  • Use of GWT UIBinder by providing the UI definition in Z.ui.xml
  • is renamed to
  • Use of HashMap instead of String in client-server RPC communication.
  • Change of servicing class name from GreetServiceImpl to SendGreeting.
  • Change of package namespace to com.blessedgeek.gwt.examples.greet.
The code for this tutorial is found in,
where the actual code of the service and async interfaces are derived from genericized interfaces, and therefore differs a little from this tutorial but is functionally equivalent.
The genericized interfaces used in the actual code is found at

The GWT module is Z and the module file is /com/blessedgeek/gwt/examples/greet/Z.gwt.xml. According to the rename-to attribute, the module is to be made available by the web server through the context URI /blessed.
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='blessed'>
  <inherits name=''/>
  <inherits name='org.synthful.gwt.http.servlet.OriginServerCall'/>
  <inherits name=''/>
  <entry-point class='com.blessedgeek.gwt.examples.greet.client.Z'/>
  <source path='client'/>

GWT RPC requires a web service to be created on the server, with which the async client communicates. As in the original stub-example, the service needs to be declared in war/WEB-INF/web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  <!-- Servlets -->
  <!-- Default page to serve -->

According to the above web.xml, sitting in the namespace com.blessedgeek.gwt.examples.greet.server, the class that provides the web service is SendGreeting (was named GreetServiceImpl in the original stub-example code). SendGreeting service is made available by the web server through the URI /blessed/greet/.

An interface to be implemented by the web service has to be defined, wherein the relative path to the URI /blessed/greet/ should be declared. Since the GWT module and the RPC web service will sit on the same parent URL /blessed, only the relative path greet needs to be defined. Hence the annotation @RemoteServiceRelativePath("greet").
package com.blessedgeek.gwt.examples.greet.client;

* The client side stub for the RPC service.
public interface GreetingService
  HashMap<String, String> doServiceResponse(HashMap<String, String> input);

A matching interface, to be implemented by the GWT client, has to be defined. It's name and path must be similar to the service interface but suffixed by Async. Therefore, GWT client interface is GreetingServiceAsync.
package com.blessedgeek.gwt.examples.greet.client;

* The async counterpart of <code>GreetingService</code>.
public interface GreetingServiceAsync
  void doServiceResponse(
    HashMap<String, String> parameters,
    AsyncCallback<HashMap<String, String>> callback);

The client async interface must define the method doServiceResponse as defined in the service interface, but with pattern

if service interface method is
ReturnType serviceMethodName (ArgType)

then the async interface method must have the pattern
void serviceMethodName(

where AsyncCallback is a GWT RPC method which would facilitate the calling-back of the client side serviceMethodName.
Instead of String objects being transmitted in the original example code, the code of this tutorial effects the transmission of HashMap objects between the server and the client.

This is the service servlet addressed by the URI /blessed/greet, which implements GreetingService interface. Rather than constructing the whole text to be displayed by the client as in the original example, this sends only the parameters.
package com.blessedgeek.gwt.examples.greet.server;

import java.util.HashMap;
import java.util.Map;
import com.blessedgeek.gwt.examples.greet.client.GreetingService;

* The server side implementation of the RPC service.
public class SendGreeting
  extends RemoteServiceServlet
  implements GreetingService

  public Map<String, String> doServiceResponse(
    Map<String, String> input){
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("serverInfo", getServletContext().getServerInfo());
    params.put("userAgent", getThreadLocalRequest().getHeader("User-Agent"));
    params.put("name", input.get("name"));
    return params;

This is UIBinder Z.ui.xml, which defines the dialog box.
<!DOCTYPE ui:UiBinder SYSTEM "">
<ui:UiBinder xmlns:ui=""
    .sendButton {
      display: block;
      color: blue;
      font-size: 16pt;
    <g:HorizontalPanel ui:field="hPanel">
      <g:Button ui:field="sendButton" text="Send"
       styleName="{style.sendButton}" />
      <g:TextBox ui:field="nameField" text="GWT User" />
    <g:DialogBox ui:field="dialogBox"
     text="Remote Procedure Call"
      <g:VerticalPanel horizontalAlignment="ALIGN_RIGHT">
        <g:Label>Sending name to the server:</g:Label>
        <g:Label ui:field="textToServerLabel" />
        <g:Label>Server replies:</g:Label>
        <g:HTML ui:field="serverResponseLabel" />
        <g:Button ui:field="closeButton" text="Close" />

/com/blessedgeek/gwt/examples/greet/public/Z.html the GWT launching HTML file:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link type="text/css" rel="stylesheet" href="Z.css">
    <title>Web Application Starter Project</title>
    <script type="text/javascript" language="javascript"
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    <h1>Web Application Starter Project</h1>

    Please enter your name and click [Send]:
    <div id="here"/>
Take note of id here, which would be used as the root panel launch pad.

The GWT Java-source bean that captures the ui definition in Z.ui.xml must be named The Java-source bean need not implement EntryPoint, but in this case it is made an EntryPoint. The GWT Java-source bean will be compiled into client-side script by the GWT compiler.

The bean defines an arbitrarily named interface LilyUiBinder which extends UIBinder, which is to be bound to the instance of class Z.
Notice GWT.create deferred binding for LilyUiBinder.
And GWT.create deferred binding for GreetingServiceAsync using GreetingService.class.
public class Z
  implements EntryPoint
  interface LilyUiBinder
  extends UiBinder<Widget, Z>{}
  private static LilyUiBinder uiBinder = GWT.create(LilyUiBinder.class);
   * Create a remote service proxy to talk to the server-side Greeting service.
  private final GreetingServiceAsync greetingService =

The bean variables bound to fields in Z.ui.xml.
  HorizontalPanel hPanel;
  Button sendButton;
  TextBox nameField;

  //Fired when user clicks send Button
  public void sendOnClick(ClickEvent event){

  //Fired when user types in the nameField.
  public void nameOnKeyUp(KeyUpEvent event){
    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER){

  DialogBox dialogBox;
  Label textToServerLabel;
  HTML serverResponseLabel;
  Button closeButton;

  public void closeOnClick(ClickEvent event){

Normally, the UIBinder deferred binding is done at the bean constructor, but it may be done at onModuleLoad of an EntryPoint object that also happens to be a UIBinder bean. Notice  the method sendNameToServer which would be called by the uihandlers defined earlier. callBack is the client-side routine that would be called-back when the server returns data to the client.
public void onModuleLoad(){
    nameField.setText("GWT User");

  private void sendNameToServer(){
    HashMap<String, String> params = new HashMap<String, String>();
    String textToServer = nameField.getText();
    params.put("name", textToServer);


  private final AsyncCallback<Map<String, String>> callBack =
    new AsyncCallback<Map<String, String>>(){
      public void onFailure(Throwable caught){
        // Show the RPC error message to the user
          .setText("Remote Procedure Call - Failure");

      public void onSuccess(Map<String, String> result){
        dialogBox.setText("Remote Procedure Call");
        String s = "Hello, "
        + result.get("name") + "!<br><br>I am running " + result.get("serverInfo")
        + ".<br><br>It looks like you are using:<br>" + result.get("userAgent");


Notice that sendNameToServer sends the text field value to the server in a hash rather than as a string. Sending in a hash would be necessary when there is more than one parameter to send to the server. Notice that at onSuccess, it also receives data from the server in a hash rather than a string.

It should be noted that due to restrictions of any pre-version 5 HTML, GWT is only half-async. The client has to initiate communication with the service. Therefore, to masquerade as full-async, the GWT client has to set up a polling loop to let the service the opportunity to pseudo-push data to the client. I recommend a polling sleep of no shorter than 5 seconds or if acceptable - 20 seconds.

Monday, February 8, 2010

Why Generics

Let's say you have an array of Process objects.
Process[] procs;

However, you find that an array has a fixed length and you wish to store only the processes that has been created within the latest one minute rolling window. Using an array as a FIFO pipe would also be rather inconvenient, so you decide to use a List. But then you would find that using a List, you could have no control over what other routines put into it before passing it to your routines. Therefore, you wish to make sure it is a List of Process objects only. Generics allow you to constrain
List<Process> proclist;

So that, now you can have a method to handle a list which you could ensure contains only Process objects:
public float meanCreationInterval(List<Process> proclist){
  .... }

Frequently, you also wish to constrain the contents of a Hashtable. The following would allow you to constrain your hashtable to contain only EmployeeId as keys, and PostalAddr as values:
Hashtable<EmployeeId, PostalAddr>

Let's say you have a base class with a method getEmployee(EmployeeId id)
class Employee {
  public Employee getPerson(EmployeeId id){ ....}

Then you extended Employee class for a specific case of Engineer

class Engineer extends Employee { ....}

But when you tried to use the parent getPerson method, you discovered, holy cow, it returns an Employee object but you want it to return an Engineer object. You could use casting, but frequently you receive an extended class as a base class and you have to write code to test what subclass it is to cast it. What if someone uses your library and passes it a subclass that you never knew existed? So you genericize your base class
class Employee<P extends Employee<?>>{
public P getPerson(EmployeeId id){ ....}

Then programmers would extend it as
class Engineer extends Employee<Engineer>{ ....}

So that, now getPerson method would return an Engineer object if the extension class is Engineer or a Manager object if the extension class is Manager, etc.

Let's say you have base classes Canvas and Window.
class Canvas<W extends Window<?>> {
  private W window;
  public W getWindow();
class Window<C extends Controller> {
  private C controller;
  public C getController { return controller;}

Then you have extension classes
class JoyStick implements Controller {
  public int getRate() { ... }
class KeyboardArrowKeys implements Controller {
  public float getPixels(){...}

MainWindow extends Window <JoyStick>{ ... }  
Popup extends Window <KeyboardArrowKeys>{ ... }  

Generics can be used to constrain not only extension of a class, but also the type arguments of the members of that class being extended
MainWindow win = new MainWindow();
Popup pop = new Popup();
  .getRate(); // allowed
  .getPixels(); // error: getPixels method not found

  .getRate(); // error: getRate method not found
  .getPixels(); // allowed

Generics can be defined as deep as is required to constrain members of any depth.
public abstract class Vehicle
<V extends Vehicle<?,?>, D extends Dashboard>
{  .... }

public class Dashboard
 <D extends Dashboard, S extends Speedo<?>>
{  .... }

public class Speedo<Sh extends Shape>
{  .... }

public class Shape<Sh extends Shape>
{  .... }

//Square needs any super class of Analogue
public class Square<D super Analogue>
  extends Shape<Square>
{  .... }

public class Analogue
  extends DispTech
{  .... }

public class Sedan
 extends Vehicle<
{  .... }

Define a Sedan Vehicle type,
but it must have a Dashboard,
where the Dashboard must have a Speedo,
and the Speedo must have Square as Shape,
and the Square needs DispTech as the specific super class of Analogue.

However, using generics for too deep number of levels can be very obfuscating.