Java Code Examples for org.mozilla.javascript.Context#newObject()
The following examples show how to use
org.mozilla.javascript.Context#newObject() .
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: JsTestsBase.java From astor with GNU General Public License v2.0 | 6 votes |
public void runJsTest(Context cx, Scriptable shared, String name, String source) { // create a lightweight top-level scope Scriptable scope = cx.newObject(shared); scope.setPrototype(shared); System.out.print(name + ": "); Object result; try { result = cx.evaluateString(scope, source, "jstest input", 1, null); } catch (RuntimeException e) { System.out.println("FAILED"); throw e; } assertTrue(result != null); assertTrue("success".equals(result)); System.out.println("passed"); }
Example 2
Source File: JsTestsBase.java From rhino-android with Apache License 2.0 | 6 votes |
public void runJsTest(Context cx, Scriptable shared, String name, String source) { // create a lightweight top-level scope Scriptable scope = cx.newObject(shared); scope.setPrototype(shared); System.out.print(name + ": "); Object result; try { result = cx.evaluateString(scope, source, "jstest input: " + name, 1, null); } catch (RuntimeException e) { e.printStackTrace(System.err); System.out.println("FAILED"); throw e; } assertTrue(result != null); assertTrue("success".equals(result)); System.out.println("passed"); }
Example 3
Source File: DocLitBareClientTest.java From cxf with Apache License 2.0 | 6 votes |
public static Scriptable testBean1ToJS(JavascriptTestUtilities testUtilities, Context context, TestBean1 b1) { if (b1 == null) { return null; // black is always in fashion. (Really, we can be called with a null). } Scriptable rv = context.newObject(testUtilities.getRhinoScope(), "org_apache_cxf_javascript_testns_testBean1"); testUtilities.rhinoCallMethod(rv, "setStringItem", testUtilities.javaToJS(b1.stringItem)); testUtilities.rhinoCallMethod(rv, "setIntItem", testUtilities.javaToJS(b1.intItem)); testUtilities.rhinoCallMethod(rv, "setLongItem", testUtilities.javaToJS(b1.longItem)); testUtilities.rhinoCallMethod(rv, "setBase64Item", testUtilities.javaToJS(b1.base64Item)); testUtilities.rhinoCallMethod(rv, "setOptionalIntItem", testUtilities.javaToJS(b1.optionalIntItem)); testUtilities.rhinoCallMethod(rv, "setOptionalIntArrayItem", testUtilities.javaToJS(b1.optionalIntArrayItem)); testUtilities.rhinoCallMethod(rv, "setDoubleItem", testUtilities.javaToJS(b1.doubleItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoItem", testBean2ToJS(testUtilities, context, b1.beanTwoItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoNotRequiredItem", testBean2ToJS(testUtilities, context, b1.beanTwoNotRequiredItem)); return rv; }
Example 4
Source File: ExpressionLanguageJavaScriptImpl.java From oval with Eclipse Public License 2.0 | 6 votes |
@Override public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException { LOG.debug("Evaluating JavaScript expression: {1}", expression); try { final Context ctx = ContextFactory.getGlobal().enterContext(); final Scriptable scope = ctx.newObject(parentScope); scope.setPrototype(parentScope); scope.setParentScope(null); for (final Entry<String, ?> entry : values.entrySet()) { scope.put(entry.getKey(), scope, Context.javaToJS(entry.getValue(), scope)); } final Script expr = expressionCache.get(expression); return expr.exec(ctx, scope); } catch (final EvaluatorException ex) { throw new ExpressionEvaluationException("Evaluating JavaScript expression failed: " + expression, ex); } finally { Context.exit(); } }
Example 5
Source File: JsonExtensionNotificationDataConverter.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
/** * {@inheritDoc} */ @Override public Object convertApplicationLastResult( final List<LastResult> lastresults) throws ConversionException { if (lastresults == null || lastresults.isEmpty()) { return null; } final Context context = Context.enter(); context.setLanguageVersion(Context.VERSION_DEFAULT); final ScriptableObject scope = context.initStandardObjects(); final LastResult lastresult = lastresults.get(0); final Scriptable vxml = context.newObject(scope); ScriptableObject.putProperty(vxml, "utterance", lastresult.getUtterance()); ScriptableObject.putProperty(vxml, "confidence", lastresult.getConfidence()); ScriptableObject.putProperty(vxml, "mode", lastresult.getInputmode()); ScriptableObject.putProperty(vxml, "interpretation", lastresult.getInterpretation()); return toJSON(vxml); }
Example 6
Source File: DocLitWrappedClientTest.java From cxf with Apache License 2.0 | 6 votes |
public static Scriptable testBean1ToJS(JavascriptTestUtilities testUtilities, Context context, TestBean1 b1) { if (b1 == null) { return null; // black is always in fashion. (Really, we can be called with a null). } Scriptable rv = context.newObject(testUtilities.getRhinoScope(), "org_apache_cxf_javascript_testns_testBean1"); testUtilities.rhinoCallMethod(rv, "setStringItem", testUtilities.javaToJS(b1.stringItem)); testUtilities.rhinoCallMethod(rv, "setIntItem", testUtilities.javaToJS(b1.intItem)); testUtilities.rhinoCallMethod(rv, "setLongItem", testUtilities.javaToJS(b1.longItem)); testUtilities.rhinoCallMethod(rv, "setBase64Item", testUtilities.javaToJS(b1.base64Item)); testUtilities.rhinoCallMethod(rv, "setOptionalIntItem", testUtilities.javaToJS(b1.optionalIntItem)); testUtilities.rhinoCallMethod(rv, "setOptionalIntArrayItem", testUtilities.javaToJS(b1.optionalIntArrayItem)); testUtilities.rhinoCallMethod(rv, "setDoubleItem", testUtilities.javaToJS(b1.doubleItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoItem", testBean2ToJS(testUtilities, context, b1.beanTwoItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoNotRequiredItem", testBean2ToJS(testUtilities, context, b1.beanTwoNotRequiredItem)); return rv; }
Example 7
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 6 votes |
private int createArray(final String arrayName, final int dimension, final Scope scope, final Scriptable start) { if (start == null) { return ERROR_SCOPE_NOT_FOUND; } final Scriptable targetScope = getAndCreateScope(start, arrayName); final String name; int dotPos = arrayName.lastIndexOf('.'); if (dotPos >= 0) { name = arrayName.substring(dotPos + 1); } else { name = arrayName; } if (ScriptableObject.hasProperty(targetScope, name)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("'" + arrayName + "' already defined"); } return ERROR_VARIABLE_ALREADY_DEFINED; } final NativeArray array = new NativeArray(dimension); ScriptableObject.putProperty(targetScope, name, array); if (LOGGER.isDebugEnabled()) { LOGGER.debug("created '" + arrayName + "' in scope '" + getScope(targetScope) + "' as an array of " + dimension); } // Fill the array for (int i = 0; i < dimension; i++) { final Context context = getContext(); final Scriptable scriptable = context.newObject(topmostScope); ScriptableObject.putProperty(array, i, scriptable); } return NO_ERROR; }
Example 8
Source File: RPCClientTest.java From cxf with Apache License 2.0 | 6 votes |
public static Scriptable testBean1ToJS(JavascriptTestUtilities testUtilities, Context context, TestBean1 b1) { if (b1 == null) { return null; // black is always in fashion. (Really, we can be called with a null). } Scriptable rv = context.newObject(testUtilities.getRhinoScope(), "org_apache_cxf_javascript_testns_testBean1"); testUtilities.rhinoCallMethod(rv, "setStringItem", testUtilities.javaToJS(b1.stringItem)); testUtilities.rhinoCallMethod(rv, "setIntItem", testUtilities.javaToJS(b1.intItem)); testUtilities.rhinoCallMethod(rv, "setLongItem", testUtilities.javaToJS(b1.longItem)); testUtilities.rhinoCallMethod(rv, "setBase64Item", testUtilities.javaToJS(b1.base64Item)); testUtilities.rhinoCallMethod(rv, "setOptionalIntItem", testUtilities.javaToJS(b1.optionalIntItem)); testUtilities.rhinoCallMethod(rv, "setOptionalIntArrayItem", testUtilities.javaToJS(b1.optionalIntArrayItem)); testUtilities.rhinoCallMethod(rv, "setDoubleItem", testUtilities.javaToJS(b1.doubleItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoItem", testBean2ToJS(testUtilities, context, b1.beanTwoItem)); testUtilities.rhinoCallMethod(rv, "setBeanTwoNotRequiredItem", testBean2ToJS(testUtilities, context, b1.beanTwoNotRequiredItem)); return rv; }
Example 9
Source File: JsSimpleDomNode.java From cxf with Apache License 2.0 | 5 votes |
public static JsSimpleDomNode wrapNode(Scriptable scope, Node node) { if (node == null) { return null; } Context cx = ContextFactory.getGlobal().enterContext(); try { JsSimpleDomNode newObject = (JsSimpleDomNode)cx.newObject(scope, "Node"); newObject.initialize(node, null); return newObject; } finally { Context.exit(); } }
Example 10
Source File: Bug421071Test.java From astor with GNU General Public License v2.0 | 5 votes |
public void run() { Context context = factory.enterContext(); try { // Run each script in its own scope, to keep global variables // defined in each script separate Scriptable threadScope = context.newObject(globalScope); threadScope.setPrototype(globalScope); threadScope.setParentScope(null); script.exec(context, threadScope); } catch (Exception ee) { ee.printStackTrace(); } finally { Context.exit(); } }
Example 11
Source File: Require.java From astor with GNU General Public License v2.0 | 5 votes |
private Scriptable executeModuleScript(Context cx, String id, Scriptable exports, ModuleScript moduleScript, boolean isMain) { final ScriptableObject moduleObject = (ScriptableObject)cx.newObject( nativeScope); URI uri = moduleScript.getUri(); URI base = moduleScript.getBase(); defineReadOnlyProperty(moduleObject, "id", id); if(!sandboxed) { defineReadOnlyProperty(moduleObject, "uri", uri.toString()); } final Scriptable executionScope = new ModuleScope(nativeScope, uri, base); // Set this so it can access the global JS environment objects. // This means we're currently using the "MGN" approach (ModuleScript // with Global Natives) as specified here: // <http://wiki.commonjs.org/wiki/Modules/ProposalForNativeExtension> executionScope.put("exports", executionScope, exports); executionScope.put("module", executionScope, moduleObject); moduleObject.put("exports", moduleObject, exports); install(executionScope); if(isMain) { defineReadOnlyProperty(this, "main", moduleObject); } executeOptionalScript(preExec, cx, executionScope); moduleScript.getScript().exec(cx, executionScope); executeOptionalScript(postExec, cx, executionScope); return ScriptRuntime.toObject(nativeScope, ScriptableObject.getProperty(moduleObject, "exports")); }
Example 12
Source File: DocLitBareClientTest.java From cxf with Apache License 2.0 | 5 votes |
public static Object testBean2ToJS(JavascriptTestUtilities testUtilities, Context context, TestBean2 beanTwoItem) { if (beanTwoItem == null) { return null; } Scriptable rv = context.newObject(testUtilities.getRhinoScope(), "org_apache_cxf_javascript_testns3_testBean2"); testUtilities.rhinoCallMethod(rv, "setStringItem", beanTwoItem.stringItem); return rv; }
Example 13
Source File: NativeTypedArrayView.java From JsDroidCmd with Mozilla Public License 2.0 | 5 votes |
private Object js_subarray(Context cx, Scriptable scope, int s, int e) { int start = (s < 0 ? length + s : s); int end = (e < 0 ? length + e : e); // Clamping behavior as described by the spec. start = Math.max(0, start); end = Math.min(length, end); int len = Math.max(0, (end - start)); int byteOff = Math.min(start * getBytesPerElement(), arrayBuffer.getLength()); return cx.newObject(scope, getClassName(), new Object[]{arrayBuffer, byteOff, len}); }
Example 14
Source File: AbstractScriptHandler.java From birt with Eclipse Public License 1.0 | 5 votes |
/** * Initialize the JavaScript context using given parent scope. * * @param scPrototype * Parent scope object. If it's null, use default scope. */ public final void init( Scriptable scPrototype ) throws ChartException { final Context cx = Context.enter( ); try { if ( scPrototype == null ) // NO PROTOTYPE { // scope = cx.initStandardObjects(); scope = new ImporterTopLevel( cx ); } else { scope = cx.newObject( scPrototype ); scope.setPrototype( scPrototype ); // !don't reset the parent scope here. // scope.setParentScope( null ); } // final Scriptable scopePrevious = scope; // !deprecated, remove this later. use script context instead. // registerExistingScriptableObject( this, "chart" ); //$NON-NLS-1$ // scope = scopePrevious; // RESTORE // !deprecated, remove this later, use logger from script context // instead. // ADD LOGGING CAPABILITIES TO JAVASCRIPT ACCESS final Object oConsole = Context.javaToJS( getLogger( ), scope ); scope.put( "logger", scope, oConsole ); //$NON-NLS-1$ } catch ( RhinoException jsx ) { throw convertException( jsx ); } finally { Context.exit( ); } }
Example 15
Source File: EcmaScriptDataModel.java From JVoiceXML with GNU Lesser General Public License v2.1 | 4 votes |
/** * {@inheritDoc} */ @Override public Object createNewObject() { final Context context = getContext(); return context.newObject(topmostScope); }
Example 16
Source File: Require.java From astor with GNU General Public License v2.0 | 4 votes |
private Scriptable getExportedModuleInterface(Context cx, String id, URI uri, URI base, boolean isMain) { // Check if the requested module is already completely loaded Scriptable exports = exportedModuleInterfaces.get(id); if(exports != null) { if(isMain) { throw new IllegalStateException( "Attempt to set main module after it was loaded"); } return exports; } // Check if it is currently being loaded on the current thread // (supporting circular dependencies). Map<String, Scriptable> threadLoadingModules = loadingModuleInterfaces.get(); if(threadLoadingModules != null) { exports = threadLoadingModules.get(id); if(exports != null) { return exports; } } // The requested module is neither already loaded, nor is it being // loaded on the current thread. End of fast path. We must synchronize // now, as we have to guarantee that at most one thread can load // modules at any one time. Otherwise, two threads could end up // attempting to load two circularly dependent modules in opposite // order, which would lead to either unacceptable non-determinism or // deadlock, depending on whether we underprotected or overprotected it // with locks. synchronized(loadLock) { // Recheck if it is already loaded - other thread might've // completed loading it just as we entered the synchronized block. exports = exportedModuleInterfaces.get(id); if(exports != null) { return exports; } // Nope, still not loaded; we're loading it then. final ModuleScript moduleScript = getModule(cx, id, uri, base); if (sandboxed && !moduleScript.isSandboxed()) { throw ScriptRuntime.throwError(cx, nativeScope, "Module \"" + id + "\" is not contained in sandbox."); } exports = cx.newObject(nativeScope); // Are we the outermost locked invocation on this thread? final boolean outermostLocked = threadLoadingModules == null; if(outermostLocked) { threadLoadingModules = new HashMap<String, Scriptable>(); loadingModuleInterfaces.set(threadLoadingModules); } // Must make the module exports available immediately on the // current thread, to satisfy the CommonJS Modules/1.1 requirement // that "If there is a dependency cycle, the foreign module may not // have finished executing at the time it is required by one of its // transitive dependencies; in this case, the object returned by // "require" must contain at least the exports that the foreign // module has prepared before the call to require that led to the // current module's execution." threadLoadingModules.put(id, exports); try { // Support non-standard Node.js feature to allow modules to // replace the exports object by setting module.exports. Scriptable newExports = executeModuleScript(cx, id, exports, moduleScript, isMain); if (exports != newExports) { threadLoadingModules.put(id, newExports); exports = newExports; } } catch(RuntimeException e) { // Throw loaded module away if there was an exception threadLoadingModules.remove(id); throw e; } finally { if(outermostLocked) { // Make loaded modules visible to other threads only after // the topmost triggering load has completed. This strategy // (compared to the one where we'd make each module // globally available as soon as it loads) prevents other // threads from observing a partially loaded circular // dependency of a module that completed loading. exportedModuleInterfaces.putAll(threadLoadingModules); loadingModuleInterfaces.set(null); } } } return exports; }
Example 17
Source File: NativeTypedArrayView.java From JsDroidCmd with Mozilla Public License 2.0 | 4 votes |
private NativeArrayBuffer makeArrayBuffer(Context cx, Scriptable scope, int length) { return (NativeArrayBuffer)cx.newObject(scope, NativeArrayBuffer.CLASS_NAME, new Object[] { length }); }
Example 18
Source File: SubQueryTest.java From birt with Eclipse Public License 1.0 | 4 votes |
/** * Sub query test * Normal case: add subquery to GroupDefinition * @throws Exception */ @Test public void test( ) throws Exception { // 1 prepare query execution Context cx = Context.enter( ); Scriptable sharedScope = cx.initStandardObjects( ); Scriptable subScope = cx.newObject( sharedScope ); subScope.setParentScope( sharedScope ); IQueryDefinition queryDefn = getDefaultQueryDefnWithSubQuery( dataSet.getName( ) ); expressions = getExpressionsOfDefaultQuery( ); // 2 do query execution IResultIterator resultIt = executeQuery( queryDefn ); // 3.1 get sub query data resultIt.next( ); IResultIterator subIterator = resultIt.getSecondaryIterator( "IAMTEST", sharedScope ); // 3.2 get sub query of sub query data subIterator.next( ); IResultIterator subSubIterator = subIterator.getSecondaryIterator( "IAMTEST2", subScope ); bindingNameRow = this.getBindingExpressionName( ); // 4.1 output sub query data testPrintln( "sub query data" ); outputData( subIterator ); testPrintln( "" ); // 4.2 output sub query of sub query data testPrintln( "sub query of sub query data" ); outputData( subSubIterator ); testPrintln( "" ); // check whether output is correct checkOutputFile(); }
Example 19
Source File: DataFrameAdapter.java From joinery with GNU General Public License v3.0 | 4 votes |
public static Scriptable jsStaticFunction_readXls(final Context ctx, final Scriptable object, final Object[] args, final Function func) throws IOException { final String file = Context.toString(args[0]); final DataFrame<Object> df = DataFrame.readXls(file); return new DataFrameAdapter(ctx.newObject(object, df.getClass().getSimpleName()), df); }
Example 20
Source File: Require.java From JsDroidCmd with Mozilla Public License 2.0 | 4 votes |
private Scriptable getExportedModuleInterface(Context cx, String id, URI uri, URI base, boolean isMain) { // Check if the requested module is already completely loaded Scriptable exports = exportedModuleInterfaces.get(id); if(exports != null) { if(isMain) { throw new IllegalStateException( "Attempt to set main module after it was loaded"); } return exports; } // Check if it is currently being loaded on the current thread // (supporting circular dependencies). Map<String, Scriptable> threadLoadingModules = loadingModuleInterfaces.get(); if(threadLoadingModules != null) { exports = threadLoadingModules.get(id); if(exports != null) { return exports; } } // The requested module is neither already loaded, nor is it being // loaded on the current thread. End of fast path. We must synchronize // now, as we have to guarantee that at most one thread can load // modules at any one time. Otherwise, two threads could end up // attempting to load two circularly dependent modules in opposite // order, which would lead to either unacceptable non-determinism or // deadlock, depending on whether we underprotected or overprotected it // with locks. synchronized(loadLock) { // Recheck if it is already loaded - other thread might've // completed loading it just as we entered the synchronized block. exports = exportedModuleInterfaces.get(id); if(exports != null) { return exports; } // Nope, still not loaded; we're loading it then. final ModuleScript moduleScript = getModule(cx, id, uri, base); if (sandboxed && !moduleScript.isSandboxed()) { throw ScriptRuntime.throwError(cx, nativeScope, "Module \"" + id + "\" is not contained in sandbox."); } exports = cx.newObject(nativeScope); // Are we the outermost locked invocation on this thread? final boolean outermostLocked = threadLoadingModules == null; if(outermostLocked) { threadLoadingModules = new HashMap<String, Scriptable>(); loadingModuleInterfaces.set(threadLoadingModules); } // Must make the module exports available immediately on the // current thread, to satisfy the CommonJS Modules/1.1 requirement // that "If there is a dependency cycle, the foreign module may not // have finished executing at the time it is required by one of its // transitive dependencies; in this case, the object returned by // "require" must contain at least the exports that the foreign // module has prepared before the call to require that led to the // current module's execution." threadLoadingModules.put(id, exports); try { // Support non-standard Node.js feature to allow modules to // replace the exports object by setting module.exports. Scriptable newExports = executeModuleScript(cx, id, exports, moduleScript, isMain); if (exports != newExports) { threadLoadingModules.put(id, newExports); exports = newExports; } } catch(RuntimeException e) { // Throw loaded module away if there was an exception threadLoadingModules.remove(id); throw e; } finally { if(outermostLocked) { // Make loaded modules visible to other threads only after // the topmost triggering load has completed. This strategy // (compared to the one where we'd make each module // globally available as soon as it loads) prevents other // threads from observing a partially loaded circular // dependency of a module that completed loading. exportedModuleInterfaces.putAll(threadLoadingModules); loadingModuleInterfaces.set(null); } } } return exports; }