1 28 29 package com.caucho.widget.impl; 30 31 import com.caucho.util.L10N; 32 import com.caucho.widget.WidgetException; 33 34 import javax.script.*; 35 36 public class WidgetScript 37 { 38 private static final L10N L = new L10N(WidgetScript.class); 39 40 private ScriptEngineManager _scriptEngineManager; 41 42 private String _text; 43 private String _language = "js"; 44 45 private ScriptEngine _scriptEngine; 46 private CompiledScript _compiledScript; 47 48 public WidgetScript() 49 { 50 _scriptEngineManager = new ScriptEngineManager(); 51 } 52 53 void setLanguage(String language) 54 { 55 if (_language == null) 56 throw new IllegalArgumentException(L.l("`{0}' cannot be null", "language")); 57 58 _language = language; 59 } 60 61 public void setText(String text) 62 { 63 _text = text; 64 } 65 66 public void init() 67 throws WidgetException 68 { 69 if (_text == null || _text.length() == 0) 70 throw new WidgetException(L.l("script has no contents")); 71 } 72 73 public void compile() 74 throws WidgetException 75 { 76 ScriptEngine engine = _scriptEngineManager.getEngineByName(_language); 77 78 if (engine == null) 79 throw new IllegalArgumentException(L.l("No script engine found for language `{0}'", _language)); 80 81 _scriptEngine = engine; 82 83 if (engine instanceof Compilable) { 84 Compilable compilable = (Compilable) _scriptEngine; 85 86 try { 87 _compiledScript = compilable.compile(_text); 88 } 89 catch (ScriptException e) { 90 throw new WidgetException(e); 91 } 92 } 93 } 94 95 public void exec(WidgetScriptContext scriptContext) 96 throws WidgetException 97 { 98 try { 99 if (_compiledScript != null) 100 _compiledScript.eval(scriptContext); 101 else 102 _scriptEngine.eval(_text, scriptContext); 103 } 104 catch (Exception e) { 105 throw new WidgetException(e); 106 } 107 } 108 } 109 | Popular Tags |