(Quick Reference)

26 Project WicketStuff (Appendix) - Reference Documentation

Authors: Andrea Del Bene, Martin Grigorov, Carsten Hufe, Christian Kroemer, Daniel Bartl, Paul Borș

Version: 6.x

26 Project WicketStuff (Appendix)

26.1 What is project WicketStuff

WicketStuff is an umbrella project that gathers different Wicket-related projects developed and maintained by the community. The project is hosted on GitHub at https://github.com/wicketstuff/core Every module is structured as a parent Maven project containing the actual project that implements the new functionality and an example project that illustrates how to use it in our code. The resulting directory structure of each module is the following:

<module name>-parent
        |
        +---<module name>
        ---<module name>-examples

So far we have introduced only modules Kryo Serializer and JavaEE Inject, but WicketStuff comes with many other modules that can be used in our applications. Some of them come in handy to improve the user experience of our pages with complex components or integrating some popular web services (like Google Maps ) and JavaScript libraries (like TinyMCE ).

This appendix provides a quick overview of what WicketStuff offers to enhance the usability and the visually-appealing of our pages.

Every WicketStuff module can be downloaded as JAR archive at http://mvnrepository.com . This site provides also the XML fragment needed to include it as a dependency into our pom.xml file.

26.2 Module tinymce

Module tinymce offers integration with the namesake JavaScript library that turns our “humble” text-areas into a full-featured HTML WYSIWYG editor:

To “tinyfy” a textarea component we must use behavior TinyMceBehavior:

TextArea textArea = new TextArea("textArea", new Model(""));
textArea.add(new TinyMceBehavior());

By default TinyMceBehavior adds only a basic set of functionalities to our textarea:

To add more functionalities we must use class TinyMCESettings to register additional TinyMCE plugins and to customize the toolbars buttons. The following code is an excerpt from example page FullFeaturedTinyMCEPage:

TinyMCESettings settings = new TinyMCESettings(
                       TinyMCESettings.Theme.advanced);
//…
// first toolbar
//…
settings.add(Button.newdocument, TinyMCESettings.Toolbar.first,
		      TinyMCESettings.Position.before);
settings.add(Button.separator, TinyMCESettings.Toolbar.first,
		      TinyMCESettings.Position.before);
settings.add(Button.fontselect, TinyMCESettings.Toolbar.first,
		      TinyMCESettings.Position.after);
//…
// other settings
settings.setToolbarAlign(
   		TinyMCESettings.Align.left);
settings.setToolbarLocation(
   		TinyMCESettings.Location.top);
settings.setStatusbarLocation(
   		TinyMCESettings.Location.bottom);
settings.setResizing(true);
//…
TextArea textArea = new TextArea("ta", new Model(TEXT));
textArea.add(new TinyMceBehavior(settings));

For more configuration examples see pages inside package wicket.contrib.examples.tinymce in the example project of the module.

26.3 Module wicketstuff-gmap3

Module wicketstuff-gmap3 integrates Google Maps service with Wicket providing component org.wicketstuff.gmap.GMap. If we want to embed Google Maps into one of our pages we just need to add component GMap inside the page. The following snippet is taken from example page SimplePage:

HTML:

…
<body>
  <div wicket:id="map">Map</div>
</body>
...

Java code:

public class SimplePage extends WicketExamplePage
{
    public SimplePage()
    {
        GMap map = new GMap("map");
        map.setStreetViewControlEnabled(false);
        map.setScaleControlEnabled(true);
        map.setScrollWheelZoomEnabled(true);
        map.setCenter(new GLatLng(52.47649, 13.228573));        
        add(map);
    }
}

The component defines a number of setters to customize its behavior and appearance. More info can be found on wiki page https://github.com/wicketstuff/core/wiki/Gmap3 .

26.4 Module wicketstuff-googlecharts

To integrate the Google Chart tool into our pages we can use module wicketstuff-googlecharts. To display a chart we must combine the following entities: component Chart, interface IChartData and class ChartProvider, all inside package org.wicketstuff.googlecharts. The following snippet is taken from example page Home:

HTML:

…
  <h2>Hello World</h2>
  <img wicket:id="helloWorld"/>
...

Java code:

IChartData data = new AbstractChartData(){
    public double[][] getData(){
       return new double[][] { { 34, 22 } };
    }
};

ChartProvider provider = new ChartProvider(new Dimension(250, 100), ChartType.PIE_3D, data); provider.setPieLabels(new String[] { "Hello", "World" }); add(new Chart("helloWorld", provider));

Displayed chart:

As we can see in the snippet above, component Chart must be used with <img> tag while the input data returned by IChartData must be a two-dimensional array of double values.

26.5 Module wicketstuff-inmethod-grid

Module wicketstuff-inmethod-grid implements a sophisticated grid-component with class com. inmethod.grid.datagrid.DataGrid.

