Karthik's Weblog

Developing a custom Apache Wicket component

Posted in Wicket by karthik on January 24, 2008

Introduction

This article walks the reader through the process of building a custom component using Apache Wicket framework. As the first step, let’s discuss the functionality that we will be packaging with our custom component. An ‘Accordion’ is not pre-packaged as a Wicket core/extensions component the way Oracle ADF Faces does for example.If you want to take a look at a demo of an Accordion, Rico has one here. This component is known by different names on the web. We will call it a TogglePane. There are probably several ways to buid one. We will look at one such approach that employs a popular javascript library scriptaculous that in turn is built on top of another gem – prototype. If you are looking for a thorough discussion on prototype, read the excellent book Prototype and Scriptaculous in Action

Through this example, readers will learn how to –

  1. Integrate an existing popular javascript framework with Wicket
  2. Make header contributions from your custom component
  3. Ajax-enable your custom component and
  4. In general, get an insight into how components are typically
    modelled on the server or wicket-side.

A custom Wicket component that has a visual representation typically ship with the following artifacts:

  1. An HTML template
  2. Optional Javascript or stylesheet or Images
  3. A corresponding java component class that extends from one of the
    several component base classes that ship with the standard Wicket
    distribution.

Note : Wicket does not mandate having an HTML template or javascript
file or stylesheet for a custom component. Custom validators, converters are examples of
components that do not have a corresponding markup. You could also reuse an existing
component’s markup and customize its behavior by extending the corresponding Java
class. The existing component should provide for extension-hooks though. Standard
wicket/wicket-extensions distribution ship with several components that allow for
customization. Now that we have some idea of what we want to build, let’s design the
HTML markup.

The Template

Here is the barebone layout for the TogglePane Component:

File:TogglePane.html


  <html>
  <body>

    <div class="pane_border">
      <div class="pane">
        <div class="pane_header">
          <span>[[Header goes here]]</span>
        </div>
        <div class="pane_content">
          <span>[[Content goes here]]</span>
        </div>
      </div>
    </div>

  </body>
  </html>

– Just a bunch of divs that can be made to look prettier by adding a little bit of CSS style later.

Adding Client-side behavior to the Template

Next, let’s take a look at the javascript that adds the scriptaculous ‘toggle’ effect.

//File: toggle.js


  var TogglePane = Class.create();

  TogglePane.prototype = {

    //constructor as expected by the prototype library

    initialize:function(divId){

      //get all elements under div with id 'divId' having style .pane'
      var searchString = 'div#'+divId+' .pane';
      this.panes = $A($$(searchString));

      this._initClientOnlyToggle();
    },

    //Initiate the toggle effect
    //when the 'header' is clicked, the content needs
    //to toggle

    _initClientOnlyToggle:function(){
      var obj = this;

      //For every pane, get the 'content' to toggle
      //'onclick' of 'header'

      this.panes.each(
        function(pane){
            var header = obj._getContainedElement(pane,'pane_header');
            var content = obj._getContainedElement
                                  (pane,'pane_content');
            header.onclick = function(){
              Effect.toggle(content);
            };
        }
     );
    } ,

    //A Helper function
    //fetch an element with class 'className' and is
    //a child of 'pane' element

    _getContainedElement:function(pane,className){
      var elem = $A(pane.childNodes).find(
          function(child){
            return child.className == className;
          }
      );
      return elem;
    },

  }

Add some style to the template

Now that we have the client-side behavior ready, lets add a
stylesheet to the template ( I know that the majority of the readers
will probably do a far better job at this):

File: toggle.css


  .pane_border {
      position: relative;
      width: 300px;
      padding: 0px;
      background-color:  #508acd;
      border: 2px ;
      text-align: left;
   }

  .pane_header {
      border: 1px #ffffff outset;
      background-color: #2b5286;
      padding: 1px 50px 1px 50px;
      font-size: 0.7em;
      color:#FFFFFF;
      font-family:'Trebuchet MS';
      font-weight:bold;
   }

  .pane_content {
      border: 1px #ffffff outset;
      padding:10px 10px 10px 10px;
      background-color: #508acd;
      color:#FFFFFF;
      font-family:Verdana, Arial, Helvetica, sans-serif;
      font-size:10px;
      font-weight:bold;
   }

Let’s add some ‘previewable’ HTML content to the markup and see how it would look like in the real-world.

Adding Previewable Content to the template

