Unity3d Notification Manager Asset

Notification Manager is a plugin for unity3d that allows you to display simple onscreen notifications. The “look and feel” is easily customized by changing the foreground and background colors or by changing the coloring mask. Notification Manager is used for simple on-screen debugging messages, or as an achievement system.

$2Buy it here.


GWT IoC – Dependency Injection Practicum

Using GWT with GIN you can have automatic dependency injection on the client side of the application.  This is one of my favorite things about using GWT, because you write in java and cross-compile to JS it makes it much easier to support concepts like Dependency Injection (DI).

GIN is built on top of Guice and while it only supports a subset of what Guice can do its still quite a bit.   Gin conforms to JSR-330 so it uses the standard @Inject annotations just like its platform counterparts (Spring3, Guice, atInject, etc..)   The interesting thing to know about GIN is that it does all of its work at compile time, so you can’t do dynamic runtime rebinding.  However, it does mean that compared to manual DI there is practially zero overhead to using the library.

Setting Up GIN

Inheriting the GIN module

You have to inherit the GIN Module in your xml file

<module>
  ...
  <inherits name="com.google.gwt.inject.Inject"/>
  ...
</module>

Define a Ginjector

A Ginjector is an interface that extends Ginjector, it defines any root level objects that you want to get from the injector. This is a primary difference where GIN differs from traditional DI frameworks, in that because it is done during compilation you must define up front the object graph you are going to use.

public interface MyWidgetGinjector extends Ginjector {
  MyWidgetMainPanel getMainPanel();
}

Define Bindings

Bindings are defined in a class that extends AbstractGinModule. The bindings syntax matches the general Guice syntax.

public class MyWidgetClientModule extends AbstractGinModule {
  protected void configure() {
    bind(MyWidgetMainPanel.class).in(Singleton.class);
    bind(MyRemoteService.class).toProvider(MyRemoteServiceProvider.class);
  }
}

Associate Bindings to Ginjector

On the interface that extends Ginjector add an @GinModules interface

@GinModules(MyWidgetClientModule.class)
public interface MyWidgetGinjector extends Ginjector {
  MyWidgetMainPanel getMainPanel();
}

Instantiate the Ginjector

Use GWT.create to make an instance of the Ginjector interface. Once you have this reference you are ready to kickstart the injection process.

public class MyWidget implements EntryPoint {
  private final MyWidgetGinjector injector = GWT.create(MyWidgetGinjector.class);
  public void onModuleLoad() {
    MyWidgetMainPanel mainPanel = injector.getMainPanel();
    RootPanel.get().add(mainPanel);
  }
}

Once the application calls getMainPanel() the injector can then start traversing the dependency graph and start to build up any dependent classes required to build the main panel.
That is all there is to it, then you are free to @Inject to your hearts content.

GWT Dispatcher – Practical Use of the Command Pattern

Last week I talked about The Anatomy of a GWT Project.  I thought it might be nice to delve into a little more detail about the practical application of  the components referenced.

Definition:

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.  Four terms always associated with the command pattern are command, receiver, invoker and client. A concrete command object has a receiver object and invokes a method of the receiver in a way that is specific to that receiver’s class. The receiver then does the work. A concrete command object is separately passed to an invoker object, which invokes the command, and optionally does bookkeeping about the command execution. Any concrete command object can be passed to the same invoker object. Both an invoker object and several concrete command objects are held by a client object. The client contains the decision making about which commands to execute at which points. To execute a command, it passes the command object to the invoker object.

That is all fine and good but lets look at it in practical terms inside a GWT application.  I like to use the gwt-dispatch library.

Defining Actions

The first thing you need to think about is what are my actions.  In general actions are atomic, this will make it easiest to add a rollback function if you should choose to do so. Lets create a hypothetical action ‘AddUser.’

public class AddUserAction implements Action {

    private String username;
    private String password;

    /** For serialization only. */
    AddUserAction () {}

    public AddUserAction ( String username, String password ) {
        this.username= username;
        this.password= password;
    }

     [....]
}

Here we define the class that represents the action and implements Action<>. In the generic type for the interface we define the result we expect to receive from this action, in this case a UserResult. Then the class is a pretty boring bean, the only exception is to remember to include a no-arg constructor because the object will be serialized/deserialized automatically.

Defining Results

In the section above we said that invoking an AddUserAction would result in receiving a UserResult. So lets define one.

public class UserResult implements Result {
    private int userid;
    private String username;

    /** For serialization only. */
    UserResult () {}

