We’re going to use Maven

Well, we’re going to take a little longer to set up the project since we decided to use Maven !

Here are some words that Richard Allen posted on the Gwt-Platform group. This convinced us.

We have a large codebase with many projects that share a large amount of code housed in other projects. I used Ant for several years, but became frustrated with how much effort was required to maintain the whole build environment, and how I was regularly having to create custom solutions for things, like dependency management, that I felt should be the tool’s responsibility. I migrated all of our projects to Maven2 several years ago and have been very pleased. Maven is by no means perfect, so it will frustrate you at times. Maven lets you work at a higher level than Ant. Maven provides a lifecycle with phases such as compile, package, and integration-test, where as Ant provides low level tasks that you have to compose into the “phases” that Maven provides. Working at a higher level reduces your workload most of the time, but is a source of frustration when you need to work at a lower level. However, you can simply use the maven-antrun-plugin to run a set of Ant tasks when you want to work at a low level. And you can always write your own plugins to do anything you want. You can also write plugins in Groovy, which we have found to be easier. BTW, Maven3 is adding some nice scripting capabilities.

Maven has greatly reduced the overall maintenance of our build environment, as well as provided many features we didn’t have with Ant. Maven draws a lot of information from your POM files, and there’s much more to Maven than simply a build tool. Here are some of the benefits I believe you would derive from using Maven.

  • Very powerful dependency management. Maven makes it easy to handle your dependencies on third-party libraries, as well as dependencies on other projects that you maintain. Tools like m2eclipse and the maven-dependency-plugin, as well as the dependency reports generated by the maven-project-info-reports-plugin are invaluable when you want to see all your projects’ dependencies, their versions, and the licenses for your third-party dependencies. The dependency reports are great for open source projects because they provide your users (or potential users) an easy way to see what your project depends on while being very simple for you to produce and maintain.
  • Consistent project structure. Sure, you could devise your own project structure that you consistently used among all of your projects, but Maven already provides one that works well, and anyone that has used Maven before will immediately understand your project layout. Like I said, we have many projects, and it’s great that our developers can switch between projects without having to learn something new about the build environment. I love it when open source projects that I use also use Maven, because I can immediately build their project or import it into Eclipse. If they use Ant, it’s a toss up. Some are easy to build and import, others aren’t. There is no consistency.
  • Simple release management. I haven’t used Maven with Mercurial, but I see it supports it. Having used Maven with Subversion, I know Maven makes it very simple to make a release of your project and publish it to a Maven repository for public access, making your release process consistent and easy, as apposed to the error-prone process that many projects use. Maven’s release tools will ensure your code is committed to your source control and that your code passes all of its tests before making a release, and will automatically update the version numbers in the POM files for you. Additionally, you can create a report of changes from your source control system and/or a report of the fixed issues from your issue management system, like JIRA, that went into the release. This is where you start to see that Maven is a whole lot more than just a build tool.
  • Simple integration with unit testing tools and static analysis tools. Maven makes it easy to run your unit tests and integration tests, generate test coverage reports, run static analysis tools such as Checkstyle, PMD, FindBugs, JavaNCSS, and JDepend, and publish those reports to a website. These tools can be helpful to gage the overall quality of your code.
  • Simple reporting and website generation. I’ve already mentioned some Maven reporting capabilities, but Maven also has a general website generation tool. You can write a website in a wiki-like language and pull in all the reports that you generated. Some other reports that are important for projects to publish, which Maven makes easy, are Javadocs, browsable source code, and information on the project’s license, mailing list, source code repository, issue tracking system, the Maven plugins used for building the project, and the list developers.
  • Repository manager. The concept that Maven uses of storing dependencies and associated metadata in a repository instead of a source control system is a huge benefit. You can use a repository manager to cache all third-party dependencies that you get from the Internet to provide your group a stable repository, deploy your own projects (and custom
    Maven plugins) for other developers in your company to use, and even restrict what versions and libraries developers can pull into projects by making the build only get its dependencies from the repository manager.
  • Now, as for using Maven with Eclipse, you have three options. You can use one of two Eclipse plugins, m2eclipse or Eclipse IAM, or you can use the maven-eclipse-plugin to generate Eclipse projects. I have never used Eclipse IAM. My experience with m2eclipse is that it is nice for a small set of projects, but if you have a large multi-project structure like we do, then m2elipse consumes too much resources. So, I install m2eclipse for some of its tools, like seeing a hierarchy of the Maven dependencies for a project, and autocomplete while editing a POM file, but I do not import our projects as Maven projects into Eclipse. Instead, I use the maven-eclipse-plugin to generate all the Eclipse projects, and then I import them as existing Eclipse projects. We use a hierarchical structure for multiple projects, which is what Maven suggests, and so all I have to do is point Eclipse at the top directory and it will find all of the generated projects. The only primary drawback to this approach, as apposed to using m2eclipse, is that you have to re-generate your Eclipse projects if you add or remove a dependency. However, the process is very fast, and you simply have to refresh a project that you have already imported. Some day, I expect m2eclipse or Eclipse IAM to be efficient enough to just use them.

    Hope that helps.

    -Richard

