• Home
  • About
  • GWT Dependency Injection recipes using GIN (II)

    June 14th, 2011

    This is the second part of a series about Dependency Injection in Google Web Toolkit using GIN. If you have not yet read the first part, there we explained how to integrate GIN in an existing GWT sample application. In this second part, we will continue enhancing the sample application while explaining other types of injection supported by GIN.

    Encapsulating the event bus

    In the first part of this series, we configured the GWT event bus used in the original application to be injected in some of the application elements. Using an event bus is a “best practice” that helps communicating the different components in the application while keeping a low coupling between them. The point here was to show how to declare and configure a first dependency using the “injector” and the “module”. Because the class “SimpleEventBus” is provided by GWT, it was not possible to annotate the code of the class with “@Singleton” to set the “injection scope”. Instead, we use the Java DSL provided by GIN.
    In order to see how to do the same with annotations, let’s use now an application class (instead of a framework class) where we can use the annotations.
    As you probably noticed, we are using the event bus to emulate the “ping-pong” strokes. Instead of such a technical artifact, let’s create a “racket”:

    
    @Singleton
    public class Racket {
        private final EventBus fEventBus;
    
        private GwtEvent<?> fLastEvent;
    
        @Inject
        public Racket(EventBus eventBus) {
            fEventBus = eventBus;
        }
    
        public void serve() {
            fLastEvent = null;
            hit();
        }
    
        public void hit() {
            fEventBus.fireEvent(getNextEvent());
        }
    
        private GwtEvent<?> getNextEvent() {
            if (fLastEvent == null || fLastEvent instanceof PongEvent) {
                fLastEvent = new PingEvent();
            } else {
                fLastEvent = new PongEvent();
            }
            return fLastEvent;
        }
    
        public void onStroke(Class<?> pingPongEvent, final Command command) {
            if (pingPongEvent == PingEvent.class) {
                fEventBus.addHandler(PingEvent.TYPE, new PingEventHandler() {
                    public void onEvent(PingEvent event) {
                        command.execute();
                    }
                });
            } else {
                fEventBus.addHandler(PongEvent.TYPE, new PongEventHandler() {
                    public void onEvent(PongEvent event) {
                        command.execute();
                    }
                });
            }
        }
    }
    

    As you can see at the code, our class is annotated with “@Singleton” to indicate the injection scope and “@Inject” to get the event bus injected in the constructor. The class is a more adequate wrapper for the event handling and offers three methods: “serve”, “hit()” and “onStroke()”.
    To configure the injection please adjust the “injector” class like this:
    
    @GinModules(InjectorModule.class)
    public interface Injector extends Ginjector {
        public static final Injector INSTANCE = GWT.create(Injector.class);
    
        public Racket getRacket();
    
        public PingView getPingView();
    
        public PongView getPongView();
    }
    

    This time, we only need to declare the dependency in the “Injector” interface (the method will be invoked from the “Simulator” class) but no additional configuration is required and therefore no changes should be made in the “InjectorModule” class.
    Because now the event bus will not be directly accessed from the “Simulator” class, we have removed it from the “Injector” interface. But, let’s see the rest of the code changes:
    
    public class PingView extends Label {
        @Inject
        public PingView(final Racket racket) {
            racket.onStroke(PongEvent.class, new Command() {
                public void execute() {
                    setText("Pong");
    
                    new Timer() {
                        public void run() {
                            setText("");
                            racket.hit();
                        }
                    }.schedule(1000);
                }
            });
        }
    }
    

    The “PongView” class is almost identical and will not be shown here.
    
    public class Simulator implements EntryPoint {
        public void onModuleLoad() {
            final Injector injector = Injector.INSTANCE;
            RootPanel.get("pingSlot").add(injector.getPingView());
            RootPanel.get("pongSlot").add(injector.getPongView());
    
            final Button button = new Button("Serve!");
            button.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    button.setVisible(false);
                    injector.getRacket().serve();
                }
            });
            RootPanel.get("buttonSlot").add(button);
        }
    }
    

    Recapitulating what we have seen so far:

    • GIN allows to define “injectors” by mean of interfaces (“Injector” interface) that can be configured using one or more “modules” each (“InjectorModule” class).
    • If we need to configure an injection aspect we can use annotations in the class code or the Java DSL in the module.
    • In at least one point of the application we will need to access the “injector” to retrieve a top-level injected object (ex: “Racket”, “PingView”, “PongView” ). For these objects to be accessible through the injector, we need to declare them in the “injector” interface.
    • Any other dependency that is declared to be injected (annotated with @Inject) will be resolved by GIN using the algorithm described in the first part of this series and does not need to be declared in the “injector” interface (ex: “EventBus”).

    If you are familiar with GUICE, you probably already know other ways of configuring dependencies and injection. Let’s see in the next point how to avoid the repetition in the views by using “assisted injection”.

    Using assisted injection to avoid code repetition

    One of the main applications of dependency injection is to avoid coding factory classes and singletons and also centralizing the application’s configuration values. This is a very powerful tool to configure application-wide objects like services, which typically are either “singletons” or “prototypes” and scarce.

    When working with data, persistency tools like JPA assist us with the task of generating Java objects for our numerous domain model entities. These objects have normally no behavior or just a little which is typically coded in the “entity” classes. But, what happens if we want to inject our services in some of these entities to have a richer domain model? Normally, we have to tackle this task ourselves and inject the services by hand. This happens because such objects do not by default participate in the injection context (unless we are using JEE or weaving).

    While this not a difficult task, it is a purely programmatic one and breaks one of the principles of dependency injection: declarative dependencies definition.
    In GUICE (and therefore in GIN) there is a concept called “assisted injection” that helps us to create objects which require dependencies from the injection context but also instance specific property values. Basically, it consists of using a factory interface with methods to instantiate the objects as managed beans (injected objects) receiving each method only the object’s specific properties as parameters. The object constructors receive of course not only the object properties but also the dependencies who should be retrieved from the dependency injection context.

    Because an image is worth a thousand words, let’s see this with an example. What we would like to achieve here is to have only one view class (“PingPongView”) instead of two specific ones that have almost the same code. If we inspect both view classes, the differences are: to which event each reacts and which text each shows. If we refactor these values as constructor parameters, we have the following resulting class:

    
    public class PingPongView extends Label {
        @Inject
        public PingPongView(final Racket racket, @Assisted final String text, @Assisted Class<? extends GwtEvent> eventClass) {
            racket.onStroke(eventClass, new Command() {
                public void execute() {
                    setText(text);
    
                    new Timer() {
                        public void run() {
                            setText("");
                            racket.hit();
                        }
                    }.schedule(1000);
                }
            });
        }
    }
    

    Probably you already noticed the @Assisted annotation in the new extracted parameters. It just indicates GIN that the non-annotated parameters should be resolved as dependencies and that the annotated ones should be provided though parameters in a factory method of the assisted injection factory:
    
    public interface AssistedInjectionFactory {
        public PingPongView createPingPongView(String text, Class<? extends GwtEvent> eventClass);
    }
    

    To install this factory in our dependency injection context we need to modify our GIN module class like this:
    
    public class InjectorModule extends AbstractGinModule {
        @Override
        protected void configure() {
            bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
    
            install(new GinFactoryModuleBuilder().build(AssistedInjectionFactory.class));
        }
    }
    

    And in the injector class, we have to expose the factory as any other dependency:
    
    @GinModules(InjectorModule.class)
    public interface Injector extends Ginjector {
        public static final Injector INSTANCE = GWT.create(Injector.class);
    
        public Racket getRacket();
        public AssistedInjectionFactory getFactory();
    }
    

    And last but not least, let’s use the assisted injection in our application:
    
    ...
        public void onModuleLoad() {
            final Injector injector = Injector.INSTANCE;
            final AssistedInjectionFactory factory = injector.getFactory();
            RootPanel.get("pingSlot").add(factory.createPingPongView("Ping", PingEvent.class));
            RootPanel.get("pongSlot").add(factory.createPingPongView("Pong", PongEvent.class));
    ...
    

    In this article, we have applied new dependency injection recipes to our GWT demo application. I hope that they can help you give a better structure to your GWT applications and also learn dependency injection features and its “best practices”.

    The source code of the application can be downloaded here. To see the application working, unzip the file, change to the folder where the Maven pom file is stored and type the command: “mvn clean gwt:run”. After the GWT “Development mode” application starts, click on the “Launch Default Browser” button.

    The other parts of this series can be found here and here.

    I hope that you enjoyed reading this article as much as I did writing it.
    See you soon!


    GWT Dependency Injection recipes using GIN

    April 5th, 2011

    Dependency Injection is already a well-known and discussed topic in the Java world and there are a good number of well established frameworks and libraries supporting this concept. While for many developers it is a must, some others seem not to be so convinced and think that it does not bring that much value to a project. Of course, it depends on the project, but with the time, it seems that its benefits have been widely accepted and support for it has been incorporated in almost every piece of software where it seemed to make sense.

    This is also the case of Google Web Toolkit where GIN provides dependency injection support on the client side.
    GIN is a mainly a GWT-based version of the Google’s homegrown dependency injection framework GUICE. But because the GWT applications run on top of the browser JavaScript engine instead of on the JVM, some of the GUICE features are not available in GIN. On the other hand, GWT provides some poweful features for code generation that have enabled a meaningful subset of the GUICE features to be implemented in GWT.

    Instead of writing an introduction tutorial to the GIN capabilities, the purpose of this article series is to illustrate some of the GIN features while applying some recipes to an existing application.

    Maybe you already know this little screencast where Hamlet D’Arcy explains how to decouple GWT components by mean of an “event bus” in a little “ping-pong” simulation. If not, maybe you would like to spend five minutes watching the screencast and, once you are done, read on and learn how to apply some dependency injection techniques to improve this little application.

    The source code of the application can be downloaded here. To see the application working, unzip the file, change to the folder where the Maven pom file is stored and type the command: “mvn clean gwt:run”. After the GWT “Development mode” application starts, click on the “Launch Default Browser” button.

    Adding GIN to the application

    In order to start using GIN in the sample application, the first task that we should accomplish is adding the GIN dependencies to the project. Because the build of the application is Maven-based, we need simply to add the following dependency to the Maven pom file:

    
    <dependency>
        <groupId>com.google.gwt.inject</groupId>
        <artifactId>gin</artifactId>
        <version>1.5.0</version>
        <scope>compile</scope>
    </dependency>
    

    Note: If you experience issues while using GIN 1.5 with GWT versions previous to 2.2, consider using GIN 1.0. With GWT version 2.2 and superior ones use GIN 1.5 instead.

    Ok, and what now? First, let’s have a look at the “main” class of our GWT application, the “Simulator” class:

    
    public class Simulator implements EntryPoint {
        public void onModuleLoad() {
            final EventBus bus = new SimpleEventBus();
            RootPanel.get("pingSlot").add(new PingView(bus));
            RootPanel.get("pongSlot").add(new PongView(bus));
    
            final Button button = new Button("Serve!");
            button.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    button.setVisible(false);
                    bus.fireEvent(new PingEvent());
                }
            });
            RootPanel.get("buttonSlot").add(button);
        }
    }
    

    The first “dependency” that we can identify here is the “event bus”. Because an event bus is heavily used in a GWT application to enable component communication with low coupling, it would be an improvement to avoid instantiating the event bus explicitly and having to expose the unique instance used in some class (“singleton”). To achieve this, we need to create two new elements: the GIN injector and at least one GIN module.
    The GIN injector is an interface that will be instantiated by mean of the GWT deferred binding functionality (“GWT.create()” factory method) and that basically declare the “managed beans” of our GWT application. These are the dependencies that can be directly accessed using an instance of the injector or that will be used by the injector to satisfy required dependencies while performing injection:
    
    @GinModules(InjectorModule.class)
    public interface Injector extends Ginjector {
        public static final Injector INSTANCE = GWT.create(Injector.class);
    
        public EventBus getEventBus();
    }
    

    The “InjectorModule” class referred in the “@GinModules” annotation is the so called “GIN Module”. In this class, we will configure how the instances of the managed beans should be created:
    
    public class InjectorModule extends AbstractGinModule {
        @Override
        protected void configure() {
            bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
        }
    }
    

    Having a look at both files, it is not difficult to understand what we are doing. In the injector and by mean of the “getEventBus” method, we have declared an injectable dependency of the interface type “EventBus”. In the module and by mean of the GIN Java DSL, we have provided an implementation for the dependency and also specified that, no matter how many times we call the “getEventBus” method in the injector, always the same unique instance should be returned. This is also part of the dependency injection configuration process and is sometimes referred as “scope binding”.
    Please, take care of not using different injector instances within the application because, in that case, you would get different event bus instances (one per injector instance).

    Let’s see now how to use the injector in the “Simulator” class to perform the injection:

    
    public void onModuleLoad() {
        final Injector injector = Injector.INSTANCE;   
        RootPanel.get("pingSlot").add(new PingView(injector.getEventBus()));
        RootPanel.get("pongSlot").add(new PongView(injector.getEventBus()));
    
        final Button button = new Button("Serve!");
        button.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                button.setVisible(false);
                injector.getEventBus().fireEvent(new PingEvent());
            }
        });
        RootPanel.get("buttonSlot").add(button);
    }
    

    If you compare this new version of the “Simulator” class with the previous one, there is not yet a major improvement in the code structure and not even a reduction in the number of code lines. The main improvement so far, is that the instantiation of the event bus is configured in a central point and that the implementation selected is not known outside this configuration class. Anyway, nothing that cannot be done with a simple “factory” class.
    Where comes then the benefit of using dependency injection? OK, let’s know move the instantiation of the “view components” to the injector. For this, adjust the classes in the following way:
    
    @GinModules(InjectorModule.class)
    public interface Injector extends Ginjector {
        public static final Injector INSTANCE = GWT.create(Injector.class);
        public EventBus getEventBus();
        public PingView getPingView();
        public PongView getPongView();
    }
    

    Then, in the “Simulator” class, use the injector to also create the views like this:
    
    public class Simulator implements EntryPoint {
        public void onModuleLoad() {
            final Injector injector = Injector.INSTANCE;
            RootPanel.get("pingSlot").add(injector.getPingView());
            RootPanel.get("pongSlot").add(injector.getPongView());
    
            final Button button = new Button("Serve!");
            button.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    button.setVisible(false);
                    injector.getEventBus().fireEvent(new PingEvent());
                }
            });
            RootPanel.get("buttonSlot").add(button);
        }
    }
    

    If the “PingView” and “PongView” classes had a default constructor, it would suffice with the previous two changes for the application to work normally. GIN would be, in that case, smart enough to find the classes and create the instances. But, because that is not the case and both classes expect a communication event bus passed as parameter in the constructor, we need to annotate the constructor with the “@Inject” annotation. Then, GIN will try to resolve the parameters in the constructor using a simple dependency resolution mechanism: if there is a method in the injector interface that returns the class of the parameter, this method will be used to obtain an instance of that class. If there is not such a declared method in the injector, but the parameter class has a default constructor, a new instance will then be instantiated. The little detail here is that the instantiation will be done using GWT deferred binding (“GWT.create()” factory method), giving GWT the possibility of “enhancing” the code, instead of simply using the default constructor of the class.
    This way, if every of the constructor parameters can be resolved as dependencies (fulfill at least one of the previous conditions), GIN can create an instance with its dependencies injected and without requiring additional configuration.

    To make the application work, add the “@Inject” annotation to the constructors of both view components as shown in this example:

    
    ...
        @Inject
        public PongView(final EventBus bus) {
    ...
    

    Note: GUICE, and therefore GIN, support the JSR-330 standard annotations for dependency injection (package: javax.inject.*) which should be a preferred option in comparison to proprietary annotations with the same semantic but defined in non-standard packages (package: com.google.inject.*). This makes possible to re-arrange the dependencies without changing the code (the type will be loaded from the classpath without being relevant in which JAR file or classpath entry it is located).

    With these changes in the sample application, we have learnt:

    • how to configure GIN using an injector interface and a module class.
    • How to define a first dependency: the event bus.
    • How to select an implementation for the dependency: the “SimpleEventBus” class.
    • How to bind this dependency to a context: the application context in this case (also referred sometimes as “singleton scope”).
    • And finally, how to get the dependency injected in a constructor (what is only one of the many ways of doing dependency injection in GIN).

    For this series of articles, we chose intentionally a simple application where to apply some simple dependency injection recipes. If you are not yet convinced of its benefits, don’t abandon yet! We have just started and in the following articles, we will explore some other possibilities and use cases.

    I hope that you enjoyed reading the article and also to see you in the next part.

    The other parts of this series can be found here and here.

    The source code of the dependency-enabled application can be downloaded here. To execute the application, simply follow the same steps described above for the initial version.


    Screencast: GWT Event Bus Basics

    February 25th, 2011

    Wheee! I made a screencast. Happy Friday to you too.

    This screencast is about the GWT Event Bus. It explains how an Event Bus can be used to loosely couple controllers or views in MVC applications, and includes live coding of a GWT using the SimpleEventBus client. The source is all available on GitHub. And as always, up votes are appreciated.

    If it doesn’t play correctly, you may want to launch it from the JetBrains.tv site.

    This screencast explains why MVC applications benefit from an event bus, and it demonstrates how to create, wire, and respond to events in Google Web Toolkit (GWT). Not bad for just six and a half minutes.” Too much fun.


    GWT UiBinder: Better Web App Separation of Concerns

    April 26th, 2010

    One of the newest features introduced in Google Web Toolkit 2.0 is the “UiBinder“. This new way of building views allows the developer to use a declarative approach when doing the layout of a GWT application.

    In case you have not heard about it, GWT is a set of tools that enables Java developers to develop “rich web applications” in the Java language. The term “rich web application” implies two things:

    • Desktop-like interaction, where a user action has immediate feedback (e.g.: input validation, search box terms suggestions, results highlighting, etc) without requiring a server round-trip (executing an HTTP request with the result of reloading the page being browsed). In the world of web applications, this is typically accomplished using Ajax (what is also what GWT does).
    • An application running within a browser, but using native browser technologies (HTML, CSS and JavaScript). If we were talking about applications held in browser plug-ins and running out-of-process within their own virtual machines or by mean of run-times, I would prefer to use the more general term “rich internet applications”. These are launched from a web browser but behave as black boxes for other user agents (e.g.: web crawlers).

    GWT allows us is write Ajax-based “rich web applications” using the Java language instead of the traditional JavaScript. GWT takes your Java code and compiles into JavaScript, HTML, and CSS. So while you write the program in Java, it is translated into a traditional web application.

    Building user interfaces in GWT

    The most common approach to building desktop application interfaces is using visual components called “widgets”. For developers with Swing experience, GWT seems a marvellous step forward because it allows you to leverage most of your knowledge with far less effort than the alternatives. I say seems because this can also be of disadvantage, as I’ll show with an example.
    If we had to create a web interface for a simple web search application, the most common way of doing the interface would be an HTML form for submitting the query and an HTML list to show the results:

    <html>
    <head>
        <title>Search application</title>
    </head>
    <body>
    <div id="searchBox">
        <h2>Search:</h2>
        <form action="">
            <label for="queryInput">Query:</label>
            <input id="queryInput" type="text"/>
            <input type="submit" value="Go!"/>
        </form>
    </div>
    <div id="searchResults">
        <h2>Results:</h2>
        <ul id="results">
            <li>Result 1</li>
            <li>Result 2</li>
            <li>Result 3</li>
        </ul>
    </div>
    </body>
    </html>

    In the case of GWT, a Swing developer might write widget and layout code like this:
    
    public class SearchGwt implements EntryPoint {
        public void onModuleLoad() {
            Widget searchBox = createSearchBox("Query:", "Go!");
            Panel searchResults = createSearchResults();
    
            VerticalPanel mainContainer = new VerticalPanel();
            mainContainer.add(new Label("Search:"));
            mainContainer.add(searchBox);
            mainContainer.add(new Label("Results:"));
            mainContainer.add(searchResults);
    
            RootPanel.get().add(mainContainer);
        }
    
        private Widget createSearchBox(String inputLabel, String buttonLabel) {
            HorizontalPanel searchBox = new HorizontalPanel();
            searchBox.add(new Label(inputLabel));
            searchBox.add(new TextBox());
            searchBox.add(new Button(buttonLabel));
            return searchBox;
        }
    
        private Panel createSearchResults() {
            VerticalPanel searchResults = new VerticalPanel();
            for (int i = 1; i <= 3; i++) {
                searchResults.add(new Label("Result " + i));
            }
            return searchResults;
        }
    }
    

    This approach is a valid one and, with some CSS styling, produces a neat interface, but it introduces a too complicated DOM structure that does not scale well for bigger applications:
    <html>
    <head>
        <title>Search GWT application</title>
    </head>
    <body>
    <!-- GWT script and iframe tags omitted -->
    <div>
        <div class="gwt-Label">Search:</div>
        <table cellspacing="0" cellpadding="0">
            <tbody>
            <tr>
                <td align="left" style="vertical-align: top;">
                    <div class="gwt-Label">Query:</div>
                </td>
                <td align="left" style="vertical-align: top;"><input type="text" tabindex="0" class="gwt-TextBox"/></td>
                <td align="left" style="vertical-align: top;">
                    <button type="button" tabindex="0" class="gwt-Button">Go!</button>
                </td>
            </tr>
            </tbody>
        </table>
        <div class="gwt-Label">Results:</div>
        <div>
            <div class="gwt-Label">Result 1</div>
            <div class="gwt-Label">Result 2</div>
            <div class="gwt-Label">Result 3</div>
        </div>
    </div>
    </body>
    </html>

    Compare the handcrafted HTML tags with the DOM produced using GWT widgets, and the first one is simpler. One of the reasons of the extra verbosity of the GWT one is the use of “HorizontalPanel” to layout the search box horizontally. This is a panel based in tables and it introduces a “too verbose” HTML table for the layout. In the case of a horizontal layout, we can also use a FlowPanel, altogether with some CSS styles, to avoid the search box components stacking vertically (which is the default layout for the HTML “div” elements that a “FlowPanel” produces). The problem is that this approach mixes widgets for layout with CSS for layout (not for styling) what stops being a pure widget approach.
    The next thing to notice in the DOM produced by GWT is the excessive presence of GWT CSS classes (e.g.: “gwt-Label”, “gwt-TextBox”). While they are most times useful when it comes to style the widgets, they are many times not used or they do not fit always our CSS selectors strategy.
    Lastly, there is a lack of HTML semantics in the DOM produced by GWT. Almost every element is a “div”. From the point of view of web standards, it is much more convenient to use an HTML list for the results as it is to use a collection of “div” elements. Producing HTML labels associated with form fields (search box label) is also a usability and accessibility improvement. Using tables for layout should be avoided.
    For a real-world application that use input fields, trees, tables, “tab panels” or splitters, etc… all in the same screen, it is a good practice to get rid of the intermediate superfluous DOM elements. It reduces drastically the amount of “glue” elements, making the DOM much more compact and faster to modify. We should avoid “glue” and automatic generated code, because it needs to be compiled, loaded, executed and maintained. In the case of an overly verbose DOM structure, CSS issues may appear because of the complex structure interactions. Fixing them is akin to fixing bugs in generated code: very difficult!

    Mixing HTML and Widgets

    So how can we mix widgets and html properly? Before GWT version 2.0, the most common way was to use “RootPanel.get(‘someId’)” to access an HTML element in the application host page, and then create an object there to attach the widgets to (ie. a “RootPanel”). If we need to embed only a few widgets in the host page, this technique suffices. But doing this in a real application with a large number of widgets becomes complex and slow.
    UiBinder scales better because it does not inject widgets into the HTML of the host page. Instead, you declare your layout in a stand-alone HTML file that can be composed with other components as many times as necessary to build more complex interfaces. Composition entails componentization, allowing the developer to create subparts of the user interface (UI components) that can be packaged, re-used and tested in isolation.
    But let us see how with an example:

    
    public class SearchGwt implements EntryPoint {
        public void onModuleLoad() {
            SearchComponent searchComponent = new SearchComponent();
            RootPanel.get().add(searchComponent);
        }
    }
    

    <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
                    xmlns:g='urn:import:com.google.gwt.user.client.ui'>
        <g:HTMLPanel>
            <div id="searchBox">
                <h2>Search:</h2>
                <form action="">
                    <label for="queryInput">Query:</label>
                    <input id="queryInput" type="text"/>
                    <input type="submit" value="Go!"/>
                </form>
            </div>
            <div id="searchResults">
                <h2>Results:</h2>
                <ul id="results">
                    <li>Result 1</li>
                    <li>Result 2</li>
                    <li>Result 3</li>
                </ul>
            </div>
        </g:HTMLPanel>
    </ui:UiBinder>

    
    public class SearchComponent extends Composite {
        interface Binder extends UiBinder<Widget, SearchComponent> {
        }
    
        private static Binder uiBinder = GWT.create(Binder.class);
    
        public SearchComponent() {
            initWidget(uiBinder.createAndBindUi(this));
        }
    }
    

    Our example has been split into three files: the first one is the GWT entry point, that now only instantiates and inserts our new UI component at the interface top level. The second is an XML file representing the view and is required by UiBinder to act as a mark-up template. The third is the Java class implementing the component logic (that as of now is almost non-existent) and invoking UiBinder.
    If you run this code so far, you will notice that now the appearance is exactly the same as in the handcrafted HTML and that there is not yet real integration between the view of the component (mark-up template) and the logic of the component (Java class). Let us fix this by substituting the HTML input field with a GWT “TextBox”:
    <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
                    xmlns:g='urn:import:com.google.gwt.user.client.ui'>
        <g:HTMLPanel>
            <div id="searchBox">
                <h2>Search:</h2>
                <form action="">
                    <label for="queryInput">Query:</label>
                    <g:TextBox ui:field="queryInput"/>
                    <input type="submit" value="Go!"/>
                </form>
            </div>
            <div id="searchResults">
                <h2>Results:</h2>
                <ul id="results">
                    <li>Result 1</li>
                   <li>Result 2</li>
                   <li>Result 3</li>
                </ul>
            </div>
        </g:HTMLPanel>
    </ui:UiBinder>

    
    public class SearchComponent extends Composite {
        interface Binder extends UiBinder<Widget, SearchComponent> {
        }
    
        private static Binder uiBinder = GWT.create(Binder.class);
    
        @UiField
        TextBox queryInput;
    
        public SearchComponent() {
            initWidget(uiBinder.createAndBindUi(this));
        }
    }
    

    Notice the changes in the template where the HTML input field has been substituted by “” and also the little change in the Java class that now has a field of type “TextBox” annotated with “UiField”. When the Java class is instantiated, the UiBinder creates and injects the “TextBox” using the matching field name and “ui:field” attribute. The result is almost the same DOM structure with only some extra attribute values generated by GWT. Note that we also eliminated the “id” HTML attribute. This last change is because of a current limitation in UiBinder which does not allow defining both attributes in the same element. This issue can be solved setting the id attribute in the constructor after the UiBinder has been invoked.
    As next step, let us now integrate the results list by writing out some simple HTML list elements:
    <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
                    xmlns:g='urn:import:com.google.gwt.user.client.ui'>
        <g:HTMLPanel>
            <div id="searchBox">
                <h2>Search:</h2>
                <form action="">
                    <label for="queryInput">Query:</label>
                    <g:TextBox ui:field="queryInput"/>
                    <input type="submit" value="Go!"/>
                </form>
            </div>
            <div id="searchResults">
                <h2>Results:</h2>
                <ul ui:field="results"/>
            </div>
        </g:HTMLPanel>
    </ui:UiBinder>

    
    public class SearchComponent extends Composite {
        interface Binder extends UiBinder<Widget, SearchComponent> {
        }
    
        private static Binder uiBinder = GWT.create(Binder.class);
    
        @UiField
        TextBox queryInput;
        @UiField
        UListElement results;
    
        public SearchComponent() {
            initWidget(uiBinder.createAndBindUi(this));
            queryInput.getElement().setId("queryInput");
            for (int i = 1; i <= 3; i++) {
                results.appendChild(createResultsItem("Result " + i));
            }
        }
    
        private Element createResultsItem(String value) {
            LIElement result = Document.get().createLIElement();
            result.setInnerHTML(value);
            return result;
        }
    }
    

    The changes in the UI Binder template is almost the same as the previous one with a subtle difference: in the previous step, we integrated a GWT widget (“TextBox”) replacing the HTML input element. In this second case, we performed a to “bind” the “ul” HTML element from the view because there is no GWT list widget that matches a simple HTML list. Instead of using the API of a GWT widget, we are using the GWT DOM API to directly modify it.

    Adding behaviour

    Let us now go back to the first GWT approach and modify it to create the results when clicking the button. This is what your pre-UiBinder code might look like:

    
    public class SearchGwt implements EntryPoint {
        public void onModuleLoad() {
            Panel searchResults = new FlowPanel();
            Widget searchBox = createSearchBox("Query:", "Go!", searchResults);
    
            FlowPanel mainContainer = new FlowPanel();
            mainContainer.add(new Label("Search:"));
            mainContainer.add(searchBox);
            mainContainer.add(new Label("Results:"));
            mainContainer.add(searchResults);
    
            RootPanel.get().add(mainContainer);
        }
    
        private Widget createSearchBox(String inputLabel, String buttonLabel,
                                       Panel searchResults) {
            HorizontalPanel searchBox = new HorizontalPanel();
            searchBox.add(new Label(inputLabel));
            searchBox.add(new TextBox());
            searchBox.add(new Button(buttonLabel,
                          createClickHandler(searchResults)));
            return searchBox;
        }
    
        private ClickHandler createClickHandler(final Panel searchResults) {
            return new ClickHandler() {
                public void onClick(ClickEvent event) {
                    for (int i = 1; i <= 3; i++) {
                        searchResults.add(new Label("Result " + i));
                    }
                }
            };
        }
    }
    

    Here we introduced a “ClickHandler” that modifies the results container with some fake ones when the search button is clicked.
    Doing the same with the UiBinder approach results on the following code:
    <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
                 xmlns:g='urn:import:com.google.gwt.user.client.ui'>
        <g:HTMLPanel>
            <div id="searchBox">
                <h2>Search:</h2>
                <label for="queryInput">Query:</label>
                <g:TextBox ui:field="queryInput"/>
                <g:Button ui:field="searchButton" text="Go!"/>
            </div>
            <div id="searchResults">
                <h2>Results:</h2>
                <ul ui:field="results"/>
            </div>
        </g:HTMLPanel>
    </ui:UiBinder>

    
    public class SearchComponent extends Composite {
        interface Binder extends UiBinder<Widget, SearchComponent> {
        }
    
        private static Binder uiBinder = GWT.create(Binder.class);
    
        @UiField
        TextBox queryInput;
        @UiField
        Button searchButton;
        @UiField
        UListElement results;
    
        public SearchComponent() {
            initWidget(uiBinder.createAndBindUi(this));
            queryInput.getElement().setId("queryInput");
        }
    
        @UiHandler("searchButton")
        void buttonClick(ClickEvent event) {
            for (int i = 1; i <= 3; i++) {
                results.appendChild(createResultsItem("Result " + i));
            }
        }
    
        private Element createResultsItem(String value) {
            LIElement result = Document.get().createLIElement();
            result.setInnerHTML(value);
            return result;
        }
    }
    

    We introduced a “Button” GWT widget in the mark-up template together with its corresponding field in the Java class. We also moved the code creating the results to its own method annotated with “UiHandler” (take into account that the signature must be compatible with a “ClickHandler”). Finally, we removed the “form” element from the mark-up (which is not required at all in an Ajax application).
    One of the core design principles in the development world is the benefits of separating logic and presentation. What would happen if now we wanted to change the place where the results appear in relation to the search box? Or, if we wanted to get rid of the “Results:” label because it is not necessary? In the first GWT approach taken, the way in which the widgets are created and nested is reflected in the Java code together with our logic, making necessary changes to this code. Also “static” presentational elements, like the “Results:” label, are embedded in the code where. Applying the separation of concerns principle tells us that they do not belong there. Making a change to either presentation or logic necessarily requires changing both presentation and logic. In the “UiBinder” approach, because of its inherent separation of concerns, these changes would happen only in the mark-up template or in the domain logic, not in both.

    Conclusions

    • When building a web application, no matter which framework you use, never forget that you are still using HTML, CSS and JavaScript. The simpler the DOM produced, the faster the application will perform and the less CSS issues you will find.
    • Web applications have web pages! Always try to use the most semantic HTML structure you can. It improves SEO, usability and accessibility and usually produces compact DOM structures.
    • Even when you program in your favourite language and do everything in code by mean of widgets, do not forget the advantages of principles like presentation and logic separation. Using UiBinder in GWT produces twice the number of files but each is simpler, cleaner, easy to manage, and easier to maintain.
    • With presentation separation, you can let your design team produce a HTML prototype of the different parts of your application that can be easily reused afterwards or even in parallel. Two teams being able to work in parallel reduces the project time span and using prototypes reduces the project risks.
    • Because different tasks require different skills, let the developers code and the designers deal with HTML and CSS. They all will be much happier and the application will be and look much better.

    Jazoon ’09: RIA and Security

    June 23rd, 2009

    Session title: RIA Security: Broken by Design
    From: Joonas Lehtinen, CEO IT Mill

    IT Mill is the creator of Vaadin: A 100% Java tool for RIA.

    Joonas outlines a spectrum of complexity from Basic site to 3D games examples:
    Web Sites (Wikipedia), AJAX Sugar (Facebook), Full RIA

    He divides „Full RIA“ divide into client side vs. Server driven. Gives a crash course in GWT.

    Vaadin: Apparently 100% Java and server driven, which sounds an awful lot like ULC at this stage… But here’s a difference: It builds on GWT and relies on JavaScript on the client-side.

    He goes on to present a bunch of development rules:

    Rule #1: Don’t trust the browser
    Rule #2: Complexity is a hiding place for bugs
    Rule #3: Large surface give more opportunities for attack. This surface has increased with Web 2.0.

     

     

    Difference between GWT and Vaadin architectures is that GWT relies on the client invoking a server-side Web Service API, whereas Vaadin renders the client’s view on the server.

    Erm… he then offers the cures for the problems (Rules above)… which I miss because the explanation is compressed into around 5s.

    I’m starting to dislike this presentation at this point. Because here comes another artificial security issue scenario… which guess which product solves. And I thought product placement in Hollywood movies was irritating.

    The issues he raises are legitimate, but the lack of objectivity is obscuring the message. And as I write the presenter is debugging JavaScript which depends on analysing the DOM on the client side – I’m not sure if he’s now analysing the problem or trying to fix it!?

    I am formally declaring myself lost at this stage. At least I hope the other attendees are getting something out of this presentation, which has lost focus IMO.

    He continues with a discussion about attacking at the transport level, inserting new data on the fly. But come on: A secure transaction in this technical setting will operate under HTTPS, which in most instances will deal with this kind of attack. Unless, of course, that’s something else I missed.

    I think I need a coffee!!!