//File: TogglePane.html


	<html>

      <!-- Add references to the javascript lib-->

      <head>
        <script type="text/javascript" src="prototype.js"></script>
        <script type="text/javascript" src="scriptaculous.js"></script>
        <script type="text/javascript" src="effects.js"></script>
        <script type="text/javascript" src="toggle.js"></script>
        <link rel="stylesheet" type="text/css" href="toggle.css"/>
      </head>

      <!-- Initialize the toggle effect on 'onload' event -->

      <body onload="new TogglePane('togglepane_id')">

        <div id="togglepane_id" class="pane_border">

          <!-- template content -->

          <div class="pane">
            <div class="pane_header">
              <span>[[Header goes here]]</span>
            </div>
            <div class="pane_content">
              <span>[[Content goes here]]</span>
            </div>
          </div>

          <!-- Dummy content-1 -->

          <div class="pane">
            <div class="pane_header">
              <span><b>User Details</b></span>
            </div>
            <div class="pane_content">
              <div>
                  <table>
                    <tr><td>Login Id</td><td><input type="text" value=""/></td></tr>
                    <tr><td>First Name</td><td><input type="text" value=""/></td></tr>
                    <tr><td>Last Name</td><td><input type="text" value=""/></td></tr>
                    <tr><td><input type="button" value="Save"/></td></tr>
                  </table>
              </div>
            </div>
          </div>

          <!-- Dummy content-2 -->

          <div class="pane">
            <div class="pane_header">
              <span><b>Address</b></span>
            </div>
            <div class="pane_content">
              <div>
                  <table>
                    <tr><td>Addr1</td><td><input type="text" value="Addr1"/></td></tr>
                    <tr><td>Addr2</td><td><input type="text" value=""/></td></tr>
                    <tr><td>City</td><td><input type="text" value="Dallas"/></td></tr>
                    <tr><td><input type="button" value="Save"/></td></tr>
                  </table>
              </div>
            </div>
          </div>

        </div>
      </body>
    </html>

Here is a sample screenshot –

Accordian

What we have at this stage is a working prototype. We are probably half way through the article and interestingly, we still haven’t discussed Wicket or fired up our Java ide yet. That’s pretty much “Wicket way” of developing web components : Develop the plain HTML UI mock-ups without bothering about the wicket-side side of the component and once you have something working, sprinkle a few wicket tags at appropriate places in the template and add “dynamic” “behavior” in the backing Java classes.

Next, lets see what it takes to convert this HTML/Javascript/CSS to a server-side Wicket component that can eventually be dropped into a Page or nested within other components that make up a page

Getting the component Wicket-ready

In Wicket, the HTML artifacts and the server-side representation of a component (a Java class) typically reside in the same package. So create a package – org.wicketstuff.funwithcomponents and copy the HTML artifacts (css, js e.t.c) under the package. Let’s add wicket:id and some minimal wicket tags to the dynamic sections of the template. This is how the template looks like now:


  <html>

     <wicket:head>
        <wicket:link>
           <script src="prototype.js" type="text/javascript"></script>
           <script src="scriptaculous.js" type="text/javascript">
           </script>
           <script src="effects.js" type="text/javascript"></script>
           <script src="toggle.js" type="text/javascript"></script>
           <link rel="stylesheet" href="toggle.css" type="text/css">
           </link>
         </wicket:link>
     </wicket:head>

     <body>

        <wicket:panel>

            <div wicket:id="outerDiv" class="pane_border">

                <div class="pane" wicket:id="panes">
                  <div class="pane_header">
                    <span wicket:id="header">[[Header]]</span>
                  </div>
                  <div class="pane_content">
                    <span wicket:id="content">[[Content]]</span>
                  </div>
                </div>

                <!--
                  Dummy content excluded for the same of brievity.
                  Feel free to copy the contents here
                 -->

            </div>

        </wicket:panel>

      </body>
    </html>

The table below summarize the wicket tags and wicket:id’s that we added to the template



  wicket:id     Purpose
  ----------   ----------
  outerDiv   |   We need to generate a unique HTML 'id' attribute for
                 this div and access it in our JS
  panes      |   We need to attach a repeater on the Wicket-side
                 corresponding to this element
  header     |   Place holder for the 'header' element
  content    |   Place holder for the 'content' element

  Wicket tags       Tag description
  -------------    -----------------
  <wicket:head>  |  Used by the component to 'contribute' header
                    artifacts
  <wicket:link>  |  Used to provide auto-linking to the artifacts
  <wicket:panel> |  To indicate that the component is essentially a
                    'Panel' that can be dropped on to a page or in
                    fact nested within our panels