That was a great and complete answer to our question and thanks to him, we finally made our mind !

Thanks Richard and everyone else that took the time to answer either here or on Gwt-Platform group.

4

Unit testing for dummies

Lately I asked one of the most generous Gwt-Platform contributors, Brendan Doherty, to write a small article about unit testing for dummies and, well, he didn’t really do what we had in mind. Still I think he said everything that needs to be said, judge for yourself:

  1. Watch as many videos as you can find on youtube by Miško Hevery, as well as these presentations. I regularly listen to him when driving in my car.
  2. Read everything ever written on the Google Testing blog.
  3. Read http://code.google.com/p/gwt-platform/wiki/UnitTesting for information on how gwt-platform provides assistance when writing your presenter unit tests.

Repeat until you are no longer a n00b.

While it’s not really a tutorial, there’s a lot of information, I’m sure a lot of you will find number one and two pretty instructive (and number three pretty useful!)

UiHandlers and supervising controller

In our last post we told you how to reference your presenter (aka supervising controller) within your view in an elegant and simple way. However, we used a slightly provocative title that may lead you to think we are no longer doing MVP. Let’s get that out of the way: even though we added one arrow to the MVP diagram of Martin Fowler, this new pattern will look and feel perfectly MVP-esque to you. In fact, some people at Google added this arrow long before we did!

What does it mean to you? It means your view is still dumb (sorry, passive, we don’t want to hurt her feelings) enough that you can often afford to test only your presenters. Really, the only thing you’ll notice is an important reduction in the number of smelly anonymous classes and your love story with UiBinder will blossom!

That being said, we already told you how to use the pattern and even gave some tools to automate the process with Gwt-Platform. We decided not to use injection for connecting the presenter to the view, mostly because it would have caused an explosion in the number of class implementations. At that point we felt the user should probably make his own implementation to his liking, injecting a Provider<MyUiHandlers> if desired.

Now let’s explain why we used this pattern and take a look at what is MVP:


As you can see there’s a direct link between the view and the presenter used for forwarding events. We felt, while reading google mvp part 2, that this pattern was doing exactly what we needed to clean things up: delegating events to the presenter.

In the old approach, the view would let the presenter access either the real widgets (bad) or a simple interface such as HasClickHandlers (better). Then the presenter would bind a handler to this object and would be directly notified of any UI interaction. Since each one of these bindings require you to write a cumbersome anonymous class, a complex view would quickly generate a LOT of boiler plate in its presenter.

Instead of doing this, the new approach lets you handle events directly in the view, mapping them to methods in the presenters. If you’re using a 1-to-1 mapping, this does not add any logic to your view. But where does the savings come from? Aren’t you simply moving all these anonymous classes to the view? This is where @UiHandler comes into play! This new annotation is a real boilerplate saver: it automatically binds a widget event to a method from the view class. The only thing left to do is to invoke the corresponding method in the presenter class.

If reducing boilerplate is not a good enough reason for you, there is another important benefit of passing the presenter to the view. Hooked? Sorry, this will have to wait for a future post… Meanwhile, don’t hesitate to give us feedback or to propose subjects!

2

Reversing the MVP pattern and using @UiHandler

EDIT: This post has been slightly edited to follow the new naming convention used in Gwt-Platform.

Through usage, we have found that the second MVP pattern proposed by Google could save us a lot of tedious anonymous classes. This approach mainly consists of creating an interface that your presenter implements and which lets your view access some of its methods. This technique can be readily used with Gwt-Platform, but it is lacking documentation. So now is the time to explain it properly!

The first thing you’ll notice is that the latest version of GWTP introduces some interfaces and abstract classes that makes it easy for you to use this pattern:

  • The HasUiHandlers interface is used to indicate that your view participates in the pattern. A view that implements this interface needs to have uiHandlers, that is, a set of methods it can use to initiate complex actions in the presenter.
  • UiHandlers is a marker interface used to define your controls, you inherit from it and define all the methods your view will need to use.
  • The abstract class ViewWithUiHandlers inherits from ViewImpl and is the straightforward implementation of HasUiHandlers. Your view can inherit from it to save you some typing.
  • The abstract class PopupViewWithUiHandlers is the same as the precedent but inherits from PopupViewImpl. Use it for your dialogs that participate in the pattern.

