Wicket Routes Mount

Wicket

At Code-Troopers, we like to work with the frameworks we love. One of them is Apache Wicket, and it happens to some of us doing some Play! Framework or Ruby on Rails (either for a client project, a side project or giving back OSS love).

One thing really great is this two frameworks is the central route system, one file allows to group all the routes handled by your application. Wicket does not provide such way of grouping routes, you can manually mount routes into your application or annotate your page classes.

Wicket routes mount library

This small library project available on Github allows to group mounts into a central file. To use it, simply add its dependency to your pom.xml (artifact is available on Maven central):

<dependency>
    <groupId>com.code-troopers</groupId>
    <artifactId>wicket-route-mount</artifactId>
    <version>0.1</version>
</dependency>


This dependency will transitively gets wicket-auth-roles (if there is a special need for a version without this dependency, it could be done easily).

Usage

To use it, simply create a routes.conf file at the root of the sources in your project (typically src/main/resources/) respecting the following format :

# mountPoint        class                           roles
/home               codetroopers.HomePage           
/secured            codetroopers.SecuredPage        USER
/user/${mode}/#{id} codetroopers.UserPage           ADMIN,USER

The files content is the following :

  • Mount path : using standard Wicket syntax (${requiredParam} and #{optionalParam} are available)
  • Page class : fully qualified name of the page class to mount
  • Roles (optional) : comma separated list of roles required to access the page

IntelliJ IDEA can do completion for class names in this file (you just need to hit the ctrl+space shortcut twice)

Wicket 6 + CDI on Heroku

herokuwicketAs an Apache Wicket user for more than five years I really enjoy its programming model. I recently played with Play Framework 2.1 and Scala and discovered that deploying to Heroku is as easy as a git push. I wondered how difficult it could be using this mechanism to deploy a Wicket application.

Existing attempts

My initial investigation led me to this blog post from Martijn Dashorst explaining how to deploy a Wicket 1.5 application to Heroku, the service has slightly evolved since and the quickstart no longer deploys (Maven repository is no longer available to the run environment).

Adding JPA in the mix

I adapted it to deploy and use Wicket 6 instead of 1.5. And as I am a CDI fan I completed the quickstart with the CDI Wicket module (inspired from this post from Igor Vaynberg) and made the necessary steps to use the heroku bundled PostgreSQL database as a JPA datasource.

The key to make the database works correctly on Heroku resides in the following code snippet, where we parse the provided environment variable to populate hibernate properties.

try {
     URI dbUri = new URI(System.getenv("DATABASE_URL"));
     String username = dbUri.getUserInfo().split(":")[0];
     String password = dbUri.getUserInfo().split(":")[1];
     String dbUrl = "jdbc:postgresql://" + dbUri.getHost() 
                    + ':' + dbUri.getPort() + dbUri.getPath();
     System.setProperty("hibernate.connection.url", dbUrl);
     System.setProperty("hibernate.connection.user", username);
     System.setProperty("hibernate.connection.password", password);
} catch (Exception e) {
     LOGGER.error("Unable to extract database url");
}

Session replication

On Wicket mailing lists, a user recently asked the steps required to get the data store works correctly on Heroku (as the disk space is ephemeral), the key is using a NoSQL backend like Redis. So I wrote a simple and basic implementation of IDataStore using Redis (I think it can be optimized by someone familiar with Redis, pull requests are welcome).

Hands on

The quickstart can be found at the following address and deploys fine on a stack with Redis Cloud and PostgreSQL add ons enabled.
In the end you got :

  • Wicket 6
  • CDI via Weld
  • JPA with PostgreSQL
  • Redis datastore

You can see it live at the following address : http://wicket-6-sample.herokuapp.com/, the app can take a few seconds to start, as Heroku will stop it if it is idling for too long.

Use Wicket templating system to generate Html

html-iconApache Wicket is a great web framework, its clear separation between logic and markup allows to focus on what’s need to be done.

As we use Wicket at SRMvision, we needed to send mails with rather rich templates to our users. The first implementation we used was relying on Wicket to generate these templates using Html. We finally don’t use it (our mailing tasks are done by a background job, thus we don’t have access to our webapp), but I though the code used in our fast proof of concept could help someone else.

import org.apache.wicket.markup.MarkupType;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.Response;
import org.apache.wicket.response.StringResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Simple panel allowing to use the templating engine 
 *    provided by Wicket to generate HTML.
 * Typical use would be to generate mail content.
 *
 * User of this class will need to subclass it 
 *    and create a panel as usual. 
 * Then a call to getHtml() will return the generated Html.
 *
 * @author cedric at gatay.fr
 */
public class HtmlTemplaterPanel extends Panel {
    private static final Logger LOGGER = 
        LoggerFactory.getLogger(HtmlTemplaterPanel.class);

    /**
     * Default constructor takes no wicket:id > 
     *   the panel will not be added to any component
     */
    public HtmlTemplaterPanel(){
        super("dummy");
    }

    /**
     * Call this whenever you want to get
     *   the Html for this component
     * @return Html or empty string
     */
    public String getHtml(){
        final Response origResponse = getRequestCycle().getResponse();
        try{
            final StringResponse stringResponse = new StringResponse();
            getRequestCycle().setResponse(stringResponse);
            renderAssociatedMarkup("panel", "");
            return stringResponse.toString();
        }catch(Exception e){
            LOGGER.error("Unable to build HTML for panel : {}",
                         e.getMessage());
        }finally{
            getRequestCycle().setResponse(origResponse);
        }
        return "";
    }

    @Override
    protected boolean getStatelessHint() {
        return true;
    }

    @Override
    public MarkupType getMarkupType() {
        return MarkupType.HTML_MARKUP_TYPE;
    }
}

If you want to generate a template using Apache Wicket, you only need to create a Panel and its associated markup which inherits this simple class. Then, when you want to get the Html for your component, call getHtml().

The only drawback of this is that you need a RequestCycle to generate the markup (you’ll find out why reading the code).

Wicket Chrome to IDEA

It is not a secret that the SRMvision platform is developped using the Apache Wicket framework.

As our application became bigger and so our team, it’s getting harder to find the correct Wicket class beneath the view of the page we get in our browsers.

To help the team in this process, I made a simple Chrome extension and a IntelliJ IDEA plugin allowing to send class names to the IDE from the web browser (at the cost of a very simple class in your project, disabled in deployment mode).

Getting your project ready

In the chrome-wicket-idea-example github repository, you have a very simple example of what needs to be done to enable navigation between your browser and your project opened in your IDE. Have a look at the WicketApplication class (specifically in the the init() method) and at the DebugComponentBeforeRenderListener class (it is where the ‘simple’ magic happen). The good thing is you only need to use this class in your project (confirmed working with Wicket 1.4, 1.5, and 6), and to mimic the initializer logic to get started.

Please notice that you can specify which classes you want to track in your markup (by restricting on package names) at the listener’s instanciation.
To test the sample project, you can run the embedded jetty server by running :

mvn jetty:run

Wicket Open In IDEA

IDEA part

The IntelliJ plugin listens for classnames to open on a http socket (10462, overridable in plugin settings).

Plugin settings

You can get the IDEA plugin in its github repository, to install it, you have to select “Install plugin from disk” from the “Plugins” category in your IDE settings.

Chrome part

The Chrome extension is really simple, like my TrelloScrum fork, it is not (yet) available on the Chrome Web Store, thus, you have to download the release here and drag and drop it on your chrome://extensions page.
If you want, you can tweak its settings, via the “Options” page :

  • IDE Host : if you change the setup of the plugin in your IDE (or run your IDE on another machine than your browser), you might need to change the host and port to reflect this.
  • Context menu presence host : if you want the context menu icon to appear only on sites where it should, you can narrow the domains here.

To use it, you only have to right click on an item in your “enhanced” web application and select “Wicket debug this”.

Context menu item

From there you’ll get a modal window listing the matching classes names (sorted by parent order, the first is the closer to the element you pointed to, the next one is the parent class and so on). If there is not any opened modal when you try to use it, it means the extension did not detect any classname in the markup.

Class modal selection

Each classname, when clicked, is sent to your IDE which will in turn opens the class matching the classname so you can edit it.
The lower part of the modal window will inform you about the status of your last action :

  • If the plugin is not enabled, or the IDE not running : it will display an error message
  • If all went like expected : it will display a confirmation message

I hope it will help other teams using this great framework, or it will give ideas to user of others frameworks.

IntelliJ + External Library + @PropertyKey How To

I am a daily user of IntelliJ IDEA to edit my Java code and Apache Wicket to write my web application. I decided recently to use IntelliJ’s annotations to make my code a little more robust by using @Nullable, @NotNull, @NonNls and @PropertyKey.
In this blog post I explain how to manually add annotation to an external library.
Continue reading