Remember to remove the reference to the stylesheet ‘toggle.css’ from
within the component template : the users of the component typically
customize the look and feel of the component

Now on to the Java side of the Component

Just to reiterate, in Wicket, you typically employ HTML and/or CSS to specify the visual layout of a component while the dynamic behavior is added to the server-side representation of the Component.

The TogglePane is essentially composed of a set of ‘panes’ and every ‘pane’ consists of a ‘header’ and ‘content’ component. The ‘header’ could be simple text ( represented as a Label component in Wicket). It could also be a Link for e.g. Now that we are not sure what the ‘header’ / ‘content’ Component is likely to be, let’s represent it in a generic fashion as an org.apache.wicket.Component instance.


    package org.wicketstuff.funwithcomponents;
    import org.apache.wicket.Component;

    public interface Pane extends Serializable{
       public Component getHeader(String headerWicketId);
       public Component getContent(String contentWicketId);
    }

The fact that we are passing the ‘wicketid’ to the implementations of the Pane interface might seem a little strange to Wicket beginners at first. The client of the toggle component could probably look up the Toggle pane template and figure the wicket:id. But that would amount to leaking the implementation details of the Toggle Pane. The header and content wicket:id is internal to the component and should remain that way. So what we do instead is pass the wicket id to the ‘clients’ of the component. The TogglePane is composed of a collection of panes –


  package org.wicketstuff.funwithcomponents;

  import java.util.List;

  import org.apache.wicket.markup.html.IHeaderContributor;
  import org.apache.wicket.markup.html.IHeaderResponse;
  import org.apache.wicket.markup.html.WebMarkupContainer;
  import org.apache.wicket.markup.html.list.ListItem;
  import org.apache.wicket.markup.html.list.ListView;
  import org.apache.wicket.markup.html.panel.Panel;

  public class TogglePane extends Panel implements IHeaderContributor {

    private WebMarkupContainer outerDiv;

    public TogglePane(String id, List panes) {
      super(id);

      outerDiv = new WebMarkupContainer("outerDiv");
      //make sure that it emits 'id' attribute
      outerDiv.setOutputMarkupId(true);

      outerDiv.add(new Panes("panes", panes));
      add(outerDiv);
    }

    //ListView is a repeater component that allows you
    //to render the markup in a loop.

    class Panes extends ListView {

      public Panes(String id, List list) {
        super(id, list);
        // TODO Auto-generated constructor stub
      }

      @Override
      protected void populateItem(final ListItem item) {
        Pane pane = (Pane) item.getModelObject();
        item.add(pane.getHeader("header"));
        item.add(pane.getContent("content"));
      }

    }

    public void renderHead(IHeaderResponse response) {
        response.renderOnLoadJavascript("new TogglePane('"
            + outerDiv.getMarkupId() + "')");
    }
  }

The javascript class that we wrote requires the ‘outerDiv’ HTML ‘id’ as an initialization parameter – you do that by implementing wicket’s IHeaderContributor interface – it allows you to make header contributions at runtime – in our case, the div HTML ‘id’ is not known until render time.
Note that you still get to keep the ‘pane’-s that you added for the sake of previewability in the TogglePane template. Just make sure that you place them within tags as shown below –


  <wicket:remove>
      [[your dummy 'pane'-s goes here]]
  </wicket:remove>

Wicket ignores the content placed within tags when rendering.
That’s it – a functioning Wicket-Accordian is ready to be put to use. But this still doesn’t sound too exciting in the sense that the component is pretty much static – it just toggles the content that exists at the time of page render. Sometimes, you might want the ability to refresh the content from the server every time the header is clicked. Still better, you might want to repaint the content asynchronously through Ajax. We can also let the user decide if he/she would like to see the content panes initially expanded or collapsed. In the next section, we will see how we can make this behavior configurable at the Component level.

Adding ability to “configure” the Accordian

