Saturday, December 3, 2011

GWT with JAX-RS (aka RPC/REST) Part 1


Come unto me all ye who are weary of heavy-laden clients and I will give you REST.

Continued from GWT with JAX-RS (aka RPC/REST) Part 0 (preamble ramble)


JAX-RS REST with GWT is equivalent in mechanism to GWT-RPC. The similarity lies in the requirement for
  • a common Data Transfer Object interface (DTO) between client and server
  • a common Remote Procedure API, using the shared DTO definitions are arguments, between client and server;
    where REST calls it Remote Service API (rSAPI), GWT-RPC calls it Remote Procedure Call.
    where the Remote Service API specifies a return type;
  • server implementation which follows the rSAPI interface.
  • a client version of the service API (cSAPI) which includes a callback; where return_type is the return type specified in the rSAPI; so that the cSAPI returns void, translating return_type as an argument to the callback
  • client implementation which follows the cSAPI interface.

RPC over REST
JAX-RS had been invented/concocted as a server-side API definition facility. I heard that JAX-RS 2.0 is under formulation to address JAX-RS being used as a client-side facility too.

However, this series of articles centre on sharing JAX-RS definition between the client and server, using currently available frameworks, allowing the client to use REST as the RPC mechanism. Hence, if you are completely comfortable with GWT-RPC, you would also be completely comfortable with GWT-REST-RPC.

In http://h2g2java.blessedgeek.com/2009/08/gwt-rpc.html, I discussed that GWT-RPC is technically RPC over HTTP. REST is SOA embedded in HTTP transported over HTTP. (Whilst SOAP is SOA transported over http without being embedded with HTTP). Therefore,

GWT+JAX-RS = RPC over REST{SOA over HTTP}.

Frameworks involved
The frameworks involved in making RPC/REST possible are
  • JAX-RS, aka JSR-311, aka Java API for RESTful Web Services
  • JAX-B, aka JSR-222, aka Java Architecture for XML Binding
  • Jackson JSON Object schema
  • RestyGWT

JAX-RS presents two layers of API.
  • The URL schema
  • The Java API layer, which is the enabling feature for RPC over REST.

JAX-RS provides a Java annotation convention that maps the REST URL API to its Java API. There are two implementations of JAX-RS.

What is REST
REST = Representational state transfer. What's that? Never bother, just call it REST. Like SOAP, nice sounding short-form, incongruent long-form.

In a short but not too complete description REST mandates that
  • All communication with a web application should be made through a set of unique URLs.
  • That set of unique URLs is known as the API of the web service offered by the web application as a communication facade.
  • You are allowed to use the HTTP Methods of GET, POST, PUT, DELETE.
  • You are allowed to pass data either as form parameters, URL path parameters, QueryString parameters, as content or as HTTP header values.
JAX-RS is a Java language formalisation of REST.
  • @Path annotation to a class, interface, or method to map a set of URL API to their respective Java API.
    The server implementation is to monitor for requests through those URL paths to call their respective Java API method to process the request.
  • @GET, @POST, @PUT, @DELETE annotations to signify HTTP method through which a particular API should accept request.
  • The arguments to the Java API is mapped to the HTTP parameters using parametric annotations such as @PathParam, @QueryParam, @MatrixParam, @FormParam, as well as through HTTP content which are unannotated arguments.
  • @Path annotation combined with the parametric arguments and HTTP method annotation defines the unique polymorphic signature of the API.

The following are two different unique polymorphic API signatures.
  • @Path ("/services/greet")
    @GET

  • @Path ("/services/greet")
    @POST
because one accepts GET while the other accepts POST.

Again, the following are two different unique polymorphic signatures
  • @Path ("/services/greet/{userName}")
    @GET
    String getGreeting(@PathParam String userName);

  • @Path ("/services/greet/{userName}")
    @GET
    String getGreeting(@QueryParam int count, @PathParam String userName);


Tuesday, November 29, 2011

GWT with JAX-RS (aka RPC/REST) Part 0 (preamble ramble)

