18. Wicket advanced topics

In this chapter we will learn some advanced topics which have not been covered yet in the previous chapters but which are nonetheless essential to make the most of Wicket and to build sophisticated web applications.

18.1. Enriching components with behaviors

With class org.apache.wicket.behavior.Behavior Wicket provides a very flexible mechanism to share common features across different components and to enrich existing components with further functionalities. As the class name suggests, Behavior adds a generic behavior to a component modifying its markup and/or contributing to the header section of the page (Behavior implements the interface IHeaderContributor).

One or more behaviors can be added to a component with Component‘s method add(Behavior…​), while to remove a behavior we must use method remove(Behavior).

Here is a partial list of methods defined inside class Behavior along with a brief description of what they do:

  • beforeRender(Component component): called when a component is about to be rendered.

  • afterRender(Component component): called after a component has been rendered.

  • onComponentTag(Component component, ComponentTag tag): called when component tag is being rendered.

  • getStatelessHint(Component component): returns if a behavior is stateless or not.

  • bind(Component component): called after a behavior has been added to a component.

  • unbind(Component component): called when a behavior has been removed from a component.

  • detach(Component component): overriding this method a behavior can detach its state before being serialized.

  • isEnabled(Component component): tells if the current behavior is enabled for a given component. When a behavior is disabled it will be simply ignored and not executed.

  • isTemporary(Component component): tells component if the current behavior is temporary. A temporary behavior is discarded at the end of the current request (i.e it’s executed only once).

  • onConfigure(Component component): called right after the owner component has been configured.

  • onRemove(Component component): called when the owner component has been removed from its container.

  • renderHead(Component component, IHeaderResponse response): overriding this method behaviors can render resources to the header section of the page.

For example the following behavior prepends a red asterisk to the tag of a form component if this one is required:

  1. public class RedAsteriskBehavior extends Behavior {
  2. @Override
  3. public void beforeRender(Component component) {
  4. Response response = component.getResponse();
  5. StringBuffer asterisktHtml = new StringBuffer(200);
  6. if(component instanceof FormComponent
  7. && ((FormComponent)component).isRequired()){
  8. asteriskHtml.append(" <b style=\"color:red;font-size:medium\">*</b>");
  9. }
  10. response.write(asteriskHtml);
  11. }
  12. }

Since method beforeRender is called before the coupled component is rendered, we can use it to prepend custom markup to component tag. This can be done writing our markup directly to the current Response object, as we did in the example above.

Please note that we could achieve the same result overriding component method onBeforeRender. However using a behavior we can easily reuse our custom code with any other kind of component without modifying its source code. As general best practice we should always consider to implement a new functionality using a behavior if it can be shared among different kinds of component.

Behaviors play also a strategic role in the built-in AJAX support provided by Wicket, as we will see in the next chapter.

18.2. Generating callback URLs with IRequestListener

With Wicket it’s quite easy to build a callback URL that is handled on server side by a component or a behavior. What we have to do is to implement interface org.apache.wicket.IRequestListener:

  1. public interface IRequestListener extends IClusterable
  2. {
  3. /**
  4. * Does invocation of this listener render the page.
  5. *
  6. * @return default {@code true}, i.e. a {@link RenderPageRequestHandler} is schedules after invocation
  7. */
  8. default boolean rendersPage()
  9. {
  10. return true;
  11. }
  12. /**
  13. * Called when a request is received.
  14. */
  15. void onRequest();
  16. }

Method onRequest is the handler that is executed to process the callback URL while rendersPage tells if the whole page should be re-rendered after onRequest has been executed (if we have a non-AJAX request).

An example of a component that implements IRequestListener can be seen in the Wicket standard link component. Here is an excerpt from its code:

  1. public abstract class Link<T> extends AbstractLink implements IRequestListener ...
  2. {
  3. /**
  4. * Called when a link is clicked.
  5. */
  6. public abstract void onClick();
  7. /**
  8. * THIS METHOD IS NOT PART OF THE WICKET API. DO NOT ATTEMPT TO OVERRIDE OR CALL IT.
  9. *
  10. * Called when a link is clicked. The implementation of this method is currently to simply call
  11. * onClick(), but this may be augmented in the future.
  12. */
  13. @Override
  14. public void onRequest()
  15. {
  16. // Invoke subclass handler
  17. onClick();
  18. }
  19. }