In Wicket, they are usually modelled through a Config class as shown below.


  package org.wicketstuff.funwithcomponents;

  import java.io.Serializable;

  public class Config implements Serializable {

    boolean panesCollapsedIntially;

    boolean withAjaxEnabled;

    public Config() {}

    public Config panesCollapsedIntially() {
      this.panesCollapsedIntially = true;
      return this;
    }

    public Config withAjaxEnabled() {
      this.withAjaxEnabled = true;
      return this;
    }

    public Config panesExplodedInitially() {
      this.panesCollapsedIntially = false;
      return this;
    }

    public Config withAjaxDisabled() {
      this.withAjaxEnabled = false;
      return this;
    }

    public boolean isAjaxEnabled(){
      return withAjaxEnabled;
    }

    public boolean arePanesCollapsedInitially(){
      return panesCollapsedIntially;
    }

  }

You can specify the Configuration at the time of construction of the TogglePane as shown below:

//MyPage is a Page that uses the TogglePane component


  import java.util.Collections;
  import java.util.List;

  import org.apache.wicket.markup.html.WebPage;

  public class MyPage extends WebPage {
    public MyPage() {
      add(new TogglePane("pane", createPanes(),
        new Config()
          .withAjaxDisabled()
            .panesCollapsedIntially()));
    }
    //snip

    public List createPanes(){
      // TODO return your panes from here
      return Collections.EMPTY_LIST;
    }
  }

//File:MyPage.html


  <html>
    <body>
      <span wicket:id="pane">[[Our Accordian will be placed here]]</span>
    </body>
  </html>

The template now requires the ‘header’ to be marked as a Wicket component as well (wicket:id=”h” – we need to be firing an Ajax request ‘onclick’ of the header)


  <wicket:panel>

    <div wicket:id="outerDiv" class="pane_border">
	  <div class="pane" wicket:id="panes">

		<! -- header identified as a wicket Component -->
		<div class="pane_header" wicket:id="h">
		    <span wicket:id="header">[[Header]]</span>
		</div>
		<div class="pane_content">
		    <span wicket:id="content">[[Content]]</span>
		</div>
	</div>
     </div>

  </wicket:panel>

Let’s add the Ajax behavior to the component next.


  public class TogglePane extends Panel implements IHeaderContributor {

    private WebMarkupContainer outerDiv;

    private Config config;

    public TogglePane(String id, List panes, Config config) {
      super(id);
      this.config = config;
      outerDiv = new WebMarkupContainer("outerDiv");
      outerDiv.setOutputMarkupId(true);

      outerDiv.add(new Panes("panes", panes));
      add(outerDiv);
    }

    class Panes extends ListView {

      public Panes(String id, List list) {
        super(id, list);
      }

      @Override
      protected void populateItem(final ListItem item) {
        final Pane pane = (Pane) item.getModelObject();
        WebMarkupContainer h = new WebMarkupContainer("h");

        //The component with wicket id 'content' needs to be added to
        //the one with wicket:id 'h' and not 'item' - Wicket expects us to
        //respect the component hierachy

        h.add(pane.getHeader("header"));

        //If Ajax, attach Ajax behavior to the 'onclick' event

        if (config.isAjaxEnabled()) {
          h.add(new AjaxEventBehavior("onclick") {

            @Override
            protected void onEvent(AjaxRequestTarget target) {

              Component newContent = pane.getContent("content");
              newContent.setOutputMarkupId(true);
              item.replace(newContent);
              target.addComponent(newContent);

            }

          });
        }
        item.add(h);
        Component content = pane.getContent("content")
        content.setOutputMarkupId(true);
        item.add(content);
      }

    }

    //Configure the togglepane.js based on the Config
    //object supplied by the user. We will modify the client-side
    //javascript to support this configuration in the next
    //section.

    public void renderHead(IHeaderResponse response) {
      String outerDivId = outerDiv.getMarkupId();
      StringBuilder jsTogglePane = new StringBuilder("new TogglePane('"
          + outerDivId + "',");

      if (config.isAjaxEnabled()) {
        jsTogglePane.append("true,");
      } else {
        jsTogglePane.append("false,");
      }
      if (config.arePanesCollapsedIntially()) {
        jsTogglePane.append("true)");
      } else {
        jsTogglePane.append("false)");
      }

      response.renderOnLoadJavascript(jsTogglePane.toString());

    }
  }

As promised earlier, let’s modify the initial version of our JavaScript class definition in order to support these configuration options.

Modify the client-side Javascript to support the configuration of component behaviour

If you are a Wicket beginner, you probably noticed that you didn’t have to write any javascript to trigger the Ajax request – Wicket enables this by computing the URL required to trigger the Ajax behavior and attaches it to the ‘onclick’ event of the header element transparently (you can click ‘view source’ on your browser’s menu and verify that the rendered HTML indeed ). But remember, we also need to attach the scriptaculous ‘toggle’ behavior on the ‘onclick’ event? Now the question is how do we combine both the ‘toggle’ and ‘wicket-introduced-ajax’ behavior? We also need to make sure that the Ajax request isn’t fired when the user collapses the header as this could be viewed as being inefficient.

