@PostConstruct
public void initScripting() {
ScriptEngineManager engineManager = new ScriptEngineManager();
this.scriptEngine = engineManager.getEngineByName(ENGINE_NAME);
if (this.scriptEngine == null) {
throw new IllegalStateException("Cannot create ScriptEngine: " + ENGINE_NAME);
}
}
@GET
@Path("{formula}/")
@Produces(MediaType.TEXT_PLAIN)
public String calculate(@PathParam("formula") String formula) {
Object retVal = null;
try {
Bindings binding = this.scriptEngine.createBindings();
binding.put("FIVE", 5);
this.scriptEngine.setBindings(binding, ScriptContext.GLOBAL_SCOPE);
retVal = this.scriptEngine.eval(formula);
} catch (Exception e) {
throw new IllegalStateException("Exception during evaluating script: " + e, e);
}
return retVal.toString();
}
}
The method calculate is annotated with @GET and so accessible through the following URL: http://localhost:8080/FluidLogic/resources/calculator/FIVE
The path FIVE is used as a method parameter and directly evaluated by the script. You can pass more sophisticated formulas as well: http://localhost:8080/FluidLogic/resources/calculator/6*7.
EJB 3.1 can be directly exposed via JAX-RS (JSR-311) without any plumbing like XML, configuration etc. An EJB 3 can use, as any other Java class, the "Scripting For The Java Platform" (JSR-223), to load and execute over 100 scripting languages (JavaScript, Groovy, JRuby, Jython Scala etc). This makes it interesting for the the implementation of simple to configure and maintain plugins and extensions. EJB 3.1 are transactional, so you could even manipulate managed JPA entities in the script and all the changes will be automatically synchronized with the database during the commit of the transaction.
An EJB 3.1 can be directly injected e.g. into a Servlet or managed bean in addition as well:
public class CalculatorView extends HttpServlet {
@EJB
private Calculator calculatorBean;
A deployable, working example was tested with Glassfish v3 and NetBeans 6.8m2 and pushed into http://kenai.com/projects/javaee-patterns/.
[See Fluid Logic pattern, page 117 in "Real World Java EE Patterns Rethinking Best Practices" book for more in-depth discussion]