| 1 21 package org.lobobrowser.html.js; 22 23 import org.lobobrowser.html.*; 24 import org.lobobrowser.html.domimpl.*; 25 import org.lobobrowser.js.JavaScript; 26 import org.mozilla.javascript.*; 27 import org.w3c.dom.Document ; 28 import java.util.logging.*; 29 30 public class Executor { 31 private static final Logger logger = Logger.getLogger(Executor.class.getName()); 32 33 38 public static Context createContext(java.net.URL codeSource, UserAgentContext ucontext) { 39 Context prev = Context.getCurrentContext(); 40 Context ctx = Context.enter(); 41 ctx.setOptimizationLevel(ucontext.getScriptingOptimizationLevel()); 42 if(prev == null) { 43 ctx.setSecurityController(new SecurityControllerImpl(codeSource, ucontext.getSecurityPolicy())); 47 } 48 return ctx; 49 } 50 51 public static boolean executeFunction(NodeImpl element, Function f, Event event) { 52 return Executor.executeFunction(element, element, f, event); 53 } 54 55 public static boolean executeFunction(NodeImpl element, Object thisObject, Function f, Event event) { 56 Document doc = element.getOwnerDocument(); 57 if(doc == null) { 58 throw new IllegalStateException ("Element does not belong to a document."); 59 } 60 Context ctx = createContext(element.getDocumentURL(), element.getUserAgentContext()); 61 try { 62 Scriptable scope = (Scriptable) doc.getUserData(Executor.SCOPE_KEY); 63 if(scope == null) { 64 throw new IllegalStateException ("Scriptable (scope) instance was expected to be keyed as UserData to document using " + Executor.SCOPE_KEY); 65 } 66 JavaScript js = JavaScript.getInstance(); 67 Scriptable thisScope = (Scriptable) js.getJavascriptObject(thisObject, scope); 68 try { 69 Scriptable eventScriptable = (Scriptable) js.getJavascriptObject(event, thisScope); 70 ScriptableObject.defineProperty(thisScope, "event", eventScriptable, ScriptableObject.READONLY); 71 Object result = f.call(ctx, thisScope, thisScope, new Object [0]); 72 if(!(result instanceof Boolean )) { 73 return true; 74 } 75 return ((Boolean ) result).booleanValue(); 76 } catch(Exception thrown) { 77 logger.log(Level.WARNING, "executeFunction(): There was an error in Javascript code.", thrown); 78 return true; 79 } 80 } finally { 81 Context.exit(); 82 } 83 } 84 85 public static boolean executeFunction(Scriptable thisScope, Function f, java.net.URL codeSource, UserAgentContext ucontext) { 86 Context ctx = createContext(codeSource, ucontext); 87 try { 88 try { 89 Object result = f.call(ctx, thisScope, thisScope, new Object [0]); 90 if(!(result instanceof Boolean )) { 91 return true; 92 } 93 return ((Boolean ) result).booleanValue(); 94 } catch(Exception err) { 95 logger.log(Level.WARNING, "executeFunction(): Unable to execute Javascript function " + f.getClassName() + ".", err); 96 return true; 97 } 98 } finally { 99 Context.exit(); 100 } 101 } 102 103 107 public static final String SCOPE_KEY = "cobra.js.scope"; 108 } 109 | Popular Tags |