org.mozilla.javascript.ScriptableObject Java Examples
The following examples show how to use
org.mozilla.javascript.ScriptableObject.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavascriptTemplate.java From manifold with Apache License 2.0 | 6 votes |
@SuppressWarnings("unused") public static String renderToStringImpl( ScriptableObject scope, JSTNode templateNode, Object... args ) { try { //make argument list including the raw string list Object[] argsWithStrings = Arrays.copyOf( args, args.length + 1 ); List rawStrings = templateNode.getChildren( RawStringNode.class ) .stream() .map( node -> node.genCode() ) .collect( Collectors.toList() ); argsWithStrings[argsWithStrings.length - 1] = rawStrings; Function renderToString = (Function)scope.get( "renderToString", scope ); return (String)renderToString.call( Context.getCurrentContext(), scope, scope, argsWithStrings ); } catch( Exception e ) { throw new RuntimeException( e ); } }
Example #2
Source File: CustomSetterAcceptNullScriptableTest.java From astor with GNU General Public License v2.0 | 6 votes |
public void testSetNullForScriptableSetter() throws Exception { final String scriptCode = "foo.myProp = new Foo2();\n" + "foo.myProp = null;"; final ContextFactory factory = new ContextFactory(); final Context cx = factory.enterContext(); try { final ScriptableObject topScope = cx.initStandardObjects(); final Foo foo = new Foo(); // define custom setter method final Method setMyPropMethod = Foo.class.getMethod("setMyProp", Foo2.class); foo.defineProperty("myProp", null, null, setMyPropMethod, ScriptableObject.EMPTY); topScope.put("foo", topScope, foo); ScriptableObject.defineClass(topScope, Foo2.class); cx.evaluateString(topScope, scriptCode, "myScript", 1, null); } finally { Context.exit(); } }
Example #3
Source File: BaseScript.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
protected void executeScript( final Map<String, Object> params ) { final Context cx = Context.getCurrentContext(); // env.js has methods that pass the 64k Java limit, so we can't compile // to bytecode. Interpreter mode to the rescue! cx.setOptimizationLevel( -1 ); cx.setLanguageVersion( Context.VERSION_1_7 ); final Object wrappedParams; if ( params != null ) { wrappedParams = Context.javaToJS( params, scope ); } else { wrappedParams = Context.javaToJS( new HashMap<String, Object>(), scope ); } try { ScriptableObject.defineProperty( scope, "params", wrappedParams, 0 ); cx.evaluateReader( scope, new FileReader( source ), this.source, 1, null ); } catch ( IOException ex ) { logger.error( "Failed to read " + source + ": " + ex.toString() ); } }
Example #4
Source File: NativeRegExp.java From JsDroidCmd with Mozilla Public License 2.0 | 6 votes |
public static void init(Context cx, Scriptable scope, boolean sealed) { NativeRegExp proto = new NativeRegExp(); proto.re = compileRE(cx, "", null, false); proto.activatePrototypeMap(MAX_PROTOTYPE_ID); proto.setParentScope(scope); proto.setPrototype(getObjectPrototype(scope)); NativeRegExpCtor ctor = new NativeRegExpCtor(); // Bug #324006: ECMA-262 15.10.6.1 says "The initial value of // RegExp.prototype.constructor is the builtin RegExp constructor." proto.defineProperty("constructor", ctor, ScriptableObject.DONTENUM); ScriptRuntime.setFunctionProtoAndParent(ctor, scope); ctor.setImmunePrototypeProperty(proto); if (sealed) { proto.sealObject(); ctor.sealObject(); } defineProperty(scope, "RegExp", ctor, ScriptableObject.DONTENUM); }
Example #5
Source File: Bug782363Test.java From rhino-android with Apache License 2.0 | 6 votes |
private void test(int variables) { double expected = (variables * (variables - 1)) / 2d; StringBuilder sb = new StringBuilder(); sb.append("function F (){\n"); for (int i = 0; i < variables; ++i) { sb.append("const x_").append(i).append("=").append(i).append(";"); } sb.append("return 0"); for (int i = 0; i < variables; ++i) { sb.append("+").append("x_").append(i); } sb.append("}; F()"); ScriptableObject scope = cx.initStandardObjects(); Object ret = cx.evaluateString(scope, sb.toString(), "<eval>", 1, null); assertTrue(ret instanceof Number); assertEquals(expected, ((Number) ret).doubleValue(), 0); }
Example #6
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 6 votes |
@Test public void test_setElem() { String fn = "function test(){ ''['foo'] = '_' }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { String code = ""; code += "String.prototype.c = 0;"; code += "Object.defineProperty(String.prototype, 'foo', {" + " set: function(v){ this.__proto__.c++ }})"; eval(cx, scope1, code); eval(cx, scope2, code); eval(cx, scope2, "test()"); eval(cx, scope1, "scope2.test()"); eval(cx, scope1, "scope2.test.call(null)"); eval(cx, scope1, "var t=scope2.test; t()"); eval(cx, scope1, "var t=scope2.test; t.call(null)"); assertTRUE(eval(cx, scope1, "0 == String.prototype.c")); assertTRUE(eval(cx, scope2, "5 == String.prototype.c")); } })); }
Example #7
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 6 votes |
@Test public void test_getProp() { String fn = "function test(){ return ''.foo }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { eval(cx, scope1, "String.prototype.foo = 'scope1'"); eval(cx, scope2, "String.prototype.foo = 'scope2'"); assertEquals("scope2", eval(cx, scope2, "test()")); assertEquals("scope2", eval(cx, scope1, "scope2.test()")); assertEquals("scope2", eval(cx, scope1, "scope2.test.call(null)")); assertEquals("scope2", eval(cx, scope1, "var t=scope2.test; t()")); assertEquals("scope2", eval(cx, scope1, "var t=scope2.test; t.call(null)")); } })); }
Example #8
Source File: Shell.java From joinery with GNU General Public License v3.0 | 6 votes |
@Override public void complete(final LineReader reader, final ParsedLine line, final List<Candidate> candidates) { final String expr = line.word().substring(0, line.wordCursor()); final int dot = expr.lastIndexOf('.') + 1; if (dot > 1) { final String sym = expr.substring(0, dot - 1); final Object value = get(sym, Repl.this); if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)value; final Object[] ids = so.getAllIds(); for (final Object id : ids) { final String candidate = sym + "." + id; candidates.add(new Candidate( candidate, candidate, null, null, null, null, false )); } } } }
Example #9
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
private <T> T readArray(final String arrayName, final int position, final Scope scope, final Scriptable start, final Class<T> type) throws SemanticError { if (start == null) { throw new SemanticError("no scope '" + scope + "' present to read '" + arrayName + "'"); } final Scriptable targetScope = getFullScope(topmostScope, arrayName); if (targetScope == null) { throw new SemanticError("'" + arrayName + "' not found"); } if (!ScriptableObject.hasProperty(targetScope, position)) { throw new SemanticError("'" + arrayName + "' has no position " + position); } final Object value = ScriptableObject .getProperty(targetScope, position); if (value == getUndefinedValue()) { return null; } @SuppressWarnings("unchecked") final T t = (T) Context.jsToJava(value, type); return t; }
Example #10
Source File: DataSetIterator.java From birt with Eclipse Public License 1.0 | 6 votes |
/** * * @param session * @param query * @param appContext * @throws AdapterException */ private void executeQuery( DataRequestSessionImpl session, IQueryDefinition query, Map appContext ) throws AdapterException { try { Scriptable scope = session.getScope( ); TempDateTransformer tt = new TempDateTransformer( session.getDataSessionContext( ) .getDataEngineContext( ) .getLocale( ) ); ScriptableObject.putProperty( scope, tt.getClassName( ), tt ); queryResult = session.prepare( query, appContext ).execute( scope ); this.it = queryResult.getResultIterator( ); } catch ( BirtException e ) { throw new AdapterException( e.getLocalizedMessage( ), e ); } }
Example #11
Source File: ApplyOnPrimitiveNumberTest.java From rhino-android with Apache License 2.0 | 6 votes |
public void testIt() { final String script = "var fn = function() { return this; }\n" + "fn.apply(1)"; final ContextAction action = new ContextAction() { public Object run(final Context _cx) { final ScriptableObject scope = _cx.initStandardObjects(); final Object result = _cx.evaluateString(scope, script, "test script", 0, null); assertEquals("object", ScriptRuntime.typeof(result)); assertEquals("1", Context.toString(result)); return null; } }; Utils.runWithAllOptimizationLevels(action); }
Example #12
Source File: ComplianceTest.java From astor with GNU General Public License v2.0 | 6 votes |
private static Test createTest(final File testDir, final String name) { return new TestCase(name) { @Override public int countTestCases() { return 1; } @Override public void runBare() throws Throwable { final Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); final Scriptable scope = cx.initStandardObjects(); ScriptableObject.putProperty(scope, "print", new Print(scope)); createRequire(testDir, cx, scope).requireMain(cx, "program"); } finally { Context.exit(); } } }; }
Example #13
Source File: RhinoClientScopeSynchronizer.java From elasticshell with Apache License 2.0 | 6 votes |
@Override protected void registerIndexAndTypes(InternalIndexClient indexClient, InternalTypeClient... typeClients) { //We are in a different thread, therefore we cannot rely on the current shell context but we need to create a new one Context context = Context.enter(); try { //register index NativeJavaObject indexNativeJavaObject = new RhinoCustomNativeJavaObject(shellNativeClient.getParentScope(), indexClient, InternalIndexClient.class); indexNativeJavaObject.setPrototype(context.newObject(shellNativeClient.getParentScope())); if (typeClients != null) { //register types for (InternalTypeClient typeClient : typeClients) { NativeJavaObject typeNativeJavaObject = new RhinoCustomNativeJavaObject(shellNativeClient.getParentScope(), typeClient, InternalTypeClient.class); ScriptableObject.putProperty(indexNativeJavaObject, typeClient.typeName(), typeNativeJavaObject); } } logger.trace("Adding index {} to shell native client", indexClient.indexName()); ScriptableObject.putProperty(shellNativeClient, indexClient.indexName(), indexNativeJavaObject); } finally { Context.exit(); } }
Example #14
Source File: ScriptNode.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Extract a map of properties from a scriptable object (generally an associative array) * * @param scriptable The scriptable object to extract name/value pairs from. * @param map The map to add the converted name/value pairs to. */ private void extractScriptableProperties(ScriptableObject scriptable, Map<QName, Serializable> map) { // we need to get all the keys to the properties provided // and convert them to a Map of QName to Serializable objects Object[] propIds = scriptable.getIds(); for (int i = 0; i < propIds.length; i++) { // work on each key in turn Object propId = propIds[i]; // we are only interested in keys that are formed of Strings i.e. QName.toString() if (propId instanceof String) { // get the value out for the specified key - it must be Serializable String key = (String)propId; Object value = scriptable.get(key, scriptable); if (value instanceof Serializable) { value = getValueConverter().convertValueForRepo((Serializable)value); map.put(createQName(key), (Serializable)value); } } } }
Example #15
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
/** * Retrieves the scope identified by the variable's full name. * @param scope the scope to start searching * @param name the fully qualified name of a variable * @return found scope, {@code null} if no such scope exists * @since 0.7.7 */ private Scriptable getScope(final Scriptable scope, final String name) { int dotPos = name.indexOf('.'); if (dotPos >= 0) { final String prefix = name.substring(0, dotPos); final String suffix = name.substring(dotPos + 1); final Object value; if (ScriptableObject.hasProperty(scope, prefix)) { value = ScriptableObject.getProperty(scope, prefix); } else { return null; } if (value instanceof Scriptable) { final Scriptable subscope = (Scriptable) value; return getScope(subscope, suffix); } else { return null; } } else { return scope; } }
Example #16
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
public boolean existsVariable(final String variableName, final Scope scope, final Scriptable start) { if (start == null) { return false; } final Scriptable targetScope = getScope(start, variableName); if (targetScope == null) { return false; } final String property; int dotPos = variableName.lastIndexOf('.'); if (dotPos >= 0) { property = variableName.substring(dotPos + 1); } else { property = variableName; } return ScriptableObject.hasProperty(targetScope, property); }
Example #17
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
/** * Transforms the given {@link ScriptableObject} into a JSON object. * * @param object * the object to serialize * @return JSON object * @since 0.7.5 */ @SuppressWarnings("unchecked") private static JSONObject toJSONObject(final Scriptable object) { if (object == null) { return null; } final Object[] ids = ScriptableObject.getPropertyIds(object); JSONObject json = new JSONObject(); for (Object id : ids) { final String key = id.toString(); Object value = object.get(key, object); if (value instanceof ScriptableObject) { final ScriptableObject scriptable = (ScriptableObject) value; final JSONObject subvalue = toJSONObject(scriptable); json.put(key, subvalue); } else { json.put(key, value); } } return json; }
Example #18
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 6 votes |
@Test public void test_setPropOp2() { String fn = "function test(){ return ''.foo += '_' }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { eval(cx, scope1, "String.prototype.foo = 'scope1'"); eval(cx, scope2, "String.prototype.foo = 'scope2'"); assertEquals("scope2_", eval(cx, scope2, "test()")); assertEquals("scope2_", eval(cx, scope1, "scope2.test()")); assertEquals("scope2_", eval(cx, scope1, "scope2.test.call(null)")); assertEquals("scope2_", eval(cx, scope1, "var t=scope2.test; t()")); assertEquals("scope2_", eval(cx, scope1, "var t=scope2.test; t.call(null)")); } })); }
Example #19
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 6 votes |
@Test public void test_setElemOp1() { String fn = "function test(){ return ''['foo'] += '_' }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { String code = ""; code += "String.prototype.c = 0;"; code += "Object.defineProperty(String.prototype, 'foo', {" + " set: function(v){ this.__proto__.c++ }})"; eval(cx, scope1, code); eval(cx, scope2, code); eval(cx, scope2, "test()"); eval(cx, scope1, "scope2.test()"); eval(cx, scope1, "scope2.test.call(null)"); eval(cx, scope1, "var t=scope2.test; t()"); eval(cx, scope1, "var t=scope2.test; t.call(null)"); assertTRUE(eval(cx, scope1, "0 == String.prototype.c")); assertTRUE(eval(cx, scope2, "5 == String.prototype.c")); } })); }
Example #20
Source File: EnvironmentChecksTest.java From caja with Apache License 2.0 | 6 votes |
public final void testEnvironmentData() throws Exception { Scriptable s = (Scriptable) RhinoTestBed.runJs( new RhinoExecutor.Input( // TODO: make an ASCII-art Rhino. "var navigator = { userAgent: 'Rhino Rhino Rhino' };", "rhino-env"), new RhinoExecutor.Input(getClass(), "environment-checks.js"), new RhinoExecutor.Input("env", getName()) ); Map<String, Object> env = Maps.newHashMap(); for (Object key : ScriptableObject.getPropertyIds(s)) { String code = "" + key; env.put(EnvironmentData.normJs(code, mq), s.get(code, s)); } for (EnvironmentDatum datum : EnvironmentDatum.values()) { assertTrue(datum.name(), env.containsKey(datum.getCode())); System.err.println(datum + " = " + env.get(datum.getCode())); } assertEquals( "Rhino Rhino Rhino", env.get(EnvironmentDatum.NAV_USER_AGENT.getCode())); }
Example #21
Source File: Bug448816Test.java From astor with GNU General Public License v2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override protected void setUp() { // set up a reference map reference = new LinkedHashMap<Object, Object>(); reference.put("a", "a"); reference.put("b", Boolean.TRUE); reference.put("c", new HashMap<Object, Object>()); reference.put(new Integer(1), new Integer(42)); // get a js object as map Context context = Context.enter(); ScriptableObject scope = context.initStandardObjects(); map = (Map<Object, Object>) context.evaluateString(scope, "({ a: 'a', b: true, c: new java.util.HashMap(), 1: 42});", "testsrc", 1, null); Context.exit(); }
Example #22
Source File: Util.java From birt with Eclipse Public License 1.0 | 6 votes |
public CachedResultSet getDefaultSubQueryCachedResultSet( ) throws Exception { IQueryDefinition queryDefn = getDefaultQueryDefnWithSubQuery( this.dataSet.getName( ) ); ResultIterator resultIterator = (ResultIterator) executeQuery( queryDefn ); resultIterator.next( ); Context cx = Context.enter( ); ResultIterator subIterator; try { ScriptableObject scope = cx.initStandardObjects( ); subIterator = (ResultIterator) resultIterator.getSecondaryIterator( "IAMTEST", //$NON-NLS-1$ scope ); } catch ( DataException e ) { throw ( e ); } finally { Context.exit( ); } return (CachedResultSet) subIterator.getOdiResult( ); }
Example #23
Source File: Bug482203Test.java From astor with GNU General Public License v2.0 | 6 votes |
public void testJsApi() throws Exception { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); Script script = cx.compileReader(new InputStreamReader( Bug482203Test.class.getResourceAsStream("Bug482203.js")), "", 1, null); Scriptable scope = cx.initStandardObjects(); script.exec(cx, scope); int counter = 0; for(;;) { Object cont = ScriptableObject.getProperty(scope, "c"); if(cont == null) { break; } counter++; ((Callable)cont).call(cx, scope, scope, new Object[] { null }); } assertEquals(counter, 5); assertEquals(Double.valueOf(3), ScriptableObject.getProperty(scope, "result")); } finally { Context.exit(); } }
Example #24
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 5 votes |
@Test public void test_getPropNoWarn2() { String fn = "function test(){ if (''.foo) return true; return false; }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { eval(cx, scope2, "String.prototype.foo = 'scope2'"); assertTRUE(eval(cx, scope2, "test()")); assertTRUE(eval(cx, scope1, "scope2.test()")); assertTRUE(eval(cx, scope1, "scope2.test.call(null)")); assertTRUE(eval(cx, scope1, "var t=scope2.test; t()")); assertTRUE(eval(cx, scope1, "var t=scope2.test; t.call(null)")); } })); }
Example #25
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
private int updateVariable(final String variableName, final Object newValue, final Scope scope, final Scriptable start) { if (start == null) { return ERROR_SCOPE_NOT_FOUND; } final Scriptable subscope = getAndCreateScope(start, variableName); final String property; int dotPos = variableName.lastIndexOf('.'); if (dotPos >= 0) { property = variableName.substring(dotPos + 1); } else { property = variableName; } if (!ScriptableObject.hasProperty(subscope, property)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("'" + variableName + "' not found"); } return ERROR_VARIABLE_NOT_FOUND; } final Object jsValue = Context.javaToJS(newValue, subscope); ScriptableObject.putProperty(subscope, property, jsValue); if (LOGGER.isDebugEnabled()) { final String json = toString(jsValue); if (scope == null) { LOGGER.debug("set '" + variableName + "' in scope '" + getScope(subscope) + "' to '" + json + "'"); } else { LOGGER.debug("set '" + variableName + "' in scope '" + getScope(subscope) + "' to '" + json + "'"); } } return 0; }
Example #26
Source File: Main.java From astor with GNU General Public License v2.0 | 5 votes |
static void processFiles(Context cx, String[] args) { // define "arguments" array in the top-level object: // need to allocate new array since newArray requires instances // of exactly Object[], not ObjectSubclass[] Object[] array = new Object[args.length]; System.arraycopy(args, 0, array, 0, args.length); Scriptable argsObj = cx.newArray(global, array); global.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); for (String file: fileList) { try { processSource(cx, file); } catch (IOException ioex) { Context.reportError(ToolErrorReporter.getMessage( "msg.couldnt.read.source", file, ioex.getMessage())); exitCode = EXITCODE_FILE_NOT_FOUND; } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); Context.reportError(msg); exitCode = EXITCODE_RUNTIME_ERROR; } } }
Example #27
Source File: SharedScope.java From manifold with Apache License 2.0 | 5 votes |
/** * Static scope applies to a program or class and is analogous to Java's Class scope. An instance scope is created * when an object is constructed via Context.newObject(), which is called from the manifold generated constructor for * a js class. */ static ScriptableObject newStaticScope() { ScriptableObject sharedGlobalScope = SharedScope.get(); ScriptableObject programScope = (ScriptableObject)Context.getCurrentContext().newObject( sharedGlobalScope ); programScope.setPrototype( sharedGlobalScope ); programScope.setParentScope( null ); return programScope; }
Example #28
Source File: Bug783797Test.java From rhino-android with Apache License 2.0 | 5 votes |
@Test public void test_StringLiteralProtoNested() { String fn = "function test(){ return (function(){ return ''.__proto__ })() }"; runWithAllOptimizationLevels(action(fn, new Action() { public void run(Context cx, ScriptableObject scope1, ScriptableObject scope2) { assertTRUE(eval(cx, scope2, "String.prototype === test()")); assertTRUE(eval(cx, scope2, "String.prototype === test.call(null)")); assertFALSE(eval(cx, scope1, "String.prototype === scope2.test()")); assertFALSE(eval(cx, scope1, "String.prototype === scope2.test.call(null)")); assertFALSE(eval(cx, scope1, "var t=scope2.test; String.prototype === t()")); assertFALSE(eval(cx, scope1, "var t=scope2.test; String.prototype === t.call(null)")); } })); }
Example #29
Source File: JsRuntime.java From manifold with Apache License 2.0 | 5 votes |
@SuppressWarnings("unused") public static Object evaluate( String source, String url ) { ScriptableObject scope = SharedScope.newStaticScope(); Parser parser = new Parser( new Tokenizer( source, url ) ); Node programNode = parser.parse(); return Context.getCurrentContext().evaluateString( scope, programNode.genCode(), "evaluate_js", 1, null ); }
Example #30
Source File: JsRuntime.java From manifold with Apache License 2.0 | 5 votes |
@SuppressWarnings("unused") public static <T> T invokeProg( ScriptableObject scope, String func, Object... args ) { try { Function renderToString = (Function)scope.get( func, scope ); //noinspection unchecked return (T)renderToString.call( Context.getCurrentContext(), scope, scope, args ); } catch( Exception e ) { throw new RuntimeException( e ); } }