Just like pageable repeaters (seen in paragraph 11.4) DataGrid provides data pagination and uses interface IDataProvider as data source. In addition the component is completely ajaxified:

DataGrid supports also editable cells and row selection:

The following snippet illustrate how to use DataGrid and is taken from wiki page https://github.com/wicketstuff/core/wiki/InMethodGrid :

HTML:

…
  <div wicket:id="grid">Grid</div>
...

Java code:

final List<Person> personList = //load a list of Persons
final ListDataProvider listDataProvider = new ListDataProvider(personList);
//define grid's columns
List<IGridColumn> cols = (List) Arrays.asList(
	     new PropertyColumn(new Model("First Name"), "firstName"),
	     new PropertyColumn(new Model("Last Name"), "lastName"));

DataGrid grid = new DefaultDataGrid("grid", new DataProviderAdapter(listDataProvider), cols); add(grid);

In the code above we have used convenience class DefaultDataGrid that is a subclass of DataGrid and it already comes with a navigation toolbar.

The example pages are under package com.inmethod.grid.examples.pages in the example project which is hosted at http://www.wicket-library.com/inmethod-grid/data-grid/simple .

26.6 Module wicketstuff-rest-annotations

REST-based API are becoming more and more popular around the web and the number of services based on this architecture is constantly increasing.

Wicket is well-known for its capability of transparently handling the state of web applications on server side, but it can be also easily adopted to create RESTful services. WicketStuff module for REST provides a special resource class and a set of annotations to implement REST APIs/services in much the same way as we do it with Spring MVC or with the standard JAX-RS.

The module provides class AbstractRestResource as generic abstract class to implement a Wicket resource that handles the request and the response using a particular data format (XML, JSON, etc...). Subclassing AbstractRestResource we can create custom resources and map their pubblic methods to a given subpath with annotation MethodMapping. The following snippet is taken from resource PersonsRestResource inside module 'restannotations-examples':

@MethodMapping("/persons")
    public List<PersonPojo> getAllPersons() {
        //method mapped at subpath "/persons" and HTTP method GET
    }

@MethodMapping(value = "/persons/{personIndex}", httpMethod = HttpMethod.DELETE) public void deletePerson(int personIndex) { //method mapped at subpath "/persons/{personIndex}" and HTTP method DELETE. //Segment {personIndex} will contain an integer value as index. }

@MethodMapping(value = "/persons", httpMethod = HttpMethod.POST) public void createPerson(@RequestBody PersonPojo personPojo) { //creates a new instance of PersonPojo reading it from request body }

MethodMapping requires to specify the subpath we want to map the method to. In addition we can specify also the HTTP method that must be used to invoke the method via REST (GET, POST, DELETE, PATCH, etc...). This value can be specified with enum class HttpMethod and is GET by default. In the code above we can see annotation RequestBody which is used to extract the value of a method parameter from the request body (method createPerson). To write/read objects to response/from request, AbstractRestResource uses an implementation of interface IWebSerialDeserial which defines the following methods:

public interface IWebSerialDeserial {

public void objectToResponse(Object targetObject, WebResponse response, String mimeType) throws Exception;

public <T> T requestToObject(WebRequest request, Class<T> argClass, String mimeType) throws Exception;

public boolean isMimeTypeSupported(String mimeType); }

To convert segments value (which are strings) to parameters type, AbstractRestResource uses the standard Wicket mechanism based on the application converter locator:

//return the converter for type clazz
    IConverter converter = Application.get().getConverterLocator().getConverter(clazz);
    //convert string to object
    return converter.convertToObject(value, Session.get().getLocale());

In order to promote the principle of convention over configuration, we don't need to use any annotation to map method parameters to path parameters if they are declared in the same order. If we need to manually bind method parameters to path parameters we can use annotation PathParam.

@MethodMapping(value = "/variable/{p1}/order/{p2}", produces = RestMimeTypes.PLAIN_TEXT)
    public String testParamOutOfOrder(PathParam("p2") String textParam, PathParam("p1") int intParam) {
        //method parameter textParam is taken from path param 'p2', while intParam uses 'p1'
    }

As JSON is de-facto standard format for REST API, the project comes also with a ready-to-use resource (GsonRestResource) and a serial/deserial (GsonSerialDeserial) that work with JSON format (both inside module 'restannotations-json'). These classes use Gson as JSON library.

AbstractRestResource supports role-based authorizations for mapped method with annotation AuthorizeInvocation:

@MethodMapping(value = "/admin", httpMethod = HttpMethod.GET)
    @AuthorizeInvocation("ROLE_ADMIN")
    public void testMethodAdminAuth() {

}

To use annotation AuthorizeInvocation we must specify in the resource construcor an instance of Wicket interface IRoleCheckingStrategy.

To read the complete documentation of the module and to discover more advanced feature please refer to the project homepage