This is a preamble ramble about deploying REST with GWT. To skip this GWT/REST advertisement, you should proceed to the next post.

What is the purpose of deploying REST when GWT-RPC suffices? Why REST with GWT?

There is an oft cited motivation for doing REST.
  • so that you could reimplement your client using Fortran, Cobol, PHP, Python, other whatnots.
  • OTH, so that you could reimplement your server using the above stated whatnots.

Honestly, those are insufficient excuses to do REST with GWT. The purpose of having a door on your house is not "so that I could have many locks on the door". Being able to have many locks is not the direct motivation, but is simply an enabler. Therefore, the above reasons combined with the following  reasons complete the motivation why you should deploy REST instead of GWT-RPC or XML-RPC or SOAP.
  • Scalability = Mashup-ability - multi-providers, multi war, application mash-up scenarios.
  • Scalability - loose coupling between client and server.
  • Visibility = Debugability - knowing exactly the data formats and schemata that are passed between client and server.
  • Standards = Visibility - I have no idea how to decode the transported data in GWT-RPC; however, JAX-RS allows you to employ established standards of JSON and XML object schemata - namely, Jackson JSON and JAX-B XML have become popular modes of object schemata.
  • Flexibility and Simplicity = Plugin-ability - loose coupling and visibility promote ease of development, enhancement and maintenance.
  • Flexibility and Simplicity does ensure that your application can be reimplemented in a more capable future language that would one day replace Java's popularity as a business enterprise language - just as Java had replaced Cobol. It's good to plan in advance for future contingencies - but having many locks is not the motivation for having a door.
  • Diversity and MVP-friendly - you could have a diversity of clients: Desktop heavy clients such as Swing, non-ASP .NET, Qt and light clients such as GWT, Qt. Qt is an interesting technology in that the same C++ code can be recompiled on Linux, Windows, and various mobile devices.
  • Agile - Visibility, Simplicity and Flexibility allows rapid prototyping using scripts, Fiddler2 (or its FireFox equivalent), to be replaced by proper Java code when the DTO and SAPI hierarchies become more complex and entwined.
  • Agile - allow a mishmash of services written mostly in Java but supplemented with script-based service providers.
  • Simplicity, Diversity, Flexibility, Scalability, Mashup-ability = Agile and gradual technology renewal. When it is time to upgrade any part of your service framework, a RESTful implementation would allow you to do it piece-meal. 
  • Bookmarkability. This is the strongest motivation in many projects to use REST. When a bank sends you an email letting you reset your password, it is probably a URL link to a REST service. REST APIs are convenient as bookmarks and actions links. For example, your grandma does not know how to update her profile but she asks you to do it for her. Fortunately that particular web site operates on REST. So you crafted a URL and mailed/skyped it to her, telling her to click on the link after logging in to her account she wishes to update.
  • RPC-ability. I don't think it is a hyperbole to say that many, if not most, RPC and XML-RPC proponents do not realise that REST can function as RPC. In fact, this series of posts focus on using REST as the RPC mechanism.
  • XMLRPC-ability. Using the right framework, REST is XMLRPC+the advantages of REST.
  • Terminologically SOAP - If you have used SOAP (Simple Object Access Protocol), you would agree that SOAP is a total misnomer because SOAP is not simple. Technically, REST is the actual simple object access protocol.

As long as your services or JEE server contexts reside within the same SLD-SOP restriction, REST would allow your GWT application to subscribe to multiple independently deployed server-side services. In fact, most enterprise GWT apps would need to subscribe to multiple independent services. For one, logging-in and user authentication should be a service of its own. Especially when you are using OAuth or OpenID.

You should see that GWT-RPC by itself is ill-equipped as a proper enterprise level enabler. GWT-RPC constrains you to only one service provider - the same service that serves the GWT UI itself has to serve the RPC service. Whereas REST would allow your GWT UI to communicate with another application context (i.e., deployed on a different war).

And then, if your service is on a different SLD origin, you could write a simple http proxy to forward-the-request/return-the-response, which invariably would run on its own war. In ancient terminology, a HTTP tunnel.