Now don’t be confused by all these tools. You’ll see that using the pattern is quite straightforward. First you need to create an interface that extends UiHandlers and add all the methods your view needs to call. We usually call that interface MyUiHandlers and place it inside the view to keep things organized:

[sourcecode language=”java”]
public interface MyUiHandlers extends UiHandlers {
void onSave();
}
[/sourcecode]

Your presenter then needs to implement this interface:

[sourcecode language=”java”]
public class ExamplePresenter extends Presenter<ExamplePresenter.MyView, ExamplePresenter.MyProxy>
implements MyUiHandlers {

@Override
public void onSave() {
doSomething();
}

}
[/sourcecode]

Then you have to connect these controls to your view. This is done by letting MyView extend HasUiHandlers and by calling setUiHandlers(impl) within your presenter’s constructor to finalize the connection:

[sourcecode language=”java”]
public class ExamplePresenter extends Presenter<ExamplePresenter.MyView, ExamplePresenter.MyProxy> implements MyUiHandlers {
public interface MyView extends View, HasUiHandlers {
}
@Inject
ExamplePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) {
super(eventBus, view, proxy);
getView().setUiHandlers(this);
}

}
[/sourcecode]

Be careful: since the view is instantiated before the presenter, the setUiHandlers(impl) method will be called after the view’s constructor has executed. This means you cannot refer to the presenter within your view’s constructor. Also, it’s important to call setUiHandlers() early, otherwise you might run into situations where your view needs to access a control when it doesn’t yet have access to them. Just to be on the safe side, you should probably check for null before invoking any control method.

 

The last step is to let your view extends ViewWithUiHandlers or PopupViewWithUiHandlers instead of ViewImpl or PopupViewImpl. Then you’re ready to use your controls via getUiHandlers(). As a result, using the wonderful @UiHandler annotation is now very easy:

[sourcecode language=”java”]
public class ExampleView extends ViewWithUiHandlers<ExampleView.MyUiHandlers> implements MyView {

@UiHandler("saveButton")
void onSaveButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onSave();
}
}
[/sourcecode]

That’s it, you now have a powerful, easy to read and versatile way of using your MVP elements without giving more responsibilities to your view and without breaking the MVP pattern. Your presenter still does all the heavy lifting and your view is still pretty dumb so testing should be a breeze!

 

22

Using @ProxyEvent

A relatively recent feature of GWTP is @ProxyEvent, and at first glance it’s not obvious why it should be needed. This post explores how @ProxyEvent works and gives guidelines on when to use it and when to rely on the regular event registration mechanism. First, let’s look at some code that uses this annotation:
[sourcecode language=”java”]
public class MessagePresenter extends Presenter<MessagePresenter.MyView, MessagePresenter.MyProxy> implements ShowMessageHandler {
// …
@ProxyEvent
@Override
public void onShowMessage(ShowMessageEvent event) {
getView().setMessage();
placeManager.revealPlace(new PlaceRequest(NameTokens.messagePage));
}
}
[/sourcecode]
The first thing that’s really important to understand is that, even though @ProxyEvent appears in your presenter, the handler registration occurs within the proxy. In this case, it means that whenever the proxy intercepts a ShowMessageEvent it will instantiate the MessagePresenter and call its onShowMessage. At that point, the presenter is not necessarily visible, so the method reveals it by navigating with placeManager.revealPlace(…). If the presenter is not a place, you could also use forceReveal(). Be carfeul, however, since forceReveal() can lead to undesirable behavior when used on a place.

So when should you use @ProxyEvent? Basically, you use it every time that an event should have the ability to “wake up” your presenter. That is, whenever the presenter should be notified of an event even before it is first instantiated. This is why the method marked with a @ProxyEvent will often contain a mechanism to reveal the presenter.

These types of event handlers dramatically simplify the process of passing a large amount of information to a presenter before revealing it: bundle the information in the event, fire it, intercept it with a @ProxyEvent, and reveal the presenter inside the handler method.

Ok enough theory, let’s expand the previous example. The following code uses an event we already discussed in Gwt-Platform event best practices. The goal, now, is to navigate to MessagePresenter whenever the event is raised.