Callback URLs can be generated with Component‘s method urlForListener(PageParameters) or with method urlForListener(Behavior, PageParameters) if we are using a request listener on a component or behavior respectively (see the following example).

Project CallbackURLExample contains a behavior (class OnChangeSingleChoiceBehavior) that implements org.apache.wicket.IRequestListener to update the model of an AbstractSingleSelectChoice component when user changes the selected option (it provides the same functionality as FormComponentUpdatingBehavior). The following is the implementation of onRequest() provided by OnSelectionChangedNotifications:

  1. @Override
  2. public void onRequest() {
  3. Request request = RequestCycle.get().getRequest();
  4. IRequestParameters requestParameters = request.getRequestParameters();
  5. StringValue choiceId = requestParameters.getParameterValue("choiceId");
  6. //boundComponent is the component that the behavior it is bound to.
  7. boundComponent.setDefaultModelObject( convertChoiceIdToChoice(choiceId.toString()));
  8. }

When invoked via URL, the behavior expects to find a request parameter (choiceId) containing the id of the selected choice. This value is used to obtain the corresponding choice object that must be used to set the model of the component that the behavior is bound to (boundComponent). Method convertChoiceIdToChoice is in charge of retrieving the choice object given its id and it has been copied from class AbstractSingleSelectChoice.

Another interesting part of OnChangeSingleChoiceBehavior is its method onComponentTag where some JavaScript “magic” is used to move user’s browser to the callback URL when event “change” occurs on bound component:

  1. @Override
  2. public void onComponentTag(Component component, ComponentTag tag) {
  3. super.onComponentTag(component, tag);
  4. CharSequence callBackURL = getCallbackUrl();
  5. String separatorChar = (callBackURL.toString().indexOf('?') > -1 ? "&" : "?");
  6. String finalScript = "var isSelect = $(this).is('select');\n" +
  7. "var component;\n" +
  8. "if(isSelect)\n" +
  9. " component = $(this);\n" +
  10. "else \n" +
  11. " component = $(this).find('input:radio:checked');\n" +
  12. "window.location.href='" + callBackURL + separatorChar +
  13. "choiceId=' + " + "component.val()";
  14. tag.put("onchange", finalScript);
  15. }

The goal of onComponentTag is to build an onchange handler that forces user’s browser to move to the callback URL (modifing standard property window.location.href). Please note that we have appended the expected parameter (choiceId) to the URL retrieving its value with a JQuery selector suited for the current type of component (a drop-down menu or a radio group). Since we are using JQuery in our JavaScript code, the behavior comes also with method renderHead that adds the bundled JQuery library to the current page.

Method getCallbackUrl() is used to generate the callback URL for our custom behavior:

  1. public CharSequence getCallbackUrl() {
  2. if (boundComponent == null) {
  3. throw new IllegalArgumentException(
  4. "Behavior must be bound to a component to create the URL");
  5. }
  6. return boundComponent.urlForListener(this, new PageParameters());
  7. }

The home page of project CallbackURLExample contains a DropDownChoice and a RadioChoice which use our custom behavior. There are also two labels to display the content of the models of the two components:

CallbackURLExample screenshot

Implementing interface IRequestListener makes a behavior stateful because its callback URL is specific for a given instance of component.

18.3. Wicket events infrastructure

Starting from version 1.5 Wicket offers an event-based infrastructure for inter-component communication. The infrastructure is based on two simple interfaces (both in package org.apache.wicket.event) : IEventSource and IEventSink.

The first interface must be implemented by those entities that want to broadcast en event while the second interface must be implemented by those entities that want to receive a broadcast event.

