Alexander Chepurnoy

The Web of Mind

Webservice With Groovy and Restlet

| Comments

Once I had a need to implement simplest web-based launcher for several tasks. It was implemented fast with Groovy and Restlet framework(for Java). Let’s start with sample, but working code, I’ll explain it further:

package org.chepurnoy.examples

import org.restlet.Component
import org.restlet.data.Protocol
import org.restlet.resource.*

class LauncherService extends ServerResource {
    static def flags = ["task1": null, "task2": null, "task3": null]
    def actions = [task1: ({print "task1 started"; Thread.sleep(30000); print "task1 finished"}),
                   task2: ({print "task2 started"; Thread.sleep(30000); print "task2 finished"}),
                   task3: ({print "task3 started"; Thread.sleep(30000); print "task3 finished"})
    ]

    @Get
    public String serve() {
        def action = getQuery().getValues("action");
        if (flags[action]) {
            return "already runned from"+flags[action]
        }
        flags[action] = new Date()
        Thread.start {
            actions[action].call()
            flags[action] = null
        }
        return "${action} started"
    }
}

Component component = new Component()
component.getServers().add(Protocol.HTTP, 8394)
component.getDefaultHost().attach("/launcher", LauncherService.class)
component.start()

Now let’s take a closer look:

  1. It’s the Groovy script in fact, so we don’t need for ‘public static void main’ method to launch embedded web-server Jetty containing our webservice.

  2. Webservice launches different tasks depends on “action” GET parameter. Possible tasks are stored in ‘actions’ list as closures. Closure usage makes code more clean as we don’t need to use if-then or Strategy design pattern.

  3. Webservice prevents a task to be launched for the second time while running. ‘flags’ list is used for it.

  4. Our script uses Thread.start static method with closure parameter to launch a task in a new thread. Kinda useful GDK feature.

It’s just example. In real world script you should return data in industry-known format(JSON/XML), check input data, maybe implement REST to post task through POST or PUT HTTP method and get status via GET etc.

Comments