Continue next GWT with JAX-RS (aka RPC/REST) Part 1

Friday, November 18, 2011

The future direction of the human race

There is a double-headed pun here. Saying double-headed is a redundancy, but a pun may involve a three-way or n-way ambiguity of reference. So, saying double-headed means it is a two-way pun.

  • First, it reflects the socio-politic and economic race between humans.
  • Second, it means humans as a species.

The race among the human species will define the future of the human race.

The future of the human race is both bright and bleak. We are running out of resources. We are suffering under the effects of global warming exacerbated by human economic activities. Millions of born and unborn babies die from the effects of human triggered global warming. It is sad that those who most profess to protect the lives of unborn children are also the ones who most defend the need to suffer the effects of  increased global warming through increased human economic activity. It is devastating that social-conservatives promote a two-headed conflicted doctrine.

But there is encouraging news. The encouraging news is that the future of the human race is the android human. The future of the human race lies in genetically manipulated agriculture - which is good news to me.

Within the next 100 years
Babies will be given bio-genetic inoculation as soon as they are born, treatments which will continue throughout their lifetime. These would involve nano-bio-robotic structures (let's call it nbrs for the time being to reduce my need for typing) injected into the human body. They will receive these inoculations just as we receive our vaccinations today.

The structures will be programmed to diagnose and treat illnesses, diseases and disorders. When the human matures into an adult, they will have the capacity to decide to receive nbrs to enhance their physiological capacities. Human adults would choose to have regular dialysis for such treatments, just as we would go to the hairdresser.

Initially, the dialysis machines will be huge and located in clinics. But within 20 years of their general availability to the public, those machines would be transformed into netbook-sized devices. Such dialysis would not involve puncturing of tissues or blood vessels. The mode of permeation would be through minimal dermal-abrasion transfer - where nbrs would migrate through the skin. Nbrs will be programmed or configured to perform specialised functions. They may be programmed to embed themselves into the cellular structure of the body or programmed for gradual termination and destruction.

Nbrs is the ultimate answer to the cure for cancer. And for devastating conditions like AIDs and HIV infection. Nbrs will be deployed to facilitate tissue and organ rejuvenation and repair, or even replacement.

One issue that would escape biological technologists for the next 500 years will be taming the cellular reproduction counter. There is a counting mechanism that precludes cells from multiplying perpetually. In our current primitive state of technology, cells that lose that counting mechanism are cancerous. Currently, we have not much of a choice - to live healthily, we must die. Live free and die.


Therefore, between a hundred years from now till the next 400 years, a human person could choose to  gradually transform into a human android. And most people would do that, if given the opportunity. Cellular rejuvenation, cloning and replacing would at the most extend human life by another fifty years. As aging cells get progressively replaced by nbrs, including brain cells, a person would ultimately become an android.

This would percolate multitude of social, legal and ethical issues.

There is no escape from that technology being deployed. Governments may legislate, and private organisations may voluntarily institute moratoria against the technology. However, such moratoria would not hold well, like a dam against huge deluge of rushing water. The dams would crumble within 50 years of their institution.

When would a person become a total android - when a person's mental capacity is no longer supported by human cells. What would society do with these grafted androids? They think like the original person and have the memories of the original person. The android would be much more intelligent than a non-supplemented human and more resilient. In the beginning, such androids would be persona non grata. They would be issued a death certificate and be required to carry that certificate at all times as personal ID. Of course, the death certificate is in the form of a unique token. Not a piece of paper.

But within 200 years later, there will be a movement of android emancipation. Much like our gay emancipation movements today. Social Conservatives of those days will comprise of gays and straights who oppose the rights of androids. But more and more people will grow old, and more and more of us would gradually slide into becoming android. It is an easy decision to make a living will and choose to pass away abruptly, but it will be difficult for a person who is gradually transforming into an android to choose to terminate oneself because the android believes that he/she/it is the original person.

There would not be a chance of war between humans and androids because most humans would ultimately become androids anyway. Predicting a war between humans and androids would be like predicting a war between young people and the members of AARP.

The androids would be more resilient to super-luminal and extended galactic travel. In their socio-political distress they will guild themselves together and their social and economic structure will be far superior to that of humans, because their motivation would no longer be capitalistic but humanistic - the motivation not for the useless and non-utilitarian accumulation of wealth but the motivations towards rights of survival and achieving the technological ability to achieve that survival on another planet. Or under the surface of the oceans. The androids would also feel the obligation to leave this planet so that their descendants would have the resources to live on it.

Ultimately, android and human culture would merge again, as the technology of human-life extension progresses and as technology-induced biological evolution would draw a very blur line between being human and being android.

There should not be a case for dramatic worries. The sci-fi dramatization of humans self-evolving ourselves till we lose our ability to reproduce will never occur. Reproductive capabilities would be enhanced and there would sooner be a genderless society or a multi-gender society - and then a continuum of genders. Like the rainbow. The rainbow does not have seven colours - it has a continuum of colours.

These potential developments in the history of the human species probably sound frightening to most people of the present age. Many of us today would want to believe a messiah would come and whisk us away from living in such an age. But we are our own messiahs, and we are the chosen race - the human race.

It is in our responsibility to play-god. The Torah that I read mandates us to play-god. And not playing-god would be shirking our responsibility.

The words natural and organic have been having too much abuse. What is natural? The only meaning for organic I know is Organic Chemistry, which often involves chemical compounds that organicists consider as non-organic. Yeah, organic chemicals are mostly non-organic.

The resistance to genetically manipulated agriculture is ridiculous. My only reason to oppose GM agriculture is that corporations like Monsanto are bullying farmers and turning our society back into feudalism. The basic currency of the world, after all, is food. To control the world, it is not the stock market, not the financial streams and repositories, not the politics, but the ability to dictate how and what and when food is cultivated. And that is what Monsanto, et al, is capable of achieving. Our opposition to GM agriculture is playing into the hands of such corporations.

Embrace agro-GM to help ourselves to form large consumer and democratic pressure to prevent agro-GM from having the freehand they now have in enforcing unreasonable contracts on farmers. Under our current political climate, they are even able to enforce an involuntary contract on a farmer if they accidentally spill GM seeds onto the farmer's property.

Realistically, there is no other avenue to reduce global warming and yet have sufficient food and water for the world's burgeoning population, except in our embracing agro-GM to chart its development in a disciplined manner. Even if a complete convergence towards non-combustible power sources is successful. Especially with the emergence of an android class of persons.

We have the responsibility not only to conserve life but to create it. And to preserve what human life that would come into existence.


Resistance is futile - you will be assimilated.

drone
n. A male bee, especially a honeybee, that is characteristically stingless, performs no work, and produces no honey. Its only function is to mate with the queen bee.


A juggernaut in colloquial English usage is a literal or metaphorical force regarded as mercilessly destructive and unstoppable. The word is derived from the Sanskrit Jagannātha

Sunday, September 4, 2011

When to use "have had"

I have occasionally encountered people who use the phrase "have had" improperly.

I do not say that they use it "wrongly" but "improperly" because I always remember my days as a kid, of one of my English teachers' admonition - "there is no such thing as wrong English".

I know that some people of purer linguistic species also prefer that there should be no such thing as "no such thing". Anyway, the admonition was there is improper usage, inappropriate usage of English but never "wrong English". The only possibility of having "wrong English" is getting married to the "wrong English" man/woman. Or, "wrong Russian/French/Chinese/etc". The usage of English, no matter how bad or unacceptable, is always "correct" as long as the grammar used is consistent so that a set of gramatical pattern could be formed.

Therefore, statements such as "thar ain't nobody who loves me", regardless its double negatives, are "correct" English according to the grammatical patterns of those who speak it.

On the other hand, many of us, myself included, prefer to use patterns of communication in English that are acceptable to either the Queen of England or the President of the United States (except for the years between and including 2001 and 2008).

I have occasionally come across people who use the possessive-past participle "have had" or "had had" in patterns such as

"I have had played football."
"I have had eaten my lunch."
"I had had been to Tokyo."

I have a vindictive feeling against such masterbaiters of the English language that they have fallen into the trap of attempting to impress their listeners with their "ability" to use the phrase "have had".

Alright, OK, super-mega-tov - if you wish to impress people with your "ability" to use the phrase "have had", at least do it properly and acceptably.

Let us look at the case of "eat lunch".


Simple Continuous
Present I eat lunch I am eating
lunch
Future I will eat lunch I will be
eating lunch
Past I ate your lunch I was eating your lunch

Present
perfect
I have eaten
lunch
I have been
eating lunch
Past
perfect
I had taken
lunch
I had been
taking lunch

And the past perfectly imperfect is - I have had eaten lunch.
Which is "unacceptable/abnormal". Let me tell you why.

The word "had" is the past tense of "have". "Have" is often used in place of words like "eat". Have is a possessive. I have a friendship with the President. I have a friend.

"I am having lunch" is the same as saying, "I am eating lunch".

Tensewise, saying "I have had lunch" is the same as "I have eaten lunch".

Therefore, saying "I have had eaten lunch" is equivalent to saying "I have had had lunch."

With this in mind, you can safely use the phrase "have had", when "had" is meant to replace a verb such as "eaten", "taken", "seduced", etc.

"Have" in place of these words has a special effect. For example, a seductress in the office boasting her exploits would say,

Statement Implication
I have the boss the boss is mine
I am having the boss at this hour, the boss is mine but tomorrow you may have him
I have had the boss I managed to conquer all odds in demolishing the boss and that had been a great experience, but now you can have what remains of him
I had had the boss once upon a time, before having the current one, I had managed to have the boss - I am no longer interested in exploiting him now.

Should you say, "I have had a friend"?

Normally, you would say "I had a friend". However, when you say, "I have had a friend", it bears negative implications of what you might have done to your "friend".

I have had a baby = I have experienced pregnancy.
I have been had = I have been taken advantage of.
I had had lunch = I had taken my lunch.


Let me tell you what is worse than hearing "have had eaten" - hearing someone say the malapropism "had have". And, worse than the worse is, of course, hearing "I had have eaten lunch".

I had have lunch = I had eat lunch.

Holy cow!

Friday, September 2, 2011

PointConfigurator in GWT HighCharts


This is a special post written specifically as an illustration to an enhancement request for GWT HighCharts project in sourceforge, because unfortunately, I have not found any way that sourceforge discussion editor could allow me to insert pictures. However, it might also be informative to anyone interested in deploying client-side/javascripted charts within GWT.

I need to be able to configure Points while the Points are being created/loaded into a Series object. I would set out to extend the Series class and over-ride the addPoint method. Unfortunately, the lone constructor of Series class is protected by package-private (aka default) access restriction.

I have no-eye-deer over why we should not use protected constructor rather than package-private, except in the case of putting up an ineffective barrier against any extension to the class. Which is pointless because I simply spoof the package namespace. Alternative explanation could be, to catch the exception that if someone had caught a good-eye-deer, to encourage that good-eye-deer be placed into the pot of roast for everyone else to enjoy. Alright then, here is the good-eye-deer that the general public should enjoy.
package org.moxieapps.gwt.highcharts.client;
import org.moxieapps.gwt.highcharts.client.Point;
import org.moxieapps.gwt.highcharts.client.Series;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONValue;

public class QSeries extends Series {
  public QSeries(BaseChart <Chart> chart, PointConfigurator cfgr){
    super(chart);
    this.cfgr = cfgr;
  }

  private PointConfigurator cfgr;

  @Override
  public Series addPoint(Point point, boolean redraw, boolean shift,
      Animation animation) {
    cfgr.configure(point);
    super.addPoint(point, redraw, shift, animation);
    return this;
  }

  public interface PointConfigurator {
    public void configure(Point p);
  }
}
The main eye-deer behind the class extension is the PointConfigurator interface and code inserted into the addPoint method to run the configure method just before the Point is added into the Series object. So that, I could define a PointConfigurator implementation - for example, the following implemetation that would colourise any Point or modify the Marker of any Point that falls into an "interesting" range.
  public class RangeConfigurator
  implements PointConfigurator{

    @Override
    public void configure(Point p) {
      double region =
        // inequality of area within a circle/ellipse:
        Math.pow(p.getX().intValue() -50,2) +
        Math.pow( (p.getY().intValue()-100000)/2000, 2);

      if (region< 100)
        p.setMarker(m1);
      
      else if (region< 300)
          p.setMarker(m2);
    }
    
    final static private Marker m1 = new Marker();
    final static private Marker m2 = new Marker();
    final static private Color red = new Color(222, 63, 63);
    final static private Color green = new Color(63, 222, 63);
    {
      m1.setFillColor(red);
      m2.setFillColor(green);
    }
  }

As a side dish,
  final static private Number[][] mkRandomArray(int count){
    Number[][] ranarray = new Number[count][];
    for(int i=0; i < count; i++ ){
      ranarray[i] = new Number[]{(int)(Random.nextDouble()*100), Math.abs(Random.nextInt()/10000)};
    }
    return ranarray;
  }
The following resulting plot illustrates what HighCharts GWT does not currently do, but why I made the modification to make it do.

Wednesday, June 15, 2011

GWT RequestBuilder vs RPC vs Script-Include

Which should we use: GWT RPC or RequestBuilder?

GWT presents four ways to perform async data transfer with the server.

  • GWT RPC
  • RequestBuilder
  • javascript include
  • the new-fangled ORM-friendly RequestFactory

GWT RPC is built on XMLHttpRequest (look up wikipedia on that) and therefore suffers the restriction of SLD SOP (Second level domain Same origin policy). I wrote a description of this at http://h2g2java.blessedgeek.com/2009/08/gwt-rpc.html. No doubt, newer browsers including IE 8 have a non-w3c-sanctioned XDomainRequest but I doubt GWT RPC has acquiesced to that new development.

RequestBuilder
RequestBuilder is also built on XMLHttpRequest. The difference between the two is that GWT RPC is an elaborate framework to define the client-server communication channel utilizing interfaces to provide Serializable POJO (plain old Java objects) transfer of data. Whereas RequestBuilder is simpler and more palatable to the usual adhoc-quick-and-dirty programmer. RequestBuilder requires you to concoct your own object data structure marshalling/demarshalling because you have to pass your data as String. But then you could encode the data structures using GWT's JSON marshalling/demarshalling routines. You can find my routine in Google Code to perform JSON data-transfer at http://code.google.com/p/synthfuljava/source/browse/trunk/gwt/http/org/synthful/gwt/http/client/JsonHttpResponseHandler.java

Is it true that GWT RPC actually calls RequestBuilder? I need to pace through the debugger to confirm that. I think I have already done that sometime before that confirms that GWT RPC actually calls RequestBuilder. GWT RPC uses its own esoteric encoding, and the format of POJO serialization is deliberately obfuscated.

JSON & JSONP
To transfer data using Javascript script include would require the data to be Javascript objects, obviously. And they Javascript objects would be stringified into text representation. Text representation of Javascript objects is JSON. You could send data to the server using JSON or whichever format that has been agreed upon between your GWT client and the server. However, the server needs to return data to your GWT client in JSONP.

JSONP is actually a Javascript function encapsulating the Javascript objects as its arguments. When the server sends your GWT cllient data using JSONP, it is actually attempting to execute a Javascript function. Therefore, that function would need to be predefined before receiving the JSONP data.
There are two ways that could happen:

  • The server sends a JSONP defining the function.
  • The client defines the function before sending the request.

Concurring the JSONP callback function with the server.
A general and his adjutant awaits to attack, each of their divisions on a different hill 10 miles apart. Their cloud of enemy is at the valley below them. The adjutant and the general agrees beforehand a set of orders correlated to a set of keywords. One of the orders could be like - attackFromLeft(orderDetails).

Similarly, the client would have predefined the Javascript callback function displayBarChart, and the data structure barChartDetails:

function displayBarChart(barChartDetails) { ... ...}

before sending a request to the server that would trigger receiving the data from the server:

displayBarChart({
  categories:[
    rambutans:{price:30, unit:kg},
    durians:{price:50, unit:pounds}
  ]
});

Script include to the rescue
Since, GWT-RPC uses its own esoteric encoding rather than JSONP, I can hardly see the possibility of its performing cross-domain GWT client-server communication.


To circumvent the SLD SOP restriction, whether in Javascript or any means of AJAX, you have to use the Javascript script include technique. i.e., < SCRIPT SRC='...' > tag. You could read my code on how to do that in the class JsonRemoteScriptCall at http://code.google.com/p/synthfuljava/source/browse/trunk/gwt/jsElements/org/synthful/gwt/javascript/client/JsonRemoteScriptCall.java.

This piece of code works on the browser DOM by dynamically defining a SCRIPT element in the DOM.

Script include is hazardous
Be duly warned that script include

<SCRIPT SRC=some-url ...></SCRIPT>

is hazardous in terms of security. Script include, like image include, allows your client to get resources from any server in the cloud that is willing to serve data to your client. And there will be no shortage of servers maliciously defining a Javascript function in the script.


Friday, May 6, 2011

The EVƎNT

There is a TV series which I follow enthusiastically. It seems to have received poor reviews from current day media critics who would (if they were honest) no longer enjoy Alfred Hitchcock's, old episodes of Twilight Zone or The Outer Limits.

Every episode is phenomenal. The Event is a classic.

If you enjoy multitasking, capable of parallel programming, capable of thinking in multiple threads of thoughts simultaneously, and have mental capacity with high functioning orders and degrees of freedom, this TV series is for you.

It is not for people who enjoy watching a show and then walking away forgetting about it, just for an hour's tryst with their TV (or their hulu screen). This show makes you think and reflect every character's motives.

Every character is well-played. Realistic and not over dramatic. Not overacted or underacted like in Days of our Lives. The story line is sufficiently complex and well developed, unless you do not have the mental capacity to perceive it that way. The twists and turns are alluring. The show makes you love characters that you had earlier hated and then hate characters that you had earlier loved. It provides you with characters about whom you have a sense of ambivalence.

Not an ordinary show of clear distinct colours - with clear distinct lines drawn between good and evil, the good guy and the bad guy. This is among the shows that critiques hate because it does not provide avenues where sidekicks and characters are directed to overact just to draw those distinct lines. This type of story lines relegates the responsibility of drawing those lines to you, the audience.

OTOH, this show is antithetical to Battle Star Galactica. BSG - if you want that swishing sound of space fights - the momentary adrenaline rush of an over-exploited storyline.

Monday, February 28, 2011

UiBinder Check List

Gloassary:
  • UI template: The ui.xml file used for declaring the client visuals.
  • UI template bean: The java source that is associated with a ui.xml file.
  • UI-set: The two files that constitute the template-bean pair.
    Example of a UI-set: abc.ui.xml <=> abc.java.
  • External bean: A java class other than the template bean being referenced within the template.

Avoid having more than one entry point in a module.
The client visuals of all entry points within a module will be overlaid together.


A module should not inherit an entry point.
The client visuals of an inherited entry point will be overlaid onto the current entry point's.

@UiFactory directive
is for declaring a factory method which would be used to generate the xml declaration of a widget in the ui template. This is useful in customising gwt widgets if all instances of a widget in a UI-set.

The name of the factory method is inconsequential and therefore there should be only one UiFactory method for each type.

For example, in the following, methodNameRegardless() wlll be used to generate all instances of DialogBox declared in the ui template.

abc.java Bean:
@UiFactory DialogBox methodNameRegardless(){
  ....
}

abc.ui.xml template:
</g:dialogbox ... >


ui:with for referencing an external bean
The ui:with declaration is used for directly instantiating and accessing a java class to be used as a bean.

com.syntercourse.maine.client.MaineMenu.ui.xml:
<ui:with type="com.syntercourse.menu.Commands" field="cmds"/>

So that henceforth, any visible method in com.syntercourse.menu.Commands class would be addressable. For example,

<g:MenuItem text="login"
command="{cmds.getLoginCmd}"/>

com.syntercourse.menu.Commands.java:
Command getLoginCmd(){
  return new  Command() {

    public void execute() {
      userService.createLoginURL(loggedInUrl, googinRPCCallback);
    }
}


ui:with for referencing the ui template bean
ui:with will instantiate the bean declared in the type attribute. When referencing the ui template bean, the ui template should not be reinstantiated (in most cases, reinstantiating its own bean would end up in an endless loop). In order to prevent a ui:with from instantiating a bean (the template bean or external bean), the template bean should declare a @UiField(provided=true) for that ui:with declaration.

com.syntercourse.maine.client.MaineMenu.ui.xml:
<ui:with type="com.syntercourse.maine.client.MaineMenu" field="bean"/>

So that henceforth, any visible method in the template bean would be addressable. For example,

<g:MenuItem text="login"
command="{bean.getLoginCmd}"/>

com.syntercourse.maine.client.MaineMenu.java:
public class MaineMenu
extends Composite{
  private final UserServiceWrapperAsync userService =
    GWT.create(UserServiceWrapper.class);

  private static final Binder binder =
    GWT.create(Binder.class);
  interface Binder extends UiBinder {}
  public MaineMenu() {
    this.bean = this; /*Important, otherwise nullpointerexception*/
    initWidget(binder.createAndBindUi(this));
  }

  @UiField(provided=true) MaineMenu bean;

  Command getLoginCmd(){
    return new Command() {
      public void execute() {
        userService.createLoginURL(loggedInUrl, loginRPCCallback);
      }
    }
  }
}


UiFactory for referencing members in the ui template bean
The @UiFactory combination can also be used to access the members of a template bean.

com.syntercourse.maine.client.MaineMenu.ui.xml:
<g:MenuItem text="login" command="{bean}"/>

com.syntercourse.maine.client.MaineMenu.java:
public class MaineMenu
extends Composite{
  private final UserServiceWrapperAsync userService =
    GWT.create(UserServiceWrapper.class);

  private static final Binder binder =
    GWT.create(Binder.class);
  interface Binder extends UiBinder {}
  public MaineMenu() {
    initWidget(binder.createAndBindUi(this));
  }
  @UiFactory Login bean(){
    return this;
  }
  class Login implements Command(){
    public void execute() {
      userService.createLoginURL(
        loggedInUrl, loginRPCCallback);
    }  
  }
}


UiFactory for referencing members in external bean
The @UiFactory combination can also be used to access the members of a template bean.

com.syntercourse.maine.client.MaineMenu.ui.xml:
<g:MenuItem text="login" command="{cmdfactory.loginCmd}"/>

com.syntercourse.maine.client.MaineMenu.java:
public class MaineMenu
extends Composite{
  private final UserServiceWrapperAsync userService =
    GWT.create(UserServiceWrapper.class);

  private static final Binder binder =
    GWT.create(Binder.class);
  interface Binder extends UiBinder {}
  public MaineMenu() {
    initWidget(binder.createAndBindUi(this));
  }
  @UiFactory CommandFactory cmdfactory(){
    return new CommandFactory();
  }
  class Login implements Command(){
    public void execute() {
      userService.createLoginURL(
        loggedInUrl, loginRPCCallback);
    }  
  }
}


com.syntercourse.maine.client.CommandFactory.java:
public class CommandFactory{
Command loginCmd = new Command(){
    public void execute() {
      userService.createLoginURL(
        loggedInUrl, loginRPCCallback);
    }  
  }
}

Monday, January 3, 2011

Building a house

Hey, it's been a long time since I posted -- reason being, we are building a house by ourselves.

We even excavated the hole and trenches ourselves.