The following entities already implement both these two interfaces (i.e. they can be either sender or receiver): Component, Session, RequestCycle and Application. IEventSource exposes a single method named send which takes in input three parameters:

  • sink: an implementation of IEventSink that will be the receiver of the event.

  • broadcast: a Broadcast enum which defines the broadcast method used to dispatch the event to the sink and to other entities such as sink children, sink containers, session object, application object and the current request cycle. It has four possible values:

Value

Description

BREADTH

The event is sent first to the specified sink and then to all its children components following a breadth-first order.

DEPTH

The event is sent to the specified sink only after it has been dispatched to all its children components following a depth-first order.

BUBBLE

The event is sent first to the specified sink and then to its parent containers.

EXACT

The event is sent only to the specified sink.

  • payload: a generic object representing the data sent with the event.

Each broadcast mode has its own traversal order for Session, RequestCycle and Application. See JavaDoc of class Broadcast for further details about this order.

Interface IEventSink exposes callback method onEvent(IEvent<?> event) which is triggered when a sink receives an event. The interface IEvent represents the received event and provides getter methods to retrieve the event broadcast type, the source of the event and its payload. Typically the received event is used checking the type of its payload object:

  1. @Override
  2. public void onEvent(IEvent event) {
  3. //if the type of payload is MyPayloadClass perform some actions
  4. if(event.getPayload() instanceof MyPayloadClass) {
  5. //execute some business code.
  6. }else{
  7. //other business code
  8. }
  9. }

Project InterComponetsEventsExample provides a concrete example of sending an event to a component (named ‘container in the middle’) using all the available broadcast methods:

InterComponentsEventsExample screenshot

18.4. Initializers

Some components or resources may need to be configured before being used in our applications. While so far we used Application’s init method to initialize these kinds of entities, Wicket offers a more flexible and modular way to configure our classes.

During application’s bootstrap Wicket searches for any properties file placed in one of the ‘/META-INF/wicket/‘ folder visible to the application classpath. When one of these files is found, the initializer defined inside it will be executed. An initializer is an implementation of interface org.apache.wicket.IInitializer and is defined inside a properties with a line like this:

  1. initializer=org.wicketTutorial.MyInitializer

The fully qualified class name corresponds to the initializer that must be executed. Interface IInitializer defines method init(Application) which should contain our initialization code, and method destroy(Application) which is invoked when application is terminated:

  1. public class MyInitializer implements IInitializer{
  2. public void init(Application application) {
  3. //initialization code
  4. }
  5. public void destroy(Application application) {
  6. //code to execute when application is terminated
  7. }
  8. }

Only one initializer can be defined in a single properties file. To overcome this limit we can create a main initializer that in turn executes every initializer we need:

  1. public class MainInitializer implements IInitializer{
  2. public void init(Application application) {
  3. new AnotherInitializer().init(application);
  4. new YetAnotherInitializer().init(application);
  5. //...
  6. }
  7. //destroy...
  8. }

18.5. Using JMX with Wicket

JMX (Java Management Extensions) is the standard technology adopted in Java for managing and monitoring running applications or Java Virtual Machines. Wicket offers support for JMX through module wicket-jmx. In this paragraph we will see how we can connect to a Wicket application using JMX. In our example we will use JConsole as JMX client. This program is bundled with Java SE since version 5 and we can run it typing jconsole in our OS shell.

Once JConsole has started it will ask us to establish a new connection to a Java process, choosing between a local process or a remote one. In the following picture we have selected the process corresponding to the local instance of Jetty server we used to run one of our example projects:

JMX new connection

After we have established a JMX connection, JConsole will show us the following set of tabs:

JMX console

JMX exposes application-specific informations using special objects called MBeans (Manageable Beans), hence if we want to control our application we must open the corresponding tab. The MBeans containing the application’s informations is named org.apache.wicket.app..

In our example we have used wicket.test as filter name for our application:

JMX console2

As we can see in the picture above, every MBean exposes a node containing its attributes and another node showing the possible operations that can be performed on the object. In the case of a Wicket application the available operations are clearMarkupCache and clearLocalizerCache:

JMX console3