[sourcecode language=”java”]
public class MessagePresenter extends
Presenter<MessagePresenter.MyView, MessagePresenter.MyProxy> implements ShowMessageHandler {
@ProxyCodeSplit
@NameToken(NameTokens.messagePage)
public interface MyProxy extends ProxyPlace<HomePresenter> {}

public interface MyView extends View {
void setMessage(String message);
}

final private PlaceManager placeManager;

@Inject
MessagePresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) {
super(eventBus, view, proxy);
this.placeManager = placeManager;
}

@ProxyEvent
@Override
public void onShowMessage(ShowMessageEvent event) {
getView().setMessage();

placeManager.revealPlace(new PlaceRequest(NameTokens.messagePage));
}

@Override
protected void revealInParent() {
RevealContentEvent.fire(this, AppPresenter.TYPE_SetMainContent, this);
}
}
[/sourcecode]
Now every time a MessageEvent is fired, MessagePresenter will be shown. This works even though @ProxyCodeSplit loads this presenter asynchronously, and without having to couple presenters. The example below shows how PuzzleBazar uses a similar strategy to reveal its LinkColumnPresenter whenever it is needed:
[sourcecode language=”java”]
public class LinkColumnPresenter extends Presenter<LinkColumnPresenter.MyView, LinkColumnPresenter.MyProxy>
implements RevealDefaultLinkColumnHandler {

public interface MyView extends View {}

@ProxyStandard
public interface MyProxy extends Proxy<LinkColumnPresenter> {}

@Inject
public LinkColumnPresenter(
final EventBus eventBus,
final MyView view,
final MyProxy proxy ) {
super(eventBus, view, proxy);
}

@Override
protected void revealInParent() {
RevealContentEvent.fire(this, SplitMainPresenter.TYPE_RevealSideBarContent, this);
}

@ProxyEvent
@Override
public void onRevealDefaultLinkColumn(RevealDefaultLinkColumnEvent event) {
forceReveal();
}
}
[/sourcecode]

Ok, so now that you know how to use @ProxyEvent you may wonder why you shouldn’t always use it! The truth is that, in most cases, there is not much harm in using it to listen to an event. Sometimes, however, it may instantiate a bunch of presenters too early, momentarily slowing down your application. For example, imagine the following:

[sourcecode language=”java”]
// Bad example don’t do this!
@ProxyEvent
@Override
public void onNavigation(NavigationEvent event) {
if (event.getRequest().getNameToken().equals("logout")) {
getView().setMessage( "Logout in process…" );
}
}
[/sourcecode]

At first this may seem reasonable. However, it means your presenter will be instantiated as soon as a NavigationEvent is fired, even if this event has nothing to do with the “logout” place. If you have many such presenters, they will all be instantiated at once! In such cases, you probably want the presenter to register towards the handler in its onBind method:

[sourcecode language=”java”]
// The right way
@Override
protected void onBind(NavigationEvent event) {
super.onBind();
addRegisteredHandler(NavigationEvent.getType(), this);
}
@Override
public void onNavigation(NavigationEvent navigationEvent) {
getView().setMessage( "Logout in process…" );
}
[/sourcecode]

Another drawback of abusing @ProxyEvent is that it makes your proxy code bigger, and since all proxies need to be instantiated when your applications starts, this may increase the initial loading time. As a result the rule of thumb is to use @ProxyEvent whenever you need your presenter to “wake up” to an event, and to use addRegisteredHandler in your onBind() method for all other cases.

I hope this helps you better understand that neat little feature of GWTP. If you need more information, you can always look at Gwt-Platform’s wiki. See you soon!

3

Gwt-Platform event best practices

A newer version of this blog post is available here.

As we worked through enhancing the way events were handled in Gwt-Platform, we came across one constatation, no common pattern was used or encouraged. This post addresses this issue and offers a little tutorial about how to create custom events in Gwt-Platform.

First of all, an event contains two major parts: the Event class itself and an Handler. Those two parts can either sit in different files or be included in the same file, with the Handler nested inside the Event. The second approach is our favorite since Handler is an interface related to an event. Also, it can be done in a few lines and reduce the total number of files.

Give that, here’s how we write our events:

