Server and client side validation

Maybe not so well known feature in Wicket is that the form component validators are actually Behaviors, or if they are not then a special adapter is used, so at the end they are stored as a behavior in the component.

Being a behavior gives the validator the chance to be notified when the respective form component is being rendered. And this makes it possible to make a validator that can validate at the server side and to contribute whatever is needed for some client side (JavaScript) library to make the same validation before the request is even made to the server.

At this repo you may find an integration with Parsley.js.

The implementation is in ParsleyValidationBehavior.
This is the base class that does most generic configuration, i.e. set the expected by Parsley data-xyz attributes in the form component markup. Additionally it uses a delegate IValidator that does the server side validation.

The usage is as any other validator in Wicket:

TextField fullName = new TextField("fullname", someModel);
fullName.add(new ParsleyValidationBehavior(EmailValidator.getInstance()).type("email").require(true));

The code above is a bit mouthfull so we can create a specialization class:

public class ParsleyEmailValidator extends ParsleyValidationBehavior
{
	public ParsleyEmailValidator()
	{
		super(EmailAddressValidator.getInstance());

		require(true);
		type("email");
	}
}

and use it like:

TextField fullName = new TextField("fullname", someModel);
fullName.add(new ParsleyEmailValidator());

The project just demostrates how to approach the problem. It does not provide full integration with Parsley.js.
If there is interest the project can be moved to WicketStuff and extended more with your help!

Update: Cedric Gatay extended the demo application with Bean Validation (JSR 303) support: Wicket + JSR_303 + Parsley. Good work, Cedric!

Replace components with animation

In this article I’m going to show you how to replace a component in Ajax response using animation effects like sliding, fading, etc.

The problem

To update a Component in Ajax request Wicket just replaces its old HTML DOM element with a new one created by the HTML in the response.
To update it with an animation you need to do:

  1. hide the old HTML element
  2. replace the component, but do not show it
  3. show the new HTML element

Attempt 1 (not working):

public void onClick(AjaxRequestTarget target) {
  target.prependJavaScript("jQuery('#"+component.getMarkupId()+"').slideUp(1000);");
  target.add(component);
  target.appendJavaScript("jQuery('#"+component.getMarkupId()+"').slideDown(1000);");
}

The first problem is that animations in JavaScript are implemented with window.setTimeout or with requestAnimationFrame and this makes them asynchronous-ish. That is Wicket will execute the prepend script to hide the element but wont wait for 1000ms before replacing it, so you wont see the slideUp effect.

The second problem is that target.add(component); will show the new HTML element right away and thus slideDown has nothing to do.

The solution

wicket-ajax-jquery.js supports special syntax for the prepended/appended JavaScripts: functionName|some-real-js-code. Such JavaScript is transformed to: function(functionName) {some-real-js-code} where functionName is a function which should be executed in your JavaScript code to allow the next operation to be executed.

Attempt 2 (working):

public void onClick(AjaxRequestTarget target) {
  component.add(new DisplayNoneBehavior());

  target.prependJavaScript("notify|jQuery('#" + component.getMarkupId() + "').slideUp(1000, notify);");
  target.add(component);
  target.appendJavaScript("jQuery('#"+component.getMarkupId()+"').slideDown(1000);");
}
private static class DisplayNoneBehavior extends AttributeAppender {
  private DisplayNoneBehavior() {
    super("style", Model.of("display: none"));
  }

  @Override
  public boolean isTemporary(Component component) {
    return true;
  }
}

