• Home
  • Events
  • About
  • Code generation in GWT with Deferred Binding (CDI-like events)

    July 4th, 2011

    If you read my series on GWT dependency injection (parts: first, second and third), maybe you remember that, in part 3, I mentioned how convenient would be to reduce the boilerplate required to define events in GWT. I also mentioned how elegant I find the event definition in CDI. Wouldn’t it be nice to have a lightweight event model like that in GWT?

    Let’s see first how an event is defined and handled in CDI:

    As you can grasp from the code, to define a new type of event in CDI it is enough to define an injected field of the parametrized class Event and the CDI container will do all the wiring for us. The parametrized type of the event defines its payload type by mean of the type parameter. To listen to the event, we just need to define a method that receives a parameter of the event payload type and annotate it with “@Observes”.

    While exactly this is maybe not doable in GWT (at least not yet), what about something like this?:

    While I can agree with you that it is not as elegant as the events approach in CDI, it is (IMO) a big improvement compared with, for instance, the ping / pong event definition in the demo application of my GIN series (source code here):

    With the new approach, the resulting “PingEvent” would look like this:

    If you are wondering why not to avoid defining the “PingEvent” class itself, two are the reasons:

    • First, the events have the same payload type (Void in this case), and therefore we need explicit types to distinguish the ping event from the pong event. This also happens in CDI where we would define explicit payload types instead.
    • Second, in this implementation we will be using GWT’s deferred binding and, during the code generation phase, we need to know the parametrized type. Because of Java generics limitations, for this last it is necessary to define a new parametrized type which captures the payload type in its type parameter (wrapper).

    Did I convince you? If I did, let’s go on and see how to use deferred binding and dependency injection to achieve it.

    Letting GWT generate the boilerplate

    Deferred binding in GWT is a really powerful feature implemented in the GWT compiler to substitute class implementations depending in environment properties like the user agent. This way, while the developer has the illusion of using the same classes independently of the browser, the deferred binding mechanism allows to select the adequate implementation for each browser.

    Far from being static, deferred binding allows to generate code on the fly by mean of a generator class. This happens when the developer invokes the “GWT.create()” method on an interface. For the operation to succeed, a generator for the interface must exist. This will be invoked during GWT compilation time and its result (one or more Java classes) will be compiled and linked into the resulting JS application.

    To configure which generator should be used for which interface, it is necessary to add a new “generate-with” entry in the GWT module descriptor. In the case of the demo application, the following code has been added to the “PingPong.gwt.xml” file:

    The contents of the “Event” and “EventGenerator” classes are the following:

    While the “Event” class contains the interface definition for our events and lives in the “client” package of our GWT application, the “EventGenerator” is a GWT specific class that resides in the “server” package of our GWT application. In order to compile the code, we will need to add a new dependency to our project: “gwt-dev-<version>.jar”.

    This generator class, by mean of some templates included in the source code, generates the boilerplate classes and saves us the tedious work of writing these classes. If you want to see this in detail, please refer to the “eventsfwk” packages in the client and server part of the application (source code here).

    Using GIN to bring everything together

    Following what I mentioned until now, it seems that if we define an interface extending the “Event” interface (ex: “SampleEvent”) and we use the generator to generate and wire the code by mean of “GWT.create(SampleEvent.class)”, we should be able to use the result as shown in the “GWTSample” execute method. Not really.

    One piece that is missing in the puzzle is which event bus should the underlying GWT events use. We could create an own one without loosing functionality but a better thing that we can do is to provide an injection point and provide a mechanism to make our events participate in the application’s dependency injection context and use the application’s event bus instead of an own instance.

    To achieve this, we have created a GIN module in the “eventsfwk” package:

    This module should be installed in the application’s dependency context and it will inject an static field in the “GwtSimpleEvent” class which is the event bus used for our improved events. To install it in our application, the injection module has been modified like this (note the line “install(EventsModule.class);”):

    This means that, when the dependency injection module is initialized at the beginning of the application execution, the previously configured event bus will be statically injected in the “GwtSimpleEvent” class used by all the generated event classes.

    I can not read minds, but maybe you are also wondering why the event fields annotated with “@Inject” get generated and injected. All in all, we don’t call anywhere “GWT.create()” to use the generator class.

    Well, we are not doing it but GIN does. Whenever GIN finds a dependency (something annotated with “@Inject”) and that dependency has not explicitly been configured (bound in the GIN modules), GIN invokes “GWT.create()” as fallback strategy. This simple mechanism allows us to generate and inject our event in only one step.

    Wow! This post has been “hardcore” GWT, don’t you think? Maybe even too “hardcore”. Please, just let me know if you like it and what do you think about the approach.

    See you in a future post!

    The source code for the initial version of the application can be downloaded here. The final version here. To see any of the applications working, unzip the corresponding 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.

    GWT Dependency Injection recipes using GIN (III)

    June 20th, 2011

    This is the third part of a series about Dependency Injection in Google Web Toolkit using GIN. If you have not yet read the first and second parts, you maybe should do it before reading this third and last article.

    In this article, we will introduce two GIN features: “constants binding” and “static injection”.
    To do this with an example, let’s refactor the “serve button” in the “Simulator” main class of the second part into an own class:

    Here the new extracted “ServeView” class:

    As you can see, the constructor of this new class is annotated with the “@Inject” annotation and receives two parameters. One of them is the racket and the other is the button’s label. In the case of the racket, it is already defined as an injectable dependency in the injector interface and in the case of the button’s label, it should be a configurable constant.
    GIN, by mean of “constants binding”, performs the binding of injectable dependencies to constants.
    Because the type of the “serveText” is String, we need to be more specific here and therefore we have annotated this dependency with the “@Named” annotation. To configure the constant value to bind to, we need to add the following line into our “InjectorModule” class:

    To let the other constants in the application be configured in the same way and to introduce the last GIN feature (“static injection”), let’s now modify the “Simulator” main class as follows:

    And our “InjectorModule” like this:

    The “static injection” allows us to inject the static fields of a class. This happens by mean of the method “requestStaticInjection” of the GIN module class and, in our application, we use it to inject the static dependencies of the “Simulator” class.

    This way, even when the “Simulator” class does not participate in the dependency injection context, its static members will be injected making the explicit references to the injector not required.

    This has the side-effect of making the “Injector” getters no more necessary leaving our injector interface “empty”:

    Please note that, in order to get the dependency injection context configured and initialized, it is required to instantiate the “Injector” interface by mean of the “GWT.create()” method as part of the application initialization. This is done in our case within the “initInjection” method in the “Simulator” main class.


    If you have read the 3 articles of this series, maybe you can remember how our demo application looked like at the beginning. While the functionality and appearance has not changed at all, the intern structure of the application is completely different.

    In my opinion, dependency injection allows a much cleaner structure, enables configuring the application in an elegant and easy way and, when used together with an event bus, produces low-coupled high-modular applications.

    Of course, “there is no free lunch” and using GIN means also that the development team has to learn new concepts and introduce a new framework in the application. Anyway, dependency injection is an already proven concept and GIN is being intensively used in most of the new GWT projects and GWT frameworks.

    While some minimal application structure optimizations could still be applied to the application, the thing that I still find improvable in it is the verbosity of the GWT events definitions. This requires writing some boilerplate classes to ensure the type safety (event handlers), and also the definition of the own event classes is too verbose, being possible to generate them automatically in most of the cases by using either GWT’s deferred binding or a JDK 6 annotation processor. If you know how the events in CDI are defined, very probably you will agree with me that such an approach would be much more elegant and concise.

    A solution for that, even when it requires dependency injection, is more related to other topics and therefore a subject for a different thread. If you got curious, stay tuned for a future post on code generation in GWT! 🙂

    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.

    As always, I hope that you enjoyed reading this series of articles as much as I did writing it and hope to see you soon in a future post!

    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”:

    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:

    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:

    The “PongView” class is almost identical and will not be shown here.

    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:

    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:

    To install this factory in our dependency injection context we need to modify our GIN module class like this:

    And in the injector class, we have to expose the factory as any other dependency:

    And last but not least, let’s use the assisted injection in our application:

    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:

    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:

    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:

    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:

    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:

    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:

    Then, in the “Simulator” class, use the injector to also create the views like this:

    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:

    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.

    LEGO® Java (IV): Apache Camel, Spring and ElasticSearch

    March 24th, 2011

    If you don’t know it yet, this is the fourth part of a series about Apache Camel. The previous posts can be found here: first part, second part and third part.
    In this fourth article, we are going to show how to properly use the Spring framework in the sample application, while adding some extra functionality to it.

    Extracting RSS feeds

    If you remember what we have done so far, the sample application is capable of, given the URL of a web page, extract the text content of the body paragraphs. To make our application a little more powerful, let’s add some functionality to extract the contents of web pages listed in RSS feeds. To accomplish this, add a new class called “RssExtractorRoutes” with the following content:

    This simple route uses the Camel “rss” endpoint to access the RSS feed from BBC news, transforms the content with the rss “marshaller” and then extracts the article links by mean of XPath. As last step, it routes the extracted links to our already existing “page extractor” route.

    Because we have added a new component, we need to add a new dependency to our Maven pom file:

    We need to apply this new route builder to the camel context and we will also eliminate the code used to send a URL to the extractor route. For this, adjust the code of the main class like this:

    If you run the application, you should see in the log entries that all the articles present in the feed are routed to the extractor and afterward, the extracted paragraphs get lost in the space.
    Let’s do something useful with them and store them in a search index. For that, we could use the Apache Lucene “endpoint” that Camel already offers, but instead of this, let’s use an Elastic Search node and explore how to configure and manage the life cycle of an Elastic Search instance by mean of Spring.
    We need a new Elastic Search “bean” class with this content:

    This class is a little bit more complicated than what we have done until now, but what it basically does is creating an elastic search “local” node, offering a method to index a content under a certain structure and another method to search for a text within the previously indexed contents. Some aspects of the bean are also configurable: the name of the index, the type of the content, the index field where the content will be stored and the number of returned search results.

    To use it in the RSS extractor, adjust the code like this:

    And finally, add the Eleasctic Search dependency to the Maven pom file:

    If you paid attention to the changes in the RSS extractor route builder, you should have noticed that now we have created an static instance and configured it in an static way. This is not completely bad but it has some disadvantages and one problem:

    • If we would like to test this route, we cannot supply a different implementation of the bean.
    • In case that we want to change the name of the index, the name of the field or any other configurable value, we have to do it in the code and recompile the application.
    • When the bean is created, the Elastic Serach node is correctly initialized but, when is the “close” method called to shutdown the instance properly? This is, of course, the problem I mentioned.

    To correct these issues, we can take advantage of the Spring framework and the excellent Spring support that Camel offers.

    First of all, let’s include the Spring dependency in our Maven pom file:

    Now, let’s create a file named “camel-context.xml” under “resources/META-INF/spring” with this content:

    And as last step, adpat the “main” class like this:

    If you run the application now, the only difference that you should notice is that the application does not stop after 100 seconds.
    By using the “Main” class that the Camel Spring support offers, we are starting the Spring container and looking for Spring configuration files that will be automatically loaded and used to configure the Spring container. Such files should have the extension “.xml” and be placed under the “META-INF/spring” package.
    The “enableHangupSupport” call instructs the application to listen to “ctrl-c” key strokes and, before terminating, to stop properly the Spring container.

    Now that we have configured Spring, let’s move the Elastic Search bean into the Spring beans file (“camel-context.xml”):

    And adjust the Rss extractor route like this:

    What we have done with these changes is: letting Spring instantiate and configure an unique instance of our bean (a singleton) and instructing Spring to invoke the “close” method whenever the container is destroyed (what happens when the user presses “ctrl-c” on the shell).
    Because now the bean will be searched by name in the Camel bean registry (the Spring container in our case), in order to substitute the bean implementation with another one, it would be enough to use a different spring configuration file or to overwrite the bean definition by loading a second beans file with a new definition of the same bean. This is a convenient thing if, for example, we want to use mocks for testing or want to have different search services.
    To avoid having to edit the spring beans file in order to change the Elastic Search bean configuration values, we can use a spring “PropertyPlaceHolderConfigurer” and create a properties file in the classpath (we will store it within the application and under the “resources” directory):

    With this configuration change, Spring searches in the top-level package for a properties file with the name “elasticsearch.properties” and resolves the “${}” values against it, giving us more flexibility to alter these values without affecting the application.

    To end this article doing something useful with our indexed contents, let’s create a search web service that allows us executing a search query and displays a web page with the matching article links.

    For this, create a new route builder:

    Notice that now, it is not necessary to add explicitly the new route builders to the camel context due to the fact that Spring will instantiate the context and look for route builders under the package “com.canoo.camel” (as configured in “camel-context.xml”).

    We need also to extend the functionality of the class “HtmlFormatterBean” as follows:

    Please notice that, because now this bean has more than only one method, you will also need to specify the method to call in every bean reference within the application.

    To test our new search service, start the application and point to the URL: http://localhost:8080/search?query=news. If some of the indexed articles contains the word “news”, you should see a list with their links.

    The camel ride ends here. I hope that you enjoyed reading the articles as much as I enjoyed writing them. I also hope that it has helped you in getting to know how Camel works and that you can found some use cases where to apply this slightly different way of building integration applications.

    The code of this fourth part is here, to execute the application just unzip the file, change to the directory where the pom file is and type ‘mvn compile exec:java -Dexec.mainClass=”com.canoo.camel.Part4″‘ in the console.

    Hope to see you soon in another post!