    public UserResult ( int userid, String username ) {
        this.userid= userid;
        this.username = username ;
    }

    [...]
}

Same as before we have constructed a pretty boring bean, just remember the no-arg constructor for serialization. Now you have fully defined the command.

Invoking Commands

Now that you have defined a command, let’s take a look at how to invoke one. The first step is getting a Dispatcher.

private final DispatchAsync dispatchAsync = new StandardDispatchAsync(
                          new DefaultExceptionHandler());

The dispatcher is the class that takes actions and sends them to the server. Typically you can use it as a singleton on the client side. If you are using GIN, you can define it as an @Singleton and let it take care of the propagation of the dispatcher for you. Calling of the action is simple:

dispatchAsync.execute( new AddUserAction ( "user1", "password" ), new AsyncCallback() {
            public void onFailure( Throwable e ) {
                Window.alert( "Error: " + e.getMessage() );
            }

            public void onSuccess( UserResult result ) {
                Window.alert( "User Added: " + result.getUserId() );
            }
} );

And that is all that is required to invoke an action. The dispatcher automatically takes care of the serializing and processing the action as an asynchronous event. Simple.

Processing Commands

Adding a command processor is almost as easy, they are defined as implementing ActionHandler. Every ActionHandler is encapsulated in its own class.

public class AddUserActionHandler implements ActionHandler<adduseraction, userresult=""> {

    public Class getActionType() {
        return AddUserAction.class;
    }

    public synchronized UserResult execute( AddUserAction action, ExecutionContext context ) throws ActionException {
        [create user (action.getUsername(), ...)]
        return new UserResult( ... );
    }

    public synchronized void rollback( AddUserAction action, UserResult result, ExecutionContext context ) throws ActionException {
        // Undo the action.
        [delete user (result.getUserId())]
    }
}

The pseudo-code for actually doing work is abbreviated in [..], but as you can see the ActionHandler is written as a very simple class. Note also that the execute method is synchronous, this makes it easier to unit-test.

Binding Servlets

There is a small about of business in wiring the dispatch servlet into the runtime context, and there are several methods for doing it. Since Guice is listed in the things I can’t live without, I will show that version of it.

Step 1: Define the Servlet Endpoint
Define a ServletModule and bind it to the endpoint ‘/dispatch’

public class DispatchServletModule extends ServletModule {
    @Override
    protected void configureServlets() {    
        serve("/dispatch").with(GuiceStandardDispatchServlet.class);
    }
}

strong>Step 2: Define an Actions Module
Bind the Action to the ActionHandler.

public class ActionsModule extends ActionHandlerModule {
    @Override
    protected void configureHandlers() {
        bindHandler(AddUserAction.class, AddUserActionHandler.class);
    }
}

strong>Step 3: Install the Module
In the GuiceServletContextListener where Guice is initialized add the ActionModule to the list.

@Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServerDispatchModule(), new ActionsModule(), new DispatchServletModule());
    }

Advanced Usage: Action Batching

Actions are great, they allow you to segment your applications into atomic actions. However sometimes it would be nice if you could execute multiple actions at once without having to nest the actions or wait for multiple round trips to finish. The gwt-dispatch library has a built-in batching function. In your ActionHandlerModule bind the following handler:

@Override
	protected void configureHandlers() {
		bindHandler(BatchAction.class, BatchActionHandler.class);
                [...]
        }

Now your application is ready to process BatchActions. A BatchAction takes in its constructor multiple actions, and the BatchResult returns a collection of results that correspond to the actions in the same order the were passed to the constructor.

Conclusions

Defining actions and Results is a simple way to encapsulate behavior and an easy way to extend the functionality of your website. I really like the fact that I didn’t have to define any handlers in the web.xml and the deployment is extremely easy and straightforward. Hopefully you can find several applied uses of the Command Pattern.

The Anatomy of a GWT Project

What is GWT?

I guess a little background first for the uninitiated.  Formally known as Google Web Toolkit, is a project that allows you to write your webcode in Java and then it transpiles (source-to-source compile) the java code into JavaScript.    This allows you to develop an application that run using JavaScript (which is everywhere) without the nightmare of actually writing (or reading) JavaScript.

The largest bonus is that you get to use all of the great and wonderful tooling that comes with Java.  Say what you will about the language itself, but the Java language has some of the best tooling around (code coverage, unit testing, dependency injection, mockito, eclipse, etc…) and access to these tools and the really nice patterns that have been developed in Java make development very productive.

From the GWT manual

