Optimizing Restlet server applications

There are several ways to optimize Restlet applications. We can leverage features of the HTTP protocol itself like caching or compression but also at the level of third-party tools like Restlet converters and template engines. This allows to have an application that provides quicker responses and optimized contents.

Using caching

One possible optimization is not to serve related resources (like images, css) when loading a particular resource with HTML content. An approach can be to use cache support provided by HTTP.

We describe here how to apply browser caching for all static elements loaded from a path with a subfolder called nocache. For these elements, headers for caching will be automatically added. For others, an expiration date of one month will be specified in headers.

This feature can be simply added with Restlet using filters within the method createInbountRoot of your application class. A filter containing caching stuff can to be added in front of the Restlet Directory that serves static content, as described below:

router.attach("/static", new Filter(getContext(),
                        new Directory(getContext(), (...))) {
    protected void afterHandle(Request request, Response response) {
        super.afterHandle(request, response);
            [adding caching stuff here]

Once the filter is added in the processing chain, we have to handle caching headers based on objects of types Representation and Response. The method noCache of the class Response automatically adds the related headers for no cache. For expiration date, the method setExpirationDate of the class Representation allows to define the laps of time before reloading the element content. Following code describes the complete code:

router.attach("/static", new Filter(getContext(),
                         new Directory(getContext(), (...))) {
    protected void afterHandle(Request request, Response response) {
        super.afterHandle(request, response);
        if (response.getEntity() != null) {
            if (request.getResourceRef().toString(false, false)
                                                        .contains("nocache")) {
            } else {
                Calendar c = new GregorianCalendar();
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, 1);

Compressing content

Modern browsers support compression for received content. This allows to reduce payload of exchanged data. Restlet supports this feature for server-side application using the class Encoder. The latter can take place within the processing chain like router, authenticator and filter. You simply need to configure it within the method createInbountRoot of your application class, as described below:

Encoder encoder = new Encoder(
             getContext(), false, true, getEncoderService());
return encoder;

Configuring specific converters

The converter feature of Restlet allows to automatically convert beans to / from representation content transparently and directly use them at the level of annotated methods of server resources.

This feature commonly uses third-party tools. The most used one corresponds to the converter based on (Jackson). It supports several formats like XML, JSON and YAML.

Putting the corresponding Restlet extensions is enough to use converters. As a matter of fact, they are automatically registered against the Restlet engine.

To configure these converters, we need to get instances of the registered converters you need to configure. Following snippet describes how to get an instance of the Jackson converter:

private JacksonConverter getRegisteredJacksonConverter() {
    JacksonConverter jacksonConverter = null;
    List<ConverterHelper> converters
             = Engine.getInstance().getRegisteredConverters();
    for (ConverterHelper converterHelper : converters) {
        if (converterHelper instanceof JacksonConverter) {
            jacksonConverter = (JacksonConverter) converterHelper;

Now we get an instance of the converter, we can get an instance of its associated ObjectMapper. It allows to configure the serialization and deserialization of the tool. In the following code, we describe how to set a serialization property not to include null values within the generated content:

private void configureJacksonConverter() {
    JacksonConverter jacksonConverter = getRegisteredJacksonConverter();

    if (jacksonConverter != null) {
        ObjectMapper objectMapper = jacksonConverter.getObjectMapper();

Configuring template engines

If we need to create on the server side by ourselves representation contents with formats like HTML and even XML or JSON, template engines can be used within server resources. Restlet provides dedicated representations for some of them with dedicated sub-classes of the class Representation. Its the case for (Freemarker).

Such engines can be configured to make content generation more efficient. For example, we can configure Freemarker to load templates once and share them against all content generations. For this, we need to set the property cacheStorage with an instance of class StrongCacheStorage. This can be done within the Restlet application class and then be accessible for all server resources, as described below:

public class SampleApplication extends Application {

    private Configuration configuration;


    public static Configuration configureFreeMarker(Context context) {
        Configuration configuration = new Configuration();
        ClassTemplateLoader loader = new ClassTemplateLoader(
        configuration.setCacheStorage(new StrongCacheStorage());
        return configuration;

    public Configuration getConfiguration() {
        return configuration;

The class TemplateRepresentation of the Freemarker extension of Restlet can be then used within the server resources, as described below:

public class MyServerResource extends ServerResource {

    private SampleApplication getSampleApplication() {
        return (SampleApplication)getApplication();


    private Representation toRepresentation(Map<String, Object> map,
                                           String templateName, MediaType mediaType) {
        return new TemplateRepresentation(templateName,
                getSampleApplication().getConfiguration(), map, mediaType);

    public Representation getHtml() {
        Map<String, Object> model = new HashMap<String, Object>();

        model.put("titre", "my title");
        model.put("users", getUsers());

        return toRepresentation(model,
            "myTemplate", MediaType.TEXT_HTML);

This entry was posted in REST, Restlet, Tips and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s