• Home
  • About
  • JavaOne 2011 Monday

    October 4th, 2011

    The technical keynote started with a weird JavaZone-style video featuring a Java programmer as a rapper. It was certainly intended to be funny but as far as I can tell, it didn’t catch on.

    The keynote was packed but the somehow reduced ballroom layout added to this impression. Attendance was said to be twice that of last year (so probably around 10’000). Even though there are certainly more people than last year, a doubled number seems a bit exaggerated to me. Throughout the day, all talks were well attended, though, but nothing like in the days when JavaOne had 10’000 attendees in Moscone Center.

    The technical content was not surprising, beside that Oracle now advertises its NoSQL solution, which is based on the former Berkeley DB. As expected JavaFX 2.0 GA has been announced along with the respective tooling and covered by 50 (!) talks on JavaFX at JavaOne. The JavaFX presentation started very conventionally but in the end showed some really cool lab projects with a dancing duke steered by gesture recognition.

    The best presenter was Mark Reinhold on Java 7/8/9. Good style, nice slides, perfect pace, interesting (but not really surprising) content. New to me was project Nashorn: new JavaScript implementation for the JVM expected for Java 8. Project Lambda is planned to contain “defender methods”, default implementations for interface methods. That sounds like traits and actually I expect some issues when doing this in Java.

    Overall, the keynote was missing the JavaOne “feeling” from the olden Sun times. There was no host that led through the event, welcomed the attendees, and encouraged everybody to network. No big names on stage, no overwhelming achievements. The crowd left the room unexcited.

    For the rest of the day I was mainly concerned with preparing and delivering my own talks on “Extending Java’s reach with Groovy” and “Pro Groovy”. They were well attended and received.

    Andres delivered his Griffon talk in parallel.

    Afterwards, I was a tired but still listened to Charles Nutter on JVM bytecode, Dan Sline on Griffon, and Jim Discroll on Groovy DSLs. Quote to take away: “Oracle ADFm makes heavy use of Groovy!”

    That’s it for today.


    Testdata generation

    September 26th, 2011

    We’ve all being there, we’ve all had this on a project once or maybe even more times. The assignment is to build an application, but there is no data for you to work with. There could be any number of reasons this could be the case to name a few, the web-service that should be connected is not done in time, the database migration is postponed. Then someone has to create database scripts with test data, or implement a test web-services. This is all a waste of time.

    But lucky for you now there is a solution.

    I’ve created an little test data framework that is easy to setup and will create test data automatically. So how does it work? Simple, its entry point is a method interceptor that you can wrap around anything you want, it doesn’t even have to be an implementation. So that DAO you want to use, but the database is still empty, just let the framework step into place and all the methods return the data that you want.

    It can also be handy to create test data for you unit test. You need to test if you bean serialization works, or want to put an entity into a in memory database with dbunit. Just call the framework with you bean class and the framework will return an instance filled with test data. It will read the existing annotations that you have on your entity bean an will only generate data that is valid for you bean.

    Here is an example of how it works:

    
     //Create an instance of the Employee class and fill it with test data.
     Employee employee = TestData.createBeanInstance(Employee.class);
    
     //Annotations that restrict the data for first name are recognized.
     assertNotNull(employee.getFirstName());
    

    To create a service that returns test data on it’s service methods:

    
     //create a instance of the service class/interface that will return test data
     Service exampleService = TestData.createService(Service.class);
    
     //this now returns a list of employee instances that are filled with test data
     List<Employee> employees = exampleService.findByName("name");
    

    Create a dbunit xml file:

    
     //create a file
     File fileLocation = File.createTempFile("file", ".xml");
    
     //populate the file with test data for the employee
     TestData.createDBUnitDataSet(Employee.class, fileLocation);
    

    If employee has relations with other classes, like employees have managers these objects will also be in the generated xml file.

    To give it a spin add the following into you pom.xml

    
         <dependency>
             <groupId>ch.nerdin</groupId>
             <artifactId>testdata-framework</artifactId>
             <version>0.10</version>
         </dependency>
    

    or if you use ivy, gradle or something else you properly know how to use this information as well.

    So nothing holding you back to make your data driven test easier to setup, or to stub out you migration points. I’m hosting this code on github so if you have issues, comments or even better contribute please do so.


    GWT and HTML5 Canvas, the future of the web?

    August 25th, 2011

    The future of computing lies in mobile computing, more and more devices come on the market, tablets and phones that will connect through the Internet as technology is getting cheaper and wifi and 3g more common. That means our software will also need to run on these handheld devices, because our clients will want their services on all platforms. This is what Java set out to do 15 years ago, so that we have the ability to write software once and run it everywhere. The problem is these new platforms, that I believe will make up a large part of the future have, until now, no Java. It would be great if we can find something that will give us the ability to write our software only once.

    I believe that the technology that is going to deliver us this promise is called HTML5. More and more applications will run inside you browser. I’m typing this article in google docs, which is a perfect example of how applications will evolve. No need to install anything or maintain up to date versions, even an operating system could be very minimalistic (google chrome). So Google is obviously sharing this vision, but also Microsoft is building it’s next version of office on something that is based on their web-browser.

    Sadly the development language of HTML5 Javascript and not Java. Java has been around a long time and there are a lot of libraries that people have made. Would be cool if we can still use these, the answer is Googles Web Toolkit. GWT provides a way to code in Java and then translate that code into Javascript. This way we can still use all that great stuff that others made.

    A good example of this future is Angry Birds, you have probably heard of this game. To create this game they have taken the java implementation of box2d called jbox2d and created a javascript version of that with the help of GWT. Once that is done you can use HTML5 Canvas to draw the Birds and calculate their positions if they are falling. Now because they have build it this way with HTML5 this game could also work on an iPhone, but even better because android is based on java you could create from this source a android version with only one line of code.

    Have a look at some of the great things people are building with the HTML5, be sure that your browser supports it.

    1. Drawing program deviantART
    2. Old style game with new technology area5
    3. Quake GWT HTML5 port

    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:

    
    public class CDISample {
        @Inject
        private Event<String> event;
    
        public void handler(@Observes String payload) {
            System.out.println(payload);
        }
    
        public static void main(String[] args) {
            event.fire("Hello event world!");
        }
    }
    

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

    
    public class GWTSample {
        @Inject
        private SampleEvent event;
    
        public void execute() {
            event.dispatchTo(new Handler<String>() {
                public void onEvent(String payload) {
                    Window.alert(payload);
                }
            });
    
            event.fire("Hello event world!");
        }
    
        public interface SampleEvent extends Event<String> {
        }
    }
    

    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):
    
    public class PingEvent extends GwtEvent<Handler> {
        public static Type<Handler> TYPE = new Type<Handler>();
    
        @Override
        public Type<Handler> getAssociatedType() {
            return TYPE;
        }
    
        @Override
        protected void dispatch(Handler handler) {
            handler.onEvent(this);
        }
    
        public interface Handler extends EventHandler {
            void onEvent(PingEvent event);
        }
    }
    

    With the new approach, the resulting “PingEvent” would look like this:
    
    public interface PingEvent extends Event<Void> {}
    

    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:

    
    ...
        <generate-with class="com.canoo.gwt.events.server.eventsfwk.EventGenerator">
            <when-type-assignable class="com.canoo.gwt.events.client.eventsfwk.Event"/>
        </generate-with>
    ...
    

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

    
    public interface Event<T> {
        public void fire(T payload);
    
        public void dispatchTo(Handler<T> callback);
    
        public interface Handler<T> {
            public void onEvent(T payload);
        }
    }
    
    public class EventGenerator extends Generator {
        private static final String EVENT_IMPL = "EventImpl";
        private static final CodeTemplate GWT_SIMPLE_EVENT_TEMPLATE = new GwtSimpleEventTemplate();
        private static final CodeTemplate EVENT_IMPL_TEMPLATE = new EventImplTemplate();
    
        @Override
        public String generate(TreeLogger treeLogger, GeneratorContext generatorContext, String typeName) throws UnableToCompleteException {
            TypeOracle typeOracle = generatorContext.getTypeOracle();
    
            JClassType parentEventType = typeOracle.findType(Event.class.getName());
            JClassType eventType = typeOracle.findType(typeName);
            JClassType payloadType = findPayloadType(eventType, parentEventType);
    
            String gwtSimpleEventImplName = generateGwtSimpleEvent(treeLogger, generatorContext, eventType, payloadType);
            String eventImplTypeName = generateEventImpl(treeLogger, generatorContext, eventType, payloadType, gwtSimpleEventImplName);
    
            return qualifyInGwtEvents(eventImplTypeName);
        }
    
        private static JClassType findPayloadType(JClassType eventType, JClassType parentEventType) {
            JClassType interfaces[] = eventType.getImplementedInterfaces();
            for (JClassType anInterface : interfaces) {
                if ((anInterface instanceof JParameterizedType) && (anInterface.getErasedType() == parentEventType.getErasedType())) {
                    JParameterizedType parametrizedType = (JParameterizedType) anInterface;
                    return parametrizedType.getTypeArgs()[0];
                }
            }
            throw new IllegalStateException("Payload type not found for: '" + eventType + "'.");
        }
    
        private String generateGwtSimpleEvent(TreeLogger treeLogger, GeneratorContext generatorContext, JClassType eventType, JClassType payloadType) {
            String gwtSimpleEventImplName = getGwtSimpleEventImplName(eventType);
    
            PrintWriter gwtSimpleEventPrintWriter = generatorContext.tryCreate(treeLogger, getEventsPackageName(), gwtSimpleEventImplName);
            GWT_SIMPLE_EVENT_TEMPLATE.generate(gwtSimpleEventPrintWriter, getEventsPackageName(), gwtSimpleEventImplName, payloadType.getName());
            generatorContext.commit(treeLogger, gwtSimpleEventPrintWriter);
    
            return gwtSimpleEventImplName;
        }
    
        private String generateEventImpl(TreeLogger treeLogger, GeneratorContext generatorContext, JClassType eventType, JClassType payloadType, String gwtSimpleEventImplName) {
            String eventImplTypeName = getEventImplTypeName(eventType);
            String eventTypeName = getEventTypeName(eventType);
    
            PrintWriter eventPrintWriter = generatorContext.tryCreate(treeLogger, getEventsPackageName(), eventImplTypeName);
            EVENT_IMPL_TEMPLATE.generate(eventPrintWriter, getEventsPackageName(), eventType.getQualifiedSourceName(), eventImplTypeName, eventTypeName, gwtSimpleEventImplName, payloadType.getName());
            generatorContext.commit(treeLogger, eventPrintWriter);
    
            return eventImplTypeName;
        }
    
    ... (some methods omitted)
    

    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:

    
    public class EventsModule extends AbstractGinModule {
        @Override
        protected void configure() {
            requestStaticInjection(GwtSimpleEvent.class);
        }
    }
    

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

    
    @GinModules(Module.class)
    public interface Injector extends Ginjector {
        public static class Module extends AbstractGinModule {
            @Override
            protected void configure() {
                bind(EventBus.class).to(SimpleEventBus.class).in(Singleton.class);
    
                install(new EventsModule());
                install(new GinFactoryModuleBuilder().build(Factory.class));
    
                bindConstant().annotatedWith(named("PingText")).to("Ping");
    
    ... (code omitted)
    }
    

    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:

    
    ...
            final Button button = new Button("Serve!");
            button.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    button.setVisible(false);
                    injector.getRacket().serve();
                }
            });
    ...
    

    Here the new extracted “ServeView” class:

    
    public class ServeView extends Button {
        @Inject
        public ServeView(final Racket racket, @Named("ServeText") String serveText) {
            super(serveText);
            addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    setVisible(false);
                    racket.serve();
                }
            });
        }
    }
    

    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:

    
    ...
            bindConstant().annotatedWith(named("ServeText")).to("Serve!");
    ...
    

    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:

    
    public class Simulator implements EntryPoint {
        @Inject
        static ServeView SERVE_VIEW;
    
        @Inject
        static AssistedInjectionFactory FACTORY;
    
        @Inject
        @Named("PingText")
        static String PING_TEXT;
    
        @Inject
        @Named("PongText")
        static String PONG_TEXT;
    
        public void onModuleLoad() {
            initInjection();
            RootPanel.get("buttonSlot").add(SERVE_VIEW);
            RootPanel.get("pingSlot").add(FACTORY.createPingPongView(PING_TEXT, PingEvent.class));
            RootPanel.get("pongSlot").add(FACTORY.createPingPongView(PONG_TEXT, PongEvent.class));
        }
    
        private void initInjection() {
            GWT.create(Injector.class);
        }
    }
    

    And our “InjectorModule” 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));
    
            bindConstant().annotatedWith(named("PingText")).to("Ping");
            bindConstant().annotatedWith(named("PongText")).to("Pong");
            bindConstant().annotatedWith(named("ServeText")).to("Serve!");
    
            requestStaticInjection(Simulator.class);
        }
    }
    

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

    
    @GinModules(InjectorModule.class)
    public interface Injector extends Ginjector {
    }
    

    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.

    Conclusions

    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!