Looking for lightweight solution for my raspberry-pi, found Restlet; a framework that allows groovy (and java) programmers to implement restfull services without a servlet container or application server.
In this example, we’ll write a small app that routes the requests based on the URL requested pattern; for this, we’ll write two files:
MainApplication.groovy
import mx.maleficarum.Status
import org.restlet.Application
import org.restlet.Component
import org.restlet.Restlet
import org.restlet.data.Protocol
import org.restlet.routing.RouterApplication application = new Application() {
public synchronized Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach(«/sample/status»,Status.class );
return router;
}
};Component component = new Component()
component.getServers().add(Protocol.HTTP, 8080)
component.getDefaultHost().attach(application);
component.start()
This class is the entry point for the application, defining a router for each URL pattern and defining the port-protocolo for our HTTP server.
Status.groovy
package mx.maleficarum
import org.restlet.data.MediaType
import org.restlet.representation.Representation
import org.restlet.representation.StringRepresentation
import org.restlet.resource.Get
import org.restlet.resource.ServerResourceclass Status extends ServerResource {
@Get
public Representation doGet(){
def msg = «This is our status message!»
return new StringRepresentation(«{\»message\»:${msg}\»}», MediaType.APPLICATION_JSON);
}
}
This class is the handler for the URL http://localhost:8080/status, and just returns a JSON message.
Finally we shall run the script as :
groovy -classpath ../lib/org.restlet.jar mx/maleficarum/RestletApplication.groovy
We just need to add to classpath org.restlet.jar.