I've been playing around with Java 6 scripting engines and restlet and I've
considered and come up with a few approaches.  I'd be interested in opinions
on this.

There certainly is the JSP-like way of write a web page where the page's output
is bound to the request response.  There are so many issues with state in
that approach in that you may find that you need to fail a response when
you've already committed output to the response.  As such, you can't change
the status of the response.  I've avoided this design pattern like the plague.

Instead, I've chosen to pass the request and response to the script and let
the script handle the posts, etc.

The first function-oriented approach looks like this in Javascript:

  var theContext = null;
  function init(context) {
     theContext = context;
  }

  function post(request, response) {
     response.setStatus(Status.SUCCESS_OK);
     response.setEntity(new StringRepresentation(request.getMethod()+"
is OK",MediaType.TEXT_PLAIN));
  }

  function get(request, response) {
     response.setStatus(Status.SUCCESS_OK);
     response.setEntity(new StringRepresentation(request.getMethod()+"
is OK",MediaType.TEXT_PLAIN));
  }

The script is initialized by passing the context to the the init()
function.   Then for
any request, the method is translated into a function call (e.g. a
POST method means
the post() function is called).

A slightly more object-oriented approach looks like:

  function RestScript(context) {
     this.context = context;
  }

  RestScript.prototype.post = function(request,response) {
     response.setStatus(Status.SUCCESS_OK);
     response.setEntity(new StringRepresentation(request.getMethod()+"
is OK",MediaType.TEXT_PLAIN));
  }

  RestScript.prototype.get = function(request,response) {
     response.setStatus(Status.SUCCESS_OK);
     response.setEntity(new StringRepresentation(request.getMethod()+"
is OK",MediaType.TEXT_PLAIN));
  }

  function init(context) {
     return new RestScript(context);
  }


The init() function is called.  If the init function returns an
object, then methods on
that object are called instread of global functions.

I've currently implemented this as a very terse Application class that
just compiles
the script and passes the requests as appropriate.  I could certainly
see expanding
this to handle mapping requests to more than one script file/source.

Comments?  Suggestions?

Has anyone tried JRuby or Groovy with Restlets ?

--Alex Milowski

Reply via email to