The code snippet shown below addresses these issues:



   TogglePane.prototype = {

      //modified constructor to support configuration

      initialize:function(divId,enableAjax,collapsePanes){

        this.divId = divId;
        //get all elements under div with id 'divId' having style
        //'.pane'
        var searchString = 'div#'+divId+' .pane';
        this.panes = $A($$(searchString));

        if(enableAjax == true){
          this._initAjaxToggle();
        }else{

          //_initClientOnlyToggle() is same as what we discussed at the
          //beginning of the article

          this._initClientOnlyToggle();
        }

        if(collapsePanes == true){
          //get all child elements of div with id 'divId'
          //having style .pane_content
          searchString = 'div#'+divId+' .pane_content';
          this.contents = $A($$(searchString));
          this._collapseContent();
        }
      },

     //A new helper method that initialized the Ajax behavior

     _initAjaxToggle:function(){
        var obj = this;
        this.panes.each(
            function(pane){

              var header = obj._getContainedElement
                       (pane,'pane_header');
              var content = obj._getContainedElement
                       (pane,'pane_content');

              //wicket-introduced 'onclick' handler that triggers the
              //ajax request

              var existingCall = header.onclick;

              header.onclick = function(){

                Effect.toggle(content);

                //Conditionally invoke the Ajax request
                //based on the current visibility of the 'content'

                if (! $(content).visible() ){
                  existingCall();
                }

              };

           }
        );
      },

      //A new helper method that 'collapses' the panes initially if
      //configured

      _collapseContent:function(){
       this.contents.each(
        function(content){
            content.hide();
        }
       );
      }
   }

Getting our Accordion to behave like Rico’s Accordion

The Accordion component that we developed differs from Rico’s equivalent in the following ways:

  1. Our component allows “all” content panes to show up expanded
    initally.
  2. When the currently ‘active’ content pane is expanded, others
    don’t collapse automatically.

“1” can be addressed by simply ‘hardcoding’ the configuration and showing all the panes collapsed initially. “2” can be addressed by adding a simple method to the client side javascript that allows you to collapse all content panes except the one that is currently ‘active’ (the one that the user clicks)



  TogglePane.prototype = {

    //A new helper method that 'collapses' all panes except the one
    //that is passed as an argument to the method

    _collapseAllContentExcept:function(ignore){
      //get all child elements of div with id 'divId' having
      //style .pane_content
      searchString = 'div#'+this.divId+' .pane_content';
      this.contents = $A($$(searchString));
      this.contents.each(
        function(content){
           if( content != ignore){
            content.hide();
           }
        }
      );
    }

  }

Make sure that you call the _collapseAllContentExcept method from within the onclick handler as depicted below:


    header.onclick = function(){

       Effect.toggle(content);
       //Conditionally invoke the Ajax request
       //based on the current visibility of the 'content'

       if (! $(content).visible() ){
         existingCall();
         //collapse all other content panes except
         //the current one
         this._collapseAllContentExcept(content);
       }

    };

Conclusion:

Component based web frameworks are gaining a lot of traction in the Java World. Apache Wicket is one of the leading implementations in this area. But many development teams are still faced with the problem of picking a web framework given the plethora of open source options available in the java world. My observation has been that development teams, while zeroing in on a component based framework, typically tend to cite the built-in component library as one of the major criteria for choosing one. Wicket ships with quite a few built-in components. If you find that a Component, a competing framework ships with, doesn’t already exist in “standard” Wicket distribution , look it up in the component wiki – may be someone has already built it for you or better, subscribe to the mailing list. The possiblity of getting the question answered on the mailing-list within a couple of minutes or worse, within an hour is very high. But if you still fail to find a convincing reply, its not the end of the road. On the contrary, its probably the beginning of a fun-filled web development journey – you can feel assured that the Wicket framework developers have more than made up for the absence of the custom component you are looking for by providing a Component/programming model that makes developing custom components a breeze. It is also important to note that every project has its own unique requirement and very few components are designed with that kind of flexibility in mind.

On a side-note, “the ease of component development” is also the primary reason why Apache Wicket committers refrain from shipping all possible custom components with the standard distribution.