public SheetJSFile read_file(String filename) throws IOException, ObjectNotFoundException { /* open file */ String d = JSHelper.read_file(filename); /* options argument */ NativeObject q = (NativeObject)this.cx.evaluateString(this.scope, "q = {'type':'binary'};", "<cmd>", 2, null); /* set up function arguments */ Object functionArgs[] = {d, q}; /* call read -> wb workbook */ Function readfunc = (Function)JSHelper.get_object("XLSX.read",this.scope); NativeObject wb = (NativeObject)readfunc.call(this.cx, this.scope, this.nXLSX, functionArgs); return new SheetJSFile(wb, this); }
/** * Wraps the 'confirm' method of the Window interface. */ public static Object confirm(Context cx, Scriptable thisObj, Object[] args, Function funObj) { int len = args.length; WindowWrapper ww = (WindowWrapper)thisObj; Window window = ww.window; if (len >= 1) { String message = (String)Context.jsToJava(args[0], String.class); if (window.confirm(message)) return Context.toObject(Boolean.TRUE, thisObj); else return Context.toObject(Boolean.FALSE, thisObj); } return Context.toObject(Boolean.FALSE, thisObj); }
/** * Calls JavaScript native function. * * @param function Function to be called. * @param args Call arguments. */ public static void call(final Function function, final Object... args) { Scriptable scope = function.getParentScope(); ObjectTopLevel topLevel = JavaScriptEngine.getObjectTopLevel(scope); if (topLevel != null) { Context cx = topLevel.getBrowserScriptEngine().enterContext(); try { function.call(cx, scope, scope, args); } catch (Exception ex) { try { JavaScriptEngine.throwWrappedScriptException(ex); } catch (ScriptException e) { throw new WrappedException(e); } } finally { Context.exit(); } } }
protected void executeSimpleHandlerCore(String handlerType, org.mozilla.javascript.Context myJavascriptContext) throws EcmaError, EvaluatorException, JavaScriptException, EngineException { handlerName = "on" + handlerType; Engine.logBeans.trace("(Transaction) Searching the " + handlerType + " handler (" + handlerName + ")"); Object object = scope.get(handlerName, scope); Engine.logBeans.trace("(Transaction) Rhino returned: [" + object.getClass().getName() + "] " + object.toString()); if (!(object instanceof Function)) { Engine.logBeans.debug("(Transaction) No " + handlerType + " handler (" + handlerName + ") found"); return; } else { Engine.logBeans.debug("(Transaction) Execution of the " + handlerType + " handler (" + handlerName + ") for the transaction '" + getName() + "'"); } function = (Function) object; Object returnedValue = function.call(myJavascriptContext, scope, scope, null); if (returnedValue instanceof org.mozilla.javascript.Undefined) { handlerResult = ""; } else { handlerResult = returnedValue.toString(); } }
/** * 执行JS * * @param js js代码 * @param functionName js方法名称 * @param functionParams js方法参数 * @return */ public static String runScript(Context context, String js, String functionName, Object[] functionParams) { org.mozilla.javascript.Context rhino = org.mozilla.javascript.Context.enter(); rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); ScriptableObject.putProperty(scope, "javaContext", org.mozilla.javascript.Context.javaToJS(context, scope)); ScriptableObject.putProperty(scope, "javaLoader", org.mozilla.javascript.Context.javaToJS(context.getClass().getClassLoader(), scope)); rhino.evaluateString(scope, js, context.getClass().getSimpleName(), 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(rhino, scope, scope, functionParams); if (result instanceof String) { return (String) result; } else if (result instanceof NativeJavaObject) { return (String) ((NativeJavaObject) result).getDefaultValue(String.class); } else if (result instanceof NativeObject) { return (String) ((NativeObject) result).getDefaultValue(String.class); } return result.toString();//(String) function.call(rhino, scope, scope, functionParams); } finally { org.mozilla.javascript.Context.exit(); } }
/** * load * @param response */ public void load( WebResponse response ) { Function onLoadEvent=null; try { Context context = Context.enter(); context.initStandardObjects( null ); HTMLDocument htmlDocument = ((DomWindow) response.getScriptingHandler()).getDocument(); if (!(htmlDocument instanceof HTMLDocumentImpl)) return; HTMLBodyElementImpl body = (HTMLBodyElementImpl) htmlDocument.getBody(); if (body == null) return; onLoadEvent = body.getOnloadEvent(); if (onLoadEvent == null) return; onLoadEvent.call( context, body, body, new Object[0] ); } catch (JavaScriptException e) { ScriptingEngineImpl.handleScriptException(e, onLoadEvent.toString()); // HttpUnitUtils.handleException(e); } catch (EcmaError ee) { //throw ee; ScriptingEngineImpl.handleScriptException(ee, onLoadEvent.toString()); } finally { Context.exit(); } }
@JSStaticFunction public static void parseToHtml(final String url, final String option, final Function func) { new Thread(new Runnable() { @Override public void run() { Document document = null; try { document = Jsoup.connect(url).get(); Elements element = document.select(option); func.call(context, scope, scope, new Object[] { element.html(), null }); } catch (IOException e) { try { func.call(context, scope, scope, new Object[] { null, e}); } catch (Exception err) {} } } }).start(); }
@JSStaticFunction public static void parseToText(final String url, final String option, final Function func) throws IOException { new Thread(new Runnable() { @Override public void run() { Document document = null; try { document = Jsoup.connect(url).get(); Elements element = document.select(option); func.call(context, scope, scope, new Object[] { element.text(), null }); } catch (IOException e) { try { func.call(context, scope, scope, new Object[] { null, e }); } catch (Exception err) {} } } }).start(); }
public void invokeFunction(String name, Object... parameters) { Function func = (Function) globalScope.get(name, globalScope); if(func != null) { Context.enter(); try { func.call(context, globalScope, globalScope, parameters); } catch (EcmaError err) { KakaoManager.getInstance().receiveError(err); } String params = ""; int i = 0; for(Object p : parameters) { i++; params += " -> " + String.valueOf(p); if(i != parameters.length) { params += "\n"; } } Logger.Log log = new Logger.Log(); log.type = Logger.Type.APP; log.title = "call \"" + name + "\""; log.index = "parameters\n" + params; Logger.getInstance().add(log); } }
private String decryptSignature(String encryptedSig, String decryptionCode) throws DecryptException { Context context = Context.enter(); context.setOptimizationLevel(-1); Object result; try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, decryptionCode, "decryptionCode", 1, null); Function decryptionFunc = (Function) scope.get("decrypt", scope); result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig}); } catch (Exception e) { throw new DecryptException("could not get decrypt signature", e); } finally { Context.exit(); } return result == null ? "" : result.toString(); }
public void testFunctionWithContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode cx.evaluateString(globalScope, "function f(a) { return myObject.f(a); }", "function test source", 1, null); Function f = (Function) globalScope.get("f", globalScope); Object[] args = { 7 }; cx.callFunctionWithContinuations(f, globalScope, args); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { Object applicationState = pending.getApplicationState(); assertEquals(7, ((Number)applicationState).intValue()); int saved = (Integer) applicationState; Object result = cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); assertEquals(8, ((Number)result).intValue()); } finally { Context.exit(); } }
/** * ECMA 11.4.3 says that typeof on host object is Implementation-dependent */ public void test0() throws Exception { final Function f = new BaseFunction() { @Override public Object call(Context _cx, Scriptable _scope, Scriptable _thisObj, Object[] _args) { return _args[0].getClass().getName(); } }; final ContextAction action = new ContextAction() { public Object run(final Context context) { final Scriptable scope = context.initStandardObjects(); scope.put("myObj", scope, f); return context.evaluateString(scope, "typeof myObj", "test script", 1, null); } }; doTest("function", action); }
public void callJsFunction(String name, Object... params) { Object obj = getJsFunction(name); if (obj instanceof Function) { Function function = (Function) obj; // NativeObject result = (NativeObject) function.call(rhino, scope, scope, params); processResult(RESULT_OK, ""); } }
/** * After finding the decrypted code in the js html5 player code * run the code passing the encryptedSig parameter * * @param encryptedSig * @param html5player * @return * @throws Exception */ private static String decipherKey(String encryptedSig, String html5player) throws Exception { String decipherFunc = loadFunction(html5player); Context context = Context.enter(); // Rhino interpreted mode context.setOptimizationLevel(-1); Object result = null; try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, decipherFunc, "decipherFunc", 1, null); Function decryptionFunc = (Function) scope.get("decrypt", scope); result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig}); } catch (Exception e) { e.printStackTrace(); } finally { Context.exit(); } if (result == null) { return ""; } else { return result.toString(); } }
@Override public String evaluate(Script script, String func, Object[] args) { String resultStr = ""; try { rhino.evaluateString(scope, script.getSourceCode(), script.getHumanName(), 1, null); Function function = (Function) scope.get(func, scope); Object result = function.call(rhino, scope, scope, args); if (result != null) { resultStr = result.toString(); } } catch (Exception e) { e(e); } return resultStr; }
@Benchmark @SuppressWarnings("unused") void createFields(int count) { Function create = (Function)ScriptableObject.getProperty(scope, "createObject"); create.call(cx, scope, null, new Object[]{count, strings, ints}); }
@Benchmark @SuppressWarnings("unused") void accessFields(int count) { Function create = (Function)ScriptableObject.getProperty(scope, "createObject"); Object o = create.call(cx, scope, null, new Object[]{1, strings, ints}); Function access = (Function)ScriptableObject.getProperty(scope, "accessObject"); access.call(cx, scope, null, new Object[] {count, o, strings, ints}); }
@Benchmark @SuppressWarnings("unused") void iterateFields(long count) { Function create = (Function)ScriptableObject.getProperty(scope, "createObject"); Object o = create.call(cx, scope, null, new Object[]{1, strings, ints}); Function iterate = (Function)ScriptableObject.getProperty(scope, "iterateObject"); iterate.call(cx, scope, null, new Object[] {count, o}); }
@Benchmark @SuppressWarnings("unused") void ownKeysFields(long count) { Function create = (Function)ScriptableObject.getProperty(scope, "createObject"); Object o = create.call(cx, scope, null, new Object[]{1, strings, ints}); Function iterate = (Function)ScriptableObject.getProperty(scope, "iterateOwnKeysObject"); iterate.call(cx, scope, null, new Object[] {count, o}); }
@Benchmark @SuppressWarnings("unused") void deleteFields(int count) { Function create = (Function)ScriptableObject.getProperty(scope, "createObject"); Object o = create.call(cx, scope, null, new Object[]{1, strings, ints}); Function delete = (Function)ScriptableObject.getProperty(scope, "deleteObject"); delete.call(cx, scope, null, new Object[] {count, o, strings, ints}); }
@Override public void transform(final InputStream content, final Path transformation, final OutputStream result) throws TransformationException, IOException { try { final Context context = Context.enter(); context.setOptimizationLevel(OPTIMIZATION_LEVEL); context.setLanguageVersion(LANGUAGE_VERSION); final Scriptable scope = context.initStandardObjects(); //read in the content final Object jsonObj = parseJson(context, scope, content); //load the javascript with the transform function try(final Reader reader = Files.newBufferedReader(transformation, UTF_8)) { context.evaluateReader(scope, reader, transformation.getFileName().toString(), 1, null); } final Object fnTransformObj = scope.get("transform", scope); if(!(fnTransformObj instanceof Function)) { throw new TransformationException("Function `transform` is not defined!"); } else { final Object functionArgs[] = { jsonObj }; final Function fnTransform = (Function)fnTransformObj; final Object resultObj = fnTransform.call(context, scope, scope, functionArgs); final String jsonResult = (String)NativeJSON.stringify(context, scope, resultObj, null, null); final char buf[] = new char[4096]; int read = -1; try(final Reader jsonReader = new StringReader(jsonResult); final Writer writer = new OutputStreamWriter(result)) { while((read = jsonReader.read(buf)) > -1) { writer.write(buf, 0, read); } } } } finally { Context.exit(); } }
private void handleEvent (final Event evt) { final String fName = evt.key; final Object[] args = (Object[])evt.data; // Find function. final Object fObject = sharedScope.get(fName, sharedScope); if (!(fObject instanceof Function)) { // No function. System.err.println("No function: " + fName + "()"); return; } // Extend scope for function call. final Scriptable scope = context.newObject(sharedScope); scope.setPrototype(sharedScope); scope.setParentScope(null); // Invoke function. final Object result = ((Function)fObject).call(context, scope, scope, args); System.out.println("Script: " + context.toString(result)); }
private boolean validateJson(JSONObject jsFunction, JSONObject requestJsonObject, JSONObject errorMessage) { String code = jsFunction.getString("#text"); String functionName = jsFunction.getString("@name"); if (jsFunction.has("@language")) { String language = jsFunction.getString("@language"); if ("groovy".equalsIgnoreCase(language)) { GroovyCodeExecutionManager executionManager = new GroovyCodeExecutionManager(code, functionName, requestJsonObject, errorMessage); return executionManager.executeGroovy(); } } try { Context context = Context.enter(); ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, code, functionName, 1, null); Function function = (Function) scope.get(functionName, scope); Object result = function.call(context, scope, scope, new Object[]{requestJsonObject.toString(), errorMessage.toString()}); String returnErrorMessage = (String) Context.jsToJava(result, String.class); JSONObject actualMessage = JSONObject.fromObject(returnErrorMessage); if (!actualMessage.isEmpty()) { errorMessage.accumulate("result", actualMessage); return false; } } catch (Exception unknownException) { logger.error("Error occurred", unknownException); } finally { Context.exit(); } return true; }
/** * Overriden Rhino method. */ public Object get(String name, Scriptable start) { Object method = super.get(name, start); if (name.equals(ADD_NAME)) { // prevent creating a Map for all JavaScript objects // when we need it only from time to time... method = new FunctionAddProxy(interpreter, (Function)method, initMap()); } else if (name.equals(REMOVE_NAME)) { // prevent creating a Map for all JavaScript objects // when we need it only from time to time... method = new FunctionRemoveProxy ((Function)method, initMap()); } else if (name.equals(ADDNS_NAME)) { method = new FunctionAddNSProxy(interpreter, (Function) method, initMap()); } else if (name.equals(REMOVENS_NAME)) { method = new FunctionRemoveNSProxy((Function) method, initMap()); } return method; }
/** * Wraps the 'setInterval' methods of the Window interface. */ public static Object setInterval(Context cx, Scriptable thisObj, Object[] args, Function funObj) { int len = args.length; WindowWrapper ww = (WindowWrapper)thisObj; Window window = ww.window; if (len < 2) { throw Context.reportRuntimeError("invalid argument count"); } long to = ((Long)Context.jsToJava(args[1], Long.TYPE)).longValue(); if (args[0] instanceof Function) { RhinoInterpreter interp = (RhinoInterpreter)window.getInterpreter(); FunctionWrapper fw; fw = new FunctionWrapper(interp, (Function)args[0], EMPTY_ARGUMENTS); return Context.toObject(window.setInterval(fw, to), thisObj); } String script = (String)Context.jsToJava(args[0], String.class); return Context.toObject(window.setInterval(script, to), thisObj); }
/** * Wraps the 'setTimeout' methods of the Window interface. */ public static Object setTimeout(Context cx, Scriptable thisObj, Object[] args, Function funObj) { int len = args.length; WindowWrapper ww = (WindowWrapper)thisObj; Window window = ww.window; if (len < 2) { throw Context.reportRuntimeError("invalid argument count"); } long to = ((Long)Context.jsToJava(args[1], Long.TYPE)).longValue(); if (args[0] instanceof Function) { RhinoInterpreter interp = (RhinoInterpreter)window.getInterpreter(); FunctionWrapper fw; fw = new FunctionWrapper(interp, (Function)args[0], EMPTY_ARGUMENTS); return Context.toObject(window.setTimeout(fw, to), thisObj); } String script = (String)Context.jsToJava(args[0], String.class); return Context.toObject(window.setTimeout(script, to), thisObj); }
/** * Wraps the 'printNode' method of the Window interface. */ public static Object printNode(Context cx, Scriptable thisObj, final Object[] args, Function funObj) { if (args.length != 1) { throw Context.reportRuntimeError("invalid argument count"); } WindowWrapper ww = (WindowWrapper)thisObj; final Window window = ww.window; AccessControlContext acc = ((RhinoInterpreter)window.getInterpreter()).getAccessControlContext(); Object ret = AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return window.printNode ((Node) Context.jsToJava(args[0], Node.class)); } }, acc); return Context.toString(ret); }
@JsScriptFuntion public static Object print(Context cx, Scriptable thisObj, Object[] args, Function funObj) { PrintStream out = System.out; for (int i = 0; i < args.length; i++) { if (i > 0) { out.print(" "); } // Convert the arbitrary JavaScript value into a string form. String s = Context.toString(args[i]); out.print(args[i]); } out.println(); return Context.getUndefinedValue(); }
public static int jsFunction_SetParameterValues(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Cpe _this = (Cpe) thisObj; SetParameterValues msg_in = new SetParameterValues(); Scriptable params = (Scriptable) args[0]; if (args.length > 1) { msg_in.key = (String) args[1]; } // int l = (int)params.getLength(); int l = (int) params.getIds().length; for (int i = 0; i < l; i++) { Scriptable nv = (Scriptable) params.get(i, params); String n = (String) nv.get("name", nv); Object ov = nv.get("value", nv); String v = ov.toString(); Object ot = nv.get("type", nv); if (ot.equals(UniqueTag.NOT_FOUND)) { msg_in.AddValue(n, v); } else { msg_in.AddValue(n, v, (String) ot); } } SetParameterValuesResponse msg_out = (SetParameterValuesResponse) _this.Call(msg_in); return msg_out.Status; }
public static void jsFunction_SetParameterAttributes(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Cpe _this = (Cpe) thisObj; //NativeArray attrs = (NativeArray)args[0]; Scriptable attrs = (Scriptable) args[0]; SetParameterAttributes msg_in = new SetParameterAttributes(); // int c = (int)attrs.getLength(); int c = (int) attrs.getIds().length; for (int i = 0; i < c; i++) { // NativeObject o = (NativeObject)attrs.get(i, attrs); Scriptable o = (Scriptable) attrs.get(i, attrs); // NativeArray acl = (NativeArray)o.get("AccessList", o); Scriptable acl = (Scriptable) o.get("AccessList", o); String[] sacl = toStringArray(acl); String Name = (String) o.get("Name", o); boolean NotificationChange = (Boolean) o.get("NotificationChange", o); // int Notification = ((Double) o.get("Notification", o)).intValue(); int Notification = Object2Int(o.get("Notification", o)); boolean AccessListChange = (Boolean) o.get("AccessListChange", o); msg_in.AddAttribute(Name, NotificationChange, Notification, AccessListChange, sacl); } //SetParameterAttributesResponse msg_out = (SetParameterAttributesResponse) _this.Call(msg_in); }
public static Scriptable jsFunction_Upload(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Cpe _this = (Cpe) thisObj; Upload msg_in = new Upload(); msg_in.CommandKey = _this.lastCommandKey = (String) args[0]; msg_in.FileType = (String) args[1]; msg_in.URL = (String) args[2]; msg_in.Username = (String) args[3]; msg_in.Password = (String) args[4]; msg_in.DelaySeconds = Object2Int(args[5]); UploadResponse msg_out = (UploadResponse) _this.Call(msg_in); Scriptable r = cx.newObject(thisObj); r.put("StartTime", r, msg_out.StartTime); r.put("CompleteTime", r, msg_out.CompleteTime); r.put("Status", r, msg_out.Status); return r; }
public static Scriptable jsFunction_GetOptions(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Cpe _this = (Cpe) thisObj; GetOptions msg_in = new GetOptions(); msg_in.OptionName = (String) args[0]; GetOptionsResponse msg_out = (GetOptionsResponse) _this.Call(msg_in); Scriptable ra = cx.newArray(thisObj, msg_out.OptionList.size()); Iterator<OptionStruct> it = msg_out.OptionList.iterator(); int i = 0; while (it.hasNext()) { OptionStruct e = it.next(); Scriptable o = cx.newObject(thisObj); o.put("OptionName", o, e.OptionName); o.put("VoucherSN", o, e.VoucherSN); o.put("State", o, e.State); o.put("Mode", o, e.Mode); o.put("StartDate", o, e.StartDate); o.put("ExpirationDate", o, e.ExpirationDate); o.put("IsTransferable", o, e.IsTransferable); ra.put(i++, ra, o); } return ra; }
public static void jsFunction_SyncParameterValues(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Cpe _this = (Cpe) thisObj; Scriptable vars = (Scriptable) args[0]; int l = (int) vars.getIds().length; Properties p = new Properties(); for (int i = 0; i < l; i++) { Object o = vars.get(i, vars); if (o instanceof String) { String[] sa = ((String) o).split("="); p.setProperty(sa[0], sa[1]); } else if (o instanceof Scriptable) { Scriptable v = (Scriptable) o; p.setProperty((String) v.get("Name", v), (String) v.get("Value", v)); } } _this.cpe.SyncParameterValues(p); }
public CpeDb(Context cx, Function ctor, HostsLocal host) throws IOException { this.host = host; Properties p = new Properties(); byte[] bp = host.getProps(); if (bp != null) { p.load(new ByteArrayInputStream(bp)); if (p != null) { for (Entry e : p.entrySet()) { String k = (String) e.getKey(); k.replace('.', '_'); //System.out.println ("PROPSAS: "+e.getKey()+"="+e.getValue()); put(k, this, e.getValue()); } } } }
public static void jsFunction_Save(Context cx, Scriptable thisObj, Object[] args, Function funObj) { CpeDb _this = (CpeDb) thisObj; Object[] ids = _this.getIds(); /* Properties p = new Properties (); for (Object oid : ids) { String id = (String)oid; p.put(id, (String)CpeDb.getProperty(thisObj, id)); } _this.host.setProps(p); */ String props = ""; for (Object oid : ids) { String id = (String) oid; props += id + "=" + (String) CpeDb.getProperty(thisObj, id) + "\n"; } _this.host.setProps(props.getBytes()); }
public static Object call(Context cx, Scriptable thisObj, Object[] args, Function funObj) { if (args.length < 1) { ((Script) thisObj).log(Level.WARNING, "call function with zero args"); return null; } ScriptLocal script; try { script = Ejb.lookupScriptBean((String) args[0]); /* Object [] newargs = null; if (args.length > 1) { newargs = new Object[args.length - 1]; System.arraycopy(args, 1, newargs, 0, args.length - 1); Scriptable a = cx.newArray(thisObj, newargs); thisObj.put("arguments", thisObj, newargs); } */ return cx.evaluateString(thisObj, new String(script.getScript()), (String) args[0], 1, null); } catch (FinderException ex) { ((Script) thisObj).log(Level.SEVERE, "CALL: function " + args[0] + " not found."); } return null; }
public String callFunction(String name) { synchronized(scriptLock) { if(scope == null) { return "Null scope."; } Object obj = null; try { obj = scope.get(name, scope); Function fct = (Function)obj; if(fct == null) { return "Function not found: " + name; } fct.call(cx, scope, scope, new Object[] {}); } catch(ClassCastException cce) { return "Function " + name + " is of type " + obj; } return null; } }