Posted By

octaviannitagmailcom on 02/28/12


Tagged

scripting facade boilerplate


Versions (?)

Boilerplate: Scripting API Facade


 / Published in: Java
 

Boilerplate Java scripting API code to evaluate scripts located in either the classpath or in the file system and then get variable values by evaluating expressions (in case no easy/direct mapping can be made from script structures to java objects)

  1. /**
  2.  * This default implementation tries to create and use a JavaScript script(ing) engine.
  3.  *
  4.  * @author Octavian Theodor NITA
  5.  * @version 1.0, Feb 27, 2012
  6.  */
  7. public class ScriptEngineFacade {
  8.  
  9. private static final Logger logger = Logger.getLogger(ScriptEngineFacade.class);
  10.  
  11. private final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
  12.  
  13. public void put(String name, Object value) {
  14. scriptEngine.put(name, value);
  15. }
  16.  
  17. public void eval(String scriptName) throws IOException, ScriptException {
  18. InputStream script = getClass().getClassLoader().getResourceAsStream(scriptName);
  19. if (script == null) { // cannot find the script in the classpath... try in the file system
  20. script = new FileInputStream(scriptName);
  21. }
  22. try {
  23. scriptEngine.eval(new InputStreamReader(script));
  24. } finally {
  25. try {
  26. script.close();
  27. } catch (IOException e) {
  28. logger.warn("cannot close stream for script " + scriptName + "; ignoring...", e);
  29. }
  30. }
  31. }
  32.  
  33. public <T> T value(String expr, Class<T> klass) {
  34. if (klass == null) {
  35. throw new IllegalArgumentException("cannot cast the value of " + expr + " using a null class name");
  36. }
  37. if (expr == null) {
  38. return null;
  39. }
  40.  
  41. try {
  42. return klass.cast(scriptEngine.eval(expr));
  43. } catch (NullPointerException e) {
  44. logger.error("cannot get the value of " + expr + ": a null or undefined reference was encountered", e);
  45. return null;
  46. } catch (ClassCastException e) {
  47. logger.error("cannot get the value of " + expr + ": expected value type for is " + klass.getName(), e);
  48. return null;
  49. } catch (ScriptException e) {
  50. logger.error("cannot get the value of " + expr + ": cannot evaluate expression", e);
  51. return null;
  52. }
  53. }
  54. }

Report this snippet  

You need to login to post a comment.