With these two operations we can force Wicket to clear the internal caches used to load components markup and resource bundles. This can be particularly useful if we have our application running in DEPLOYMENT mode and we want to publish minor fixes for markup or bundle files (like spelling or typo corrections) without restarting the entire application. Without cleaning these two caches Wicket would continue to use cached values ignoring any change made to markup or bundle files.

Some of the exposed properties are editable, hence we can tune their values while the application is running. For example if we look at the properties of ApplicationSettings we can set the maximum size allowed for an upload modifying the attribute DefaultMaximumUploadSize:

JMX console4

18.6. Generating HTML markup from code

So far, as markup source for our pages/panels we have used a static markup file, no matter if it was inherited or directly associated to the component. Now we want to investigate a more complex use case where we want to dynamical generate the markup directly inside component code.

To become a markup producer, a component must simply implement interface org.apache.wicket.markup.IMarkupResourceStreamProvider. The only method defined in this interface is getMarkupResourceStream(MarkupContainer, Class<?>) which returns an utility interface called IResourceStream representing the actual markup.

In the following example we have a custom panel without a related markup file that generates a simple

tag as markup:

  1. public class AutoMarkupGenPanel extends Panel implements IMarkupResourceStreamProvider {
  2. public AutoMarkupGenPanel(String id, IModel<?> model) {
  3. super(id, model);
  4. }
  5. @Override
  6. public IResourceStream getMarkupResourceStream(MarkupContainer container,
  7. Class<?> containerClass) {
  8. String markup = "<wicket:panel><div>Panel markup</div></wicket:panel>";
  9. StringResourceStream resourceStream = new StringResourceStream(markup);
  10. return resourceStream;
  11. }
  12. }

Class StringResourceStream is a resource stream that uses a String instance as backing object.

18.6.1. Avoiding markup caching

As we have seen in the previous paragraph, Wicket uses an internal cache for components markup. This can be a problem if our component dynamical generates its markup when it is rendered because once the markup has been cached, Wicket will always use the cached version for the specific component. To overwrite this default caching policy, a component can implement interface IMarkupCacheKeyProvider.

This interface defines method getCacheKey(MarkupContainer, Class<?>) which returns a string value representing the key used by Wicket to retrieve the markup of the component from the cache. If this value is null the markup will not be cached, allowing the component to display the last generated markup each time it is rendered:

  1. public class NoCacheMarkupPanel extends Panel implements IMarkupCacheKeyProvider {
  2. public NoCacheMarkupPanel(String id, IModel<?> model) {
  3. super(id, model);
  4. }
  5. /**
  6. * Generate a dynamic HTML markup that changes every time
  7. * the component is rendered
  8. */
  9. @Override
  10. public IResourceStream getMarkupResourceStream(MarkupContainer container,
  11. Class<?> containerClass) {
  12. String markup = "<wicket:panel><div>Panel with current nanotime: " + System.nanoTime() +
  13. "</div></wicket:panel>";
  14. StringResourceStream resourceStream = new StringResourceStream(markup);
  15. return resourceStream;
  16. }
  17. /**
  18. * Avoid markup caching for this component
  19. */
  20. @Override
  21. public String getCacheKey(MarkupContainer arg0, Class<?> arg1) {
  22. return null;
  23. }
  24. }

18.7. Summary

In this chapter we have introduced some advanced topics we didn’t have the chance to cover yet. We have started talking about behaviors and we have seen how they can be used to enrich existing components (promoting a component-oriented approach). Behaviors are also fundamental to work with AJAX in Wicket, as we will see in the next chapter.

After behaviors we have learnt how to generate callback URLs to execute a custom method on server side defined inside a specific callback interface.

The third topic of the chapter has been the event infrastructure provided in Wicket for inter-component communication which brings to our components a desktop-like event-driven architecture.

Then, we have introduced a new entity called initializer which can be used to configure resources and component in a modular and self-contained way.

We have also looked at Wicket support for JMX and we have seen how to use this technology for monitoring and managing our running applications.

Finally we have introduced a new technique to generate the markup of a component from its Java code.