Java technologies offer a productive development platform, and with GWT, they can instantly become the basis of your AJAX development platform as well. Here are some of the benefits of developing with GWT:

  • You can use all of your favorite Java development tools for AJAX development.
  • Static type checking in the Java language boosts productivity while reducing errors.
  • Common JavaScript errors (typos, type mismatches) are easily caught at compile time rather than by users at runtime.
  • Code prompting/completion is widely available.
  • Automated Java refactoring is pretty snazzy these days.
  • Java-based OO designs are easier to communicate and understand, thus making your AJAX code base more comprehensible with less documentation.

What about browser differences?

We all know that IE has a tendency to be a bit of a pain in the backside when it comes to making you site look and behave like other browsers, it is really no difference when it comes to the JavaScript in the browser.  Fortunately GWT compiles multiple permutations of your application, once for each browser dialect and then at runtime it serves the right version.  So everything works the same  between browsers.

The Anatomy of an Application

As with any toolkit or framework once you have it you are free to shoot yourself in the foot with it, so Google generally gives many talks on GWT Best Practices at their annual IO conference.  Back in 2009 Ray Ryan gave a talk about the architecture of an application. It is a great video and I still suggest that people watch it.  It is interesting because during his talk he referenced a number of technologies and concepts that weren’t incorporated into the toolkit yet.  Then they were released as libraries that you could pull in, then some of them were promoted to be stock members of the toolkit.

So now in 2013 I thought I would take a look back at the best practices and talk about the current state of thing.

UIBinder (Declarative UI, MVP)

This is a big one, and one of my favorite upgrades to GWT from its initial versions.  When you are writing a webapp, it is unnatural to use anything other than HTML and CSS.  The UIBinder allows you to do just that you can layout all of the panels and widgets using quasi-normal markup.  This really helps when you are working with designers that aren’t going to be the ones that actually code the application, because you can reuse their designs and styles directly in the application.

More can be read about the UIBinder here: http://www.gwtproject.org/doc/latest/DevGuideUiBinder.html

Gin (IoC)

Once I had experienced a dependency injector I no longer can remember living without it, it was a very trans-formative event in my professional career.  On the server side I like to use Guice as my IoC container, and the good thing is that for the client side they have GIN.  GIN is great because it supports most all of the same semantics of Guice, but is stripped down for the client side.  The primary difference is that GIN does all of its injection at compile time, so you can’t do runtime substitutions of classes, but that isn’t something that I have ever really wanted to do on the client.

This way you can write all of you classes the way you normally would so they are accessible and easy to unit test and then allow the injector to wire it all up for you.

GWT Dispatch (Command Pattern)

This is one of the patterns/libraries that  I really like.  I know several developers that prefer the stock GWT RPC, but I always hate defining all of the servlets require.  The GWT Dispatch library implements the command pattern where you define a series of Actions that are serialized (automatically) and corresponding ActionHandlers on the server.   For me this is a much cleaner pattern and much easier to extend, and because it all shares the same servlet endpoint it is much easier to refactor.   Also if you use this pattern, you get the ability to do call batching for free (its built in) and you are 80% of the way to have an undo stack.  Each Action handler allows you to define rollbacks for actions, its just up to you on how you want to track the stack.
Read More about the command pattern here.

History, Activities, and Places

This is where it all comes together.  The key to writing a successful client side application, is how you structure it so that the back button works.  I hate it when I see developers tell clients that they can’t use the browsers back button, or have to build their own back button into the application.   As of version 2.1 (which was a while ago) GWT started to build tools that would help with history tracking, and that was nice but for a long time it was still largely up to the developers to figure out.  Then they added support for Places and Activities.

I believe this is the most important page in their manual, and the concept that people should spend the most time understanding.  Mastering the Activity and Place controllers will allow you to easily use the tools outlined above while achieving auto-magic support for history tokens and the back button (as well as bookmarks etc..)

I have built many different applications that use the methods outlined about and am excited to see how the toolkit will continue to evolve to make programming large scale ajax applications more pervasive and less painful in the future.

New Project: JAXB4GWT

I was tired of seeing all of the XML parsing code in one of my GWT applications.  Because if the way the application was structured, it was impossible to do the xml parsing on the server and return a serialized bean back to the client.  So my approach was to emulate jaxb for the GWT client side.

My approach uses a generator, so all the parsers are created at compile time and linked into the application.

Project Home: http://code.google.com/p/gwtjaxb/

I have gone through several iterations of development, and am pleased to release version 1.0.0.  I am using this library in some of my own projects that are in production, and parsing some XML that is found in the wild.