[sourcecode language=”java”]
public class ShowMessageEvent extends
GwtEvent<ShowMessageEvent.ShowMessageHandler> {
public interface ShowMessageHandler extends EventHandler {
void onShowMessage(ShowMessageEvent event);
}

private static Type<ShowMessageHandler> TYPE = new Type<ShowMessageHandler>();

public static void fire(HasEventBus source, String message) {
if (TYPE != null) {
source.fireEvent(new ShowMessageEvent(message));
}
}

public static Type<ShowMessageHandler> getType() {
return TYPE;
}

private final String message;

public ShowMessageEvent(final String message) {
this.message = message;
}

@Override
public Type<ShowMessageHandler> getAssociatedType() {
return TYPE;
}

public String getMessage() {
return message;
}

@Override
protected void dispatch(ShowMessageHandler handler) {
handler.onShowMessage(this);
}
}[/sourcecode]

Note here the static fire method. This is a convenient static factory method that let’s you fire an event without having to manually instantiate a ShowMessageEvent class. Using these methods is recommended rather than calling directly fireEvent. Also, the first parameter of this method is not the event bus itself, but rather the source. Passing in your presenter as the first parameter will make sure that the event is attached to the real source that triggered it. Using HasEventBus rather than GWT’s HasHandlers increases the type safety of GWTP, ensuring you never fire into a widget an event that was supposed to go on the bus.

Now that we have all the scaffolding for the event, it’s time to figure out how to use it. In Gwt-Platform every presenter implements HasEventBus so they all have the ability to fire events. The best practice approach is to simply use the static fire method of your event. In the above example this would be ShowMessageEvent.fire(this, “Hello world!”);. Some situations will require you to fire events from an object that doesn’t have access to fireEvent(). In this case, the best practice is to inject the EventBus, implement HasEventBus, and relay the call to fireEvent:

[sourcecode language=”java”]
public abstract class MyCustomCallback<T> implements AsyncCallback<T>, HasEventBus {
@Inject
private static EventBus eventBus;

@Override
public void onFailure(Throwable caught) {
ShowMessageEvent.fire(this, "Oops! Something went wrong!");
}

@Override
public void fireEvent(GwtEvent<?> event) {
eventBus.fireEvent(this, event);
}
}
[/sourcecode]

In this case we have used static injection to provide the EventBus (don’t forget to requestStaticInjection in your Gin module!). This is because AsyncCallback classes do not typically participate in dependency injection. If your class does participate in dependency injection then you should use constructor injection. The goal of this pattern is to ensure that event sources are correctly tracked. Since the callback implements HasEventBus it will set itself as the source of the event. More importantly, every class that extends this abstract class will be able to fire any event and set itself as the source.

Now, how do we listen to events travelling on the bus? If you’re listening from a presenter, the prefered way is to use addRegisteredHandler(eventType, eventHandler);. This method not only registers a handler on the event bus, it also makes sure that every registered handler is correctly unregistered when the presenter is unbound. If you are not within a presenter, inject the EventBus and call eventBus.addHandler(eventType, eventHandler);. It is customary to use an anonymous inner class as an eventHandler, for example:

[sourcecode language=”java”]
public abstract class MyPresenter extends PresenterImpl<MyPresenter.MyView, MyPresenter.MyProxy> {

@Override
public void onBind() {
super.onBind();
addRegisteredHandler( ShowMessageEvent.getType(), new ShowMessageHandler() {
@Override
void onShowMessage(ShowMessageEvent event) {
getView().displayMessage( event.getMessage() );
}
} );
}
}
[/sourcecode]

But you can also use the following pattern:

[sourcecode language=”java”]
public abstract class MyPresenter extends PresenterImpl<MyPresenter.MyView, MyPresenter.MyProxy>
implements ShowMessageHandler {

@Override
public void onBind() {
super.onBind();
addRegisteredHandler( ShowMessageEvent.getType(), this );
}

@Override
void onShowMessage(ShowMessageEvent event) {
getView().displayMessage( event.getMessage() );
}
}
[/sourcecode]

I hope this post will help you design your own events, but in any case feel free to leave comments or ask questions! In a future article we will discuss how you can automatically generate most of the boilerplate using GWTP’s annotation processing classes contributed by Brendan Doherty. We will also discuss the use of the @ProxyEvent annotation and how it differs from the events described above.

13

ArcBees birth

ArcBees provides consulting and development services to businesses looking to offer quality web applications to their clients.

Our mission is to be the top developers for cloud-based applications, to be active members of the open source community, to deliver quality web apps that goes way beyond the standard fare and to do that using the best practices of our industry. Our goal is to make sure your clients enjoy the best possible web-based experience, and to make it easy for your application to scale with the growing demand.

We will soon open source the development of our own web site. This blog will guide you through every step we take, letting you catch a glimpse of the subtle decisions and technical tricks needed when building a rich web portal.

There’s a lot of features and news coming up in the near future. Stay tuned, we’ll keep you informed !