Problem 1) is solved by using notify as a callback function which should be executed when the sliding up is finished.
Problem 2) is solved by using DisplayNoneBehavior that add ‘display: none’ to the markup of this component just for this rendering (see Behavior#isTemporary(Component)).

This code can be extracted in a helper class and reused. Simple implementation of such helper class can be found in the demo application.

This functionality is broken in Wicket 6.4.0, 6.5.0 and 6.6.0. It is fixed with WICKET-5039.

WicketStuff download stats for Nov 2012

Some download statistics for Wicket Stuff projects for November 2012:

  1. inmethod-grid (2468)
  2. googlecharts (666)
  3. tinymce (660)
  4. wicketstuff-annotation (648)
  5. inmethod-grid-examples (589)
  6. input-events (572)
  7. objectautocomplete (537)
  8. gmap2-examples (505)
  9. input-events-examples (480)
  10. googlecharts-examples (475)

As you can see, the examples projects are rather popular-taking 4 top 10 slots.

JavaScript based functional testing

The problem

Every software developer very well knows that producing new code leads to producing new bugs (problems in the software).
The good software developers know that writing tests for their code doesn’t solve completely the problem but at least prevents regressions. Unfortunately developers often do not have time to write the tests, or are too lazy to do it, or just don’t like the way they do it and try to postpone it.

In this article I’ll describe a prototype of a mini framework that can be used to create functional tests for web applications that run blazing fast, are easy to debug and more imporatantly are very close to the real way a web application is being used.

Note: this article is not Wicket specific. The described solution can be used for any kind of web application.

The solution

A well known library for writing functional tests for web applications is WebDriver/Selenium2.
My problem with it is that it is:

  • slow – starting the browser instance takes time, issuing commands to it takes time, HtmlUnitDriver with JavaScript enabled is very slow…
  • unreliable – every Driver implementation behaves differently. For me only FirefoxDriver works well
  • well, let’s not say more bad words for WebDriver. Some of its developers may have the same opinion for Apache Wicket :-)

In this article I’m going to describe how to use QUnit to run functional tests for Wicket Examples.

Apache Wicket project already uses QUnit for its unit tests since version 6.0.0 and so far they seems to serve us very well.

The main idea is that the tests run the application in an iframe, i.e. each test tells the iframe what is its initial source url, then the test can enter data in input fields, click links and buttons and finally assert the result of the previous actions.

CORS

The first problem is Cross origin requests – the tests need to be in the same domain as the application to be able to manipulate it.
There are (at least) two possible solutions:

  • run the application with the proper Access-Control-Allow-Origin header value
  • create a new application that merges the tests in the original application

The first approach is too obtrusive. It makes the application aware of its clients (the tests).
I prefer the second solution – by using Maven War Overlays we can create a Maven project that contains the tests and injects the original application in itself. This way the tests are available in my-tests folder in the web context for example.

QUnit Setup

To create QUnit tests you need to start with their HTML template. For our functional tests we need to put our additional iframe in its body. It is good to make the iframe big enough to be able to see what happens when you debug a test. In non-debug mode everything happens so fast that you cannot see anything ;-)

Here is the HTML template:

 





	
	
	
    
    
    

	
    

	
    
    
    
    
    



	

Wicket Examples JS tests

    The interesting things here are:

    • we preserve current page’s (the tests’ page) jQuery in $q variable and unset the original jQuery and $ variables just to avoid name clashes later in our tests.
    • we add Helpers.js which is a set of helper functions which are used by all our tests
    • we add <script> for all actual tests
    • and finally we add the iframe that will run the application

    And here is how the tests themselves look like:

    helloworld.js:

    
    $q(document).ready(function() {
    	"use strict";
    
    	module('Hello World');
    
    	asyncTest('hello world', function () {
    		expect(2);
    
    		onPageLoad(function($) {
    
    			var $message = $('#message');
    			equal($message.length, 1, "The greeting is there");
    			equal($message.text(), 'Hello World!', "The greeting is correct")
    			
    			start();
    		});
    		getIframe().attr('src', '/helloworld');
    	});
    
    });
    
    

    The idea is that we use QUnit asyncronous tests because often our tests will need to go over several pages in the application and we should not allow QUnit to go to the next test before the current test is finished.

    So what does this test do ?
    It registers a callback for the load event for the iframe and tells the iframe to go to the page we need to test. When the callback fires we make our assertions and then notify QUnit that we are ready with QUnit#start(). We can register several nested onPageLoad callbacks if the test needs to go over several pages.

    The Ajax tests work similarly just they listen for Wicket’s Global Ajax events. See ajax/form.js from the demo application for example.

    Demo

    A demo application that integrates wicket-examples.war can be found at my GitHub account.
    To run it:

    The tests can be integrated in Continious Integration setup easily by using PhantomJS and/or Grunt.js (also based on PhantomJS).
    To run the tests with Grunt.js check the header content of grunt.js in the project.

    Credits

    The original idea is borrowed from User interfaces and unit testing with QUnit

    Uploading files to Wicket IResource

    Several times people have asked in the mailing lists how to integrate JavaScript widgets for file uploading like Plupload, Uploadify, Fine Uploader or jQuery-File-Upload with Apache Wicket.

    The problem

    Wicket provides FileUploadField which can be used as part of a form submission. It supports HTML5 multiple attribute and works great but these JavaScript widgets are smarter than that!

    The widgets provide functionalities to select the files to upload with HTML5′s Drag & Drop, or if HTML5 is not supported by the browser then fallback to Flash or IFrame solution.

    So the widgets don’t really need a form to be able to do their work. All they need is a destination URL to send the bytes to.

    The solution

    Users of Apache Wicket know very well its WebPage component. It is used as a main container of other smaller components that construct the content that is delivered to the client when a given url is requested.
    Since file uploading doesn’t really need to construct a page and its optional response often is just a piece of data explaining that the upload is successful or not we are going to use Wicket’s IResource as an endpoint. IResource could be mounted at a predefined mount path just like pages by using a ResourceReference:

    MyApplication.java:

    
    @Override
    public void init() {
        super.init();
    
        mountResource("fileUpload", new FileUploadResourceReference(BASE_FOLDER));
        mountResource("fileManager", new FileManageResourceReference(BASE_FOLDER));
    }
    
    

    Here we mounted two resources – one as destination for the file uploads and another for managing the uploaded files (it can serve and delete them).

    Check Wicket 1.5 – Mounting resources for more information.

    Reading the uploaded files

    The main problem to solve is how to read the uploaded files from the request parameters.
    Actually the solution is quite simple, just few lines of code:

    AbstractFileUploadResource.java

    @Override
    protected ResourceResponse newResourceResponse(Attributes attributes)
    {
    	ServletWebRequest webRequest = (ServletWebRequest) attributes.getRequest();
    	MultipartServletWebRequest multiPartRequest = webRequest.newMultipartWebRequest(getMaxSize(), "ignored");
    	Map> files = multiPartRequest.getFiles();
    	...
    }
    

    We just asked Wicket to create a WebRequest that knows how to read the multipart request parameters. The final result is a map with keys the name of the request parameter and values the respective FileItems which can be used to get the uploaded file’s name, size, input stream, etc.

    And basically that’s it!
    From here on our code is responsible to store somewhere these files and return a response to the client is the format it expects – JSON, HTML, …

    Demo

    At my GitHub account you may find a demo application that integrates jQuery-File-Upload. I’ve chosen this widget because it looks very nice and I wanted to contribute it to Wicket Bootstrap project. It appeared that the docs and APIs of this widget are not the best one could wish for. To be able to duplicate the functionalities from its demo page I had to read and debug its internals (specifically jquery.fileupload-ui.js).

    There are still some functionalities which do not work completely:

    • the cancel button
    • the gallery preview of the uploaded files
    • the UI is broken in IE (I blame my CSS skills for that!)

    But all these are not directly related to the topic of this post – how to upload files to Wicket IResource and how to read them at the server side.
    If you need this component for your application and you fix this issues I’ll gladly accept your Pull Requests.

    Wicket 6 resource management

    Several improvements in the header contribution functionality have been made in Wicket 6 to make it more flexible.

    Header items

    The major API break is that now IHeaderResponse can render only instances of HeaderItem. In previous versions IHeaderResponse had many #renderXyz() methods for each and every combination of CSS or JavaScript attributes, like media, IE condition, charset, url, id, etc. The new version of IHeaderResponse has just one #render(HeaderItem) and the developer should use the most specific implementation of HeaderItem.

    For example:

    AnyComponent/AnyBehavior.java:

    
    @Override
    public void renderHead(IHeaderResponse response) {
    	super.renderHead(response);
    
    	response.render(new CssContentHeaderItem(someCss, someId, optionalCondition));
    	response.render(CssHeaderItem.forReference(new SomeCssResourceReference()));
    	response.render(JavaScriptHeaderItem.forScript(someScript, someId));
    }
    
    

    JavaScriptHeaderItem and CssHeaderItem provide factory methods for all default implementations of JavaScript and CSS related header items.

    Dependency management

    Resource references take advantage of the new HeaderItem’s and use them to specify on what other resources they depend. The most trivial example is when a JavaScriptResourceReference used to contribute a jQuery plugin needs to declare that it depends on jQuery. This way the component/behavior needs to contribute only the resources it really depends on and Wicket cares to deliver the dependencies first and then the dependants.

    public class MyResourceReference extends JavaScriptResourceReference {
    	public ResourceReferenceA() {
    		super(ResourceReferenceA.class, "my.js");
    	}
    
    	public Iterable getDependencies() {
    		List dependencies = new ArrayList();
    
    		Url dojoGoogleCdn = Url.parse("https://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js");
    		ExternalUrlResourceReference externalUrlResourceReference = new ExternalUrlResourceReference(dojoGoogleCdn);
    		dependencies.add(JavaScriptHeaderItem.forReference(externalUrlResourceReference));
    
    		dependencies.add(CssHeaderItem.forReference(new CssResourceReference(ResourceReferenceA.class, "a.css")));
    
    		return dependencies;
    	}
    }
    

    With the example above Wicket will render first the <script> to load Dojo and the <link> to load a.css before rendering the <script> for my.js.

    Resource bundles

    Another new feature in Wicket 6 is that several resources can be combined together in one before delivering it to the browser.

    One way to do this is to use WebApplication’s ResourceBundles:

    public void init() {
    	super.init();
    
    	getResourceBundles()
    		.addJavaScriptBundle(ResourceManagementApplication.class, "bundle.js",
    			new ResourceReferenceA(),
    			new ResourceReferenceB(),
    			new ResourceReferenceC()
    		);
    }
    

    Another way is by extending ConcatResourceBundleReference and using it as any other ResourceReference.

    Resource replacement

    Sometimes a third-party library or even Wicket itself adds dependencies you
    would rather replace by something else. For example, your application might
    depend on a more recent version of a JavaScript library or you want to use a
    CDN rather than a packaged resource. For this, Wicket 6 supports replacement
    resources. A replacement resource is a resource that will replace any
    occurence of some other resource throughout the application. It does not
    matter if the replaced resource is added in third party code, in your code or
    even as a depedency of another resource.

    The following code replaces any occurence of DojoResourceReference by the
    version hosted on the Google APIs CDN:

    MyApplication.java:

    @Override
    public void init() {
      super.init();
      
      addResourceReplacement(
        DojoResourceReference.get(),
        new UrlResourceReference(Url.parse("https://ajax.googleapis.com/ajax/libs/dojo/1.7.3/dojo/dojo.js"))
      );
    

    Positioning of contributions

    Filtered items

    A not well know feature in Wicket is that the application can provide custom IHeaderResponseDecorator and filter the header contributions. A common use case is when the application needs to render all JavaScripts in the footer of the page and leave CSSs in the header.
    This is made a bit simpler now by introducing FilteredHeaderItem.

    To make a use of it the developer have to add a special component in his page:

    add(new HeaderResponseContainer("someId", filterName));
    
    
    

    And later contribute FilteredHeaderItems in any component or behavior:

    @Override
    public void renderHead(IHeaderResponse response) {
    	super.renderHead(response);
    
    	response.render(new FilteredHeaderItem(wrappedItem, filterName));
    }
    

    Priority items

    Since Wicket 1.5 components do their header contribution before the page they are contained in. The reason is that the application may use a third party component library and the page should be able to override any contribution made by the components. A better design is if the components may be configured what to contribute but sometimes this is not possible. The same is valid for component inheritence – the specialization (the child component) contributes after the base component.
    Thanks to the HeaderItems with Wicket 6 it is possible to give some header contributions bigger priority than the others when there is such need. By default Wicket provides PriorityHeaderItem which is an item that is contributed before any other non-priority item. If the application needs finer control then it may register a custom comparator with IResourceSettings#setHeaderItemComparator(Comparator)

    response.render(new PriorityHeaderItem(wrappedItem));
    

    Demo application

    A demo application showing all these features in action can be found at Martin Grigorov’s GitHub repository. Run it locally and check the produced markup for the pages. There are comments inside the code describing the demonstrated features.

    Wicket 6 Native WebSockets

    Asynchronous communication with Web Sockets

    Wicket 6.0 introduces two new modules, both of them related to Server Push technology, Wicket-Atmosphere and Wicket Native WebSockets. In this article we will see how to make your application more dynamic by employing Wicket Native WebSockets.

    Web Sockets

    Web Sockets are new technology, part of HTML5 stack, for asynchronous communication between the web server and the browser. The client initiates a WebSocket connection by using the JavaScript APIs and from there on both the client and the server may send data to the other party fully asynchronously.

    Wicket Native WebSocket

    Server side APIs

    Wicket Native WebSocket module provides an integration that makes it as easy to use WebSockets as you already use Ajax in your Wicket applications. Basically all you need to do is to add a WebSocketBehavior to a page/component and override the callback methods you may be interested in – onConnect, onClose and/or onMessage.

    add(new WebSocketBehavior() {
    
      @Override protected void onMessage(WebSocketRequestHandler handler, TextMessage message) {
        String msg = message.getText();
        // use the message sent by the client
    
        handler.push("A message pushed by the server");
      }
    
    });
    

    Most probably an application will need to push messages from the server to the client asynchronously, i.e. without the client to ask for such messages. This may be achived by storing the needed information to lookup the WebSocket connection when WebSocketBehavior#onConnect(ConnectedMessage) is called:

    @Override protected void onConnect(ConnectedMessage message) {
    	applicationName = message.getApplication().getName();
    	sessionId = message.getSessionId();
    	pageId = message.getPageId();
    
    	// store applicationName, sessionId, pageId somehow so they are available later
    }
    
    

    Later when you need to push a message asynchronously you may lookup the connection with:

    
      IWebSocketConnectionRegistry registry = new SimpleWebSocketConnectionRegistry();
      Application application = Application.get(applicationName);
      IWebSocketConnection wsConnection = registry.getConnection(application, sessionId, pageId);
    
      if (wsConnection != null && wsConnection.isOpen()) {
        wsConnection.send("Asynchronous message");
      }
    
    

    Client side API

    By default when WebSocketBehavior is used Wicket will open a default WebSocket connection for you, so you can just use:

    Wicket.WebSocket.send("A message sent by the client");
    

    to send a message from the client to the server.

    To listen for messages pushed by the server you have to subscribe for a topic with name ‘/websocket/message’:

    Wicket.Event.subscribe("/websocket/message", function(jqEvent, message) {
    
    	// do something with the message.
    	// it may be a text or a binary message depending on what you pushed from the server side
    });
    
    

    Re-rendering components

    If you have noticed earlier #onMessage() receives a parameter of type WebSocketRequestHandler. This request handler implements AjaxRequestTarget so it is possible to add components (via #add(Component…)), to prepend/append JavaScript (via #prependJavaScript() and #appendJavaScript()) as you already do with Ajax behaviors.

    @Override protected void onMessage(WebSocketRequestHandler handler, TextMessage message) {
    
    	handler.add(someComponent);
    }
    
    

    Demo application

    At Martin Grigorov’s GitHub repository you may find an application that demonstrates some of the new possibilities available with WebSockets. The application schedules an asynchronous task at the server side that pushes data back to the client and visualizes it in Google Line chart.

    Documentation

    More complete documentation may be found at the Wiki. Feel free to contribute to make it better. Just create an account and edit it!

    Wicket 6 JavaScript improvements

    A major rework of the internals of the core Wicket JavaScript libraries has been done for Wicket 6. The good news is the client APIs are mostly the same and the application developers will not need to change their applications.

    Event registration

    Until version 1.5.x attaching an Ajax event behavior to a component would lead to addition of an inline attribute to the markup of this component. For example the produced markup for an AjaxLink is similar to:

    Link
    

    In Wicket 6 JavaScript event registration is being used instead. For example the above becomes:

    
      ...
      
    
    ...
    Link
    

    The benefit is that the event registrations for all elements are done in one place – the page header and your markup elements are not cluttered with extra attributes. Also the generated code for the event registration is much shorter than the one produced in the earlier versions.

    jQuery as backing library

    The previous implementations of wicket-ajax.js and wicket-event.js were home baked solutions which worked well but also suffered from the differences in the browsers. Often users complained that some functionality doesn’t work on particular version of particular browser. That’s why the Wicket team chose to use JQuery to deal with browser inconsistencies and leave us to do our business logic.

    All Java components and behaviors still use the Wicket.** APIs so if an application already uses another big JavaScript library and adding jQuery is not an option then the developer of this application will be able to provide implementation of wicket-event.js and wicket-ajax.js based on her favorite JavaScript library.
    To do it the developer should use the new IJavaScriptLibrarySettings:

    MyApplication#init():

    
    public void init() {
      super.init();
    
      IJavaScriptLibrarySettings jsSettings = getJavaScriptLibrarySettings();
    
      jsSettings.setBackingLibraryReference(new DojoResourceReference());
    
      jsSettings.setWicketEventReference(new DojoWicketEventResourceReference());
    
      jsSettings.setWicketAjaxReference(new DojoWicketAjaxResourceReference());
    
    }
    

    Ajax request attributes

    The main change in the Java code is the introduction of AjaxRequestAttributes in Ajax behaviors API.
    AjaxRequestAttributes can be used to configure how exactly the Ajax call should be executed and how its response should be processed. To do this use:

    AnyAjaxComponent/AnyAjaxBehavior.java:

      @Override
      protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
      {
          super.updateAjaxAttributes(attributes);
    
          attributes.setSomeAttribute();
      }
    

    This way the developer can specify whether the Ajax call should use GET or POST method, whether to submit a form, on what JavaScript events to listen to, etc. For a full list of the available attributes see the new Wiki page. Most of the attributes have default values and they may be omitted in the generated JavaScript code.

    Ajax call listeners

    Because of the usage of event registration there is no need of IAjaxCallDecorator because there is no script to decorate anymore. The same functionality can be achieved with the new IAjaxCallListener. It provides the means to register JavaScript listeners which are being called during the Ajax call execution. A listener may provide a precondition which may cancel completely the Ajax call when evaluated to false, a before handler – executed right after the successful pass of the preconditions, an after handler – executed right after the make of the Ajax call, a success handler – executed on successful return of the Ajax call, a failure handler – executed when the Ajax call fails for some reason, and a complete handler which is executed after the success/failure handlers no matter what.

    To register an AjaxCallListener do something like:

      @Override
      protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
      {
          super.updateAjaxAttributes(AjaxRequestAttributes attributes);
    
          IAjaxCallListener listener = new IAjaxCallListener()
          {
            @Override
            public CharSequence getBeforeHandler(Component c) { return handler; }
            .....
          };
    
          attributes.getAjaxCallListeners().add(listener);
      }
    

    In the example above the returned handler could be any instance of CharSequence. If it is an instance of JsonFunction then it will be written as is, otherwise Wicket will assume that the text is just the body of a JavaScript function and will wrap it in JsonFunction for you. The benefit of using JsonFunction is that it generates JSON with function as a value. This is non-valid JSON but this way there is no need to use eval() in the browser and the execution of the handlers is faster.

    Global Ajax call listeners

    IAjaxCallListener’s can be used to listen for the lifecycle of an Ajax call for a specific component. If the user application needs to listen for all Ajax calls then it may subscribe to the following topics:

    • /ajax/call/before
    • /ajax/call/after
    • /ajax/call/success
    • /ajax/call/failure
    • /ajax/call/complete

    Those replaces the old Wicket.Ajax.(registerPreCallHandler|registerPostCallHandler|registerFailureHandler) methods and uses publish/subscribe mechanism.

    Example (JavaScript):

        Wicket.Event.subscribe('/ajax/call/failure', function(jqEvent, attributes, jqXHR, errorThrown, textStatus) {
          // do something when an Ajax call fails
        });
    

    All global listeners receive the same arguments as the respective IAjaxCallListener handler plus jQuery.Event that is passed by the PubSub system.

    Demo application

    At Martin Grigorov’s GitHub repository you may find a simple demo application that shows some of the new features.
    The application provides a custom AjaxButton (HandlebarsButton) that uses:

    • org.apache.wicket.ajax.attributes.AjaxRequestAttributes#setWicketAjaxResponse(false) – tells Wicket.Ajax to not try to process the returned Ajax response. The response is custom JSON which will be processed by a custom success handler
    • org.apache.wicket.ajax.attributes.AjaxRequestAttributes#setDataType(“json”) – a hint to Wicket.Ajax that the response is JSON and it will try to parse it for us, so your success handler can use it as JavaScript object directly
    • usage of JsonFunction as success handler – this way the application needs to provide the complete code of a JavaScript function that will handle the success case
    • usage of plain Strings with the function bodies for the precondition, before and complete handlers – Wicket will wrap them in JsonFunction for you
    • shows how to suppress the execution of AjaxRequestHandler – there is no need of it since we return custom JSON response

    The application itself just updates a POJO (an article) at the server side and serializes it to JSON which is used at the client side to be rendered with the help of Handlebars JavaScript library.

    More

    More complete documentation may be found at the Wiki. Feel free to contribute to make it better. Just create an account and edit it!

    What’s new in Wicket 6

    What’s new in Wicket 6

    Wicket 6.0 is around the corner and it is time to describe what’s new and what’s has changed since Wicket 1.5. This article will mention briefly the major things. More details about the bigger changes will be provided in separate articles.

    Why 6.0 ?

    The Wicket team decided to use semantic versioning (http://semver.org) from now on. That means that having version like x.y.z we will fix bugs in ‘z’, introduce new features which do not break APIs in ‘y’ and break APIs in ‘x’ versions.
    This new version has APIs breaks here and there (more on this below) so it must be a change in ‘x’ part of the version.
    Wicket 2.0 has been used already few years ago, somewhere between Wicket 1.2 and 1.3 for a major change which didn’t work well and has been discontinued. Next option was Wicket 3.0 but since Wicket 6.0 now requires JDK 6 we decided to jump to 6.0.0. That doesn’t mean that Wicket 7 will require JDK 7.

    Major changes in Wicket 6.0

    JavaScript uses jQuery

    One of the bigger changes is in the Ajax support. Since version 6.0 Wicket will use jQuery internally for its JavaScript needs. Initially we started with an implementation based on YUI but the communitity asked us to re-think this decision and use jQuery instead because most of Wicket’s users use jQuery at the moment. So we switched to jQuery as backing library but made it such way that it is easy to replace the current implementation with another one based on another JavaScript library if this is needed by some of the users.

    Another change in the this area is that now Wicket uses JavaScript event registration (e.g. jQuery(element).on(‘click’, function() { … }) instead of using inline attributes in the HTML (e.g. <a onclick=”…”>).

    Resource management

    ResourceReference class now can declare its dependencies so you just need to contribute a ResourceReference for your jQuery plugin for example, and the ResourceReference itself will tell Wicket that jQuery has to be delivered as well.

    Additionally PackageResourceReference and its specializations can deliver minified version of their resource if such is available. For example by using
    ‘new JavaScriptResourceReference(MyComponent.class, “my.js”)’ Wicket will deliver my.js in development mode but will deliver my.min.js in production mode if it is available in the same folder.

    New Tree component

    The previous Tree component implementation used AWT/SWING APIs and it was not possible to use it in more restricted environments like Google AppEngine. That’s why it has been deprecated and will be removed in a some next major release of Wicket.
    AbstractTree and its specializations NestedTree and TableTree are the replacements.

    New modules

    A few new modules have been added to the Wicket portfolio. For now they are with experimental status but depending on the adoption they will either join the other modules or will be removed.

    Integration with Atmosphere

    The first new module is Wicket Atmosphere (Maven id: org.apache.wicket:wicket-atmosphere:jar). It is an integration with Atmosphere project and provides server push functionality. Depending on the configuration it may use WebSocket, long polling, streaming, JSONP, Server Side events mechanisms.

    Wicket Native WebSocket

    The second new module is again related to server push functionality but uses native integration with the underlying web container if such is supported. At the moment only Jetty 7+ and Tomcat 7+ are supported.

    What didn’t make it

    Component queueing

    The task of component queueing was to remove the requirement to keep in sync the component trees in the markup and in Java. Due to various technical problems this task has been postponed and may be implemented in a later version of Wicket.

    CDI integration

    The Contexts and Dependency injection (CDI) integration implemented in wicket-cdi cannot be merged to Apache Wicket for now because it uses some libraries which are not available yet in Maven central repository. Until this problem is resolved users still can use it as described at the project site.

    What else

    Some more information about the major changes can be found at the Roadmap page and about other minor changes at the Migration page

    The Wicket team!