Java Code Examples for org.mozilla.javascript.Context#evaluateString()

The following examples show how to use org.mozilla.javascript.Context#evaluateString() . 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: CipherManager.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
private static String RhinoEngine(String s) {
	Context rhino = Context.enter();
	rhino.setOptimizationLevel(-1);
	try {
		Scriptable scope = rhino.initStandardObjects();
		rhino.evaluateString(scope, cachedDechiperFunction, "JavaScript", 1, null);
		Object obj = scope.get("decipher", scope);

		if (obj instanceof Function) {
			Function jsFunction = (Function) obj;
			Object jsResult = jsFunction.call(rhino, scope, scope, new Object[]{s});
			String result = Context.toString(jsResult);
			return result ;
		}
	}
	finally {
		Context.exit();
	}
	return s;
}
 
Example 2
Source File: TypeOfTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
Source File: Bug448816Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: Bug466207Test.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void setUp() {
    // set up a reference map
    reference = new ArrayList<Object>();
    reference.add("a");
    reference.add(Boolean.TRUE);
    reference.add(new HashMap<Object, Object>());
    reference.add(new Integer(42));
    reference.add("a");
    // get a js object as map
    Context context = Context.enter();
    ScriptableObject scope = context.initStandardObjects();
    list = (List<Object>) context.evaluateString(scope,
            "(['a', true, new java.util.HashMap(), 42, 'a']);",
            "testsrc", 1, null);
    Context.exit();
}
 
Example 5
Source File: JsTestsBase.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
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 6
Source File: AddToMatchedText.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void execute(final Context context, final Scriptable scope) {
    String metaCurrent = (String) context.evaluateString(scope,
            "meta.current().text;", "AddToMatchedText:get meta", 0, null);

    if (metaCurrent.length() == 0) {
        context.evaluateString(scope,
                "meta.current=function() {return {text:'" + matchedText
                        + "', score:1.0};};", "AddToMatchedText:set meta1",
                0, null);
    } else {
        context.evaluateString(scope,
                "meta.current=function() {return {text:'" + metaCurrent
                        + " " + matchedText + "', score:1.0};};".replace("'", "\\'"),
                "AddToMatchedText:set meta1", 0, null);
    }
}
 
Example 7
Source File: ApplyOnPrimitiveNumberTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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 8
Source File: DeletePropertyTest.java    From rhino-android with Apache License 2.0 6 votes vote down vote up
/**
 * delete should not delete anything in the prototype chain.
 */
@Test
public void testDeletePropInPrototype() throws Exception {
	final String script = "Array.prototype.foo = function() {};\n"
		+ "Array.prototype[1] = function() {};\n"
		+ "var t = [];\n"
		+ "[].foo();\n"
		+ "for (var i in t) delete t[i];\n"
		+ "[].foo();\n"
		+ "[][1]();\n";

	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);
			return null;
		}
	};

	Utils.runWithAllOptimizationLevels(action);
}
 
Example 9
Source File: AbstractScriptHandler.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates the given expression and returns the value.
 * 
 * @param sScriptContent
 */
public final Object evaluate( String sScriptContent ) throws ChartException
{
	final Context cx = Context.enter( );
	try
	{
		return cx.evaluateString( scope, sScriptContent, "<cmd>", 1, null ); //$NON-NLS-1$
	}
	catch ( RhinoException jsx )
	{
		throw convertException( jsx );
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 10
Source File: SecureJavascriptUtil.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static Object evaluateScript(VariableScope variableScope, String script, Map<Object, Object> beans) {
  Context context = Context.enter();
  try {
      Scriptable scope = context.initStandardObjects();
      SecureScriptScope secureScriptScope = new SecureScriptScope(variableScope, beans);
      scope.setPrototype(secureScriptScope);

      return context.evaluateString(scope, script, "<script>", 0, null);
  } finally {
      Context.exit();
  }
}
 
Example 11
Source File: XmlExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testConvertApplicationLastResultSimpleSemanticInterpretation()
        throws Exception {
    final XmlExtensionNotificationDataConverter converter = new XmlExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = 'yes';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yeah", .75f, "voice", out);
    list.add(result);
    Element element = (Element) converter.convertApplicationLastResult(list);
    System.out.println(toString(element));
}
 
Example 12
Source File: Rhino.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void putScopeFunction(String name, Object obj, String method, int params) throws ScriptExecException {
    try {
        Context cx = Context.enter();
        cx.setOptimizationLevel(-1); // always interpretive mode                     
        ScriptableObject.putProperty(scope, "__" + name, Context.javaToJS(obj, scope));         
        cx.evaluateString(scope, "function " + name + "(" + createArgs(params) + ") {return __" + name +"." + method + "(" + createArgs(params) + ");}", "<cmd>", 1, null);
    } finally {
        Context.exit();            
    }
}
 
Example 13
Source File: RhinoWorkerUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <T> T parseRhino(File rhinoScript, ScopeOperation<T> operation) {
    Context context = Context.enter();
    try {
        operation.initContext(context);
        Scriptable scope = context.initStandardObjects();
        String printFunction = "function print(message) {}";
        context.evaluateString(scope, printFunction, "print", 1, null);
        context.evaluateString(scope, readFile(rhinoScript, "UTF-8"), rhinoScript.getName(), 1, null);
        return operation.action(scope, context);
    } finally {
        Context.exit();
    }
}
 
Example 14
Source File: JavascriptEngineFactory.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
protected ScriptableObject createRootScope( ) throws BirtException
{
	Context context = Context.enter( );
	try
	{
		ScriptableObject rootScope = context.initStandardObjects( );
		context
				.evaluateString(
						rootScope,
						"function registerGlobal( name, value) { _jsContext.registerGlobalBean(name, value); }",
						"<inline>", 0, null );
		context
				.evaluateString(
						rootScope,
						"function unregisterGlobal(name) { _jsContext.unregisterGlobalBean(name); }",
						"<inline>", 0, null );
		return rootScope;
	}
	catch ( Exception ex )
	{
		logger.log( Level.WARNING,
				"Error occurs while initialze script scope", ex );
		return null;
	}
	finally
	{
		Context.exit( );
	}
}
 
Example 15
Source File: SemanticInterpretationBlock.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void execute(Context context, Scriptable scope) {
    LOGGER.debug("executing: " + tagContent);

    context.evaluateString(scope, tagContent.toString(),
            "SISR executable from TagCollection", 0, null);
}
 
Example 16
Source File: JavaScriptEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * This is used by an application to evaluate a string containing
 * some expression.
 */
public Object eval(String source, int lineNo, int columnNo, Object oscript)
    throws BSFException {

    String scriptText = oscript.toString();
    Object retval = null;
    Context cx;

    try {
        cx = Context.enter();

        cx.setOptimizationLevel(-1);
        cx.setGeneratingDebug(false);
        cx.setGeneratingSource(false);
        cx.setOptimizationLevel(0);
        cx.setDebugger(null, null);

        retval = cx.evaluateString(global, scriptText,
                                   source, lineNo,
                                   null);

        if (retval instanceof NativeJavaObject)
            retval = ((NativeJavaObject) retval).unwrap();

    } 
    catch (Throwable t) { // includes JavaScriptException, rethrows Errors
        handleError(t);
    } 
    finally {
        Context.exit();
    }
    return retval;
}
 
Example 17
Source File: NativeStringTest.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void assertEvaluates(final Object expected, final String source) {
    final ContextAction action = new ContextAction() {
        public Object run(Context cx) {
            final Scriptable scope = cx.initStandardObjects();
            final Object rep = cx.evaluateString(scope, source, "test.js",
                    0, null);
            assertEquals(expected, rep);
            return null;
        }
    };
    Utils.runWithAllOptimizationLevels(action);
}
 
Example 18
Source File: SdpProcessor.java    From openwebrtc-android-sdk with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private SdpProcessor() {
    Context context = Context.enter();
    context.setOptimizationLevel(-1);
    context.setLanguageVersion(Context.VERSION_1_8);
    mScope = context.initStandardObjects();

    try {
        context.evaluateString(mScope, sSdpJsSource, "sdp.js", 1, null);
        mSdpToJsonFunction = context.compileFunction(mScope, "function sdpToJson(sdp) { return JSON.stringify(SDP.parse(sdp)); }", "sdpToJson", 1, null);
        mJsonToSdpFunction = context.compileFunction(mScope, "function jsonToSdp(sdp) { return SDP.generate(JSON.parse(sdp)); }", "jsonToSdp", 1, null);
    } finally {
        Context.exit();
    }
}
 
Example 19
Source File: JavaScriptMessageMapperRhino.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void initLibraries(final Context cx, final Scriptable scope) {
    if (getConfiguration().map(JavaScriptMessageMapperConfiguration::isLoadLongJS).orElse(false)) {
        loadJavascriptLibrary(cx, scope, new InputStreamReader(getClass().getResourceAsStream(WEBJARS_LONG)),
                WEBJARS_LONG);
    }
    if (getConfiguration().map(JavaScriptMessageMapperConfiguration::isLoadBytebufferJS).orElse(false)) {
        loadJavascriptLibrary(cx, scope, new InputStreamReader(getClass().getResourceAsStream(WEBJARS_BYTEBUFFER)),
                WEBJARS_BYTEBUFFER);
    }

    loadJavascriptLibrary(cx, scope, new InputStreamReader(getClass().getResourceAsStream(DITTO_SCOPE_SCRIPT)),
            DITTO_SCOPE_SCRIPT);
    loadJavascriptLibrary(cx, scope, new InputStreamReader(getClass().getResourceAsStream(INCOMING_SCRIPT)),
            INCOMING_SCRIPT);
    loadJavascriptLibrary(cx, scope, new InputStreamReader(getClass().getResourceAsStream(OUTGOING_SCRIPT)),
            OUTGOING_SCRIPT);

    final String userIncomingScript = getConfiguration()
            .flatMap(JavaScriptMessageMapperConfiguration::getIncomingScript)
            .orElse("");
    if (userIncomingScript.isEmpty()) {
        // shortcut: the user defined an empty incoming mapping script -> assume that the ExternalMessage is in DittoProtocol
        incomingMapping = DefaultIncomingMapping.get();
    } else {
        incomingMapping = new ScriptedIncomingMapping(contextFactory, scope);
        cx.evaluateString(scope, userIncomingScript,
                JavaScriptMessageMapperConfigurationProperties.INCOMING_SCRIPT, 1, null);
    }

    final String userOutgoingScript = getConfiguration()
            .flatMap(JavaScriptMessageMapperConfiguration::getOutgoingScript)
            .orElse("");
    if (userOutgoingScript.isEmpty()) {
        // shortcut: the user defined an empty outgoing mapping script -> send the Adaptable as DittoProtocol JSON
        outgoingMapping = DefaultOutgoingMapping.get();
    } else {
        outgoingMapping = new ScriptedOutgoingMapping(contextFactory, scope);
        cx.evaluateString(scope, userOutgoingScript,
                JavaScriptMessageMapperConfigurationProperties.OUTGOING_SCRIPT, 1, null);
    }
}
 
Example 20
Source File: RemoteRunner.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
public void run( )
{
	try
	{
		System.out.println( "start server" );

		server = new ReportVMServer( );

		Context cx = Context.enter( );

		server.start( 10000, cx );

		System.out.println( "server started" );

		Scriptable global = new ImporterTopLevel( );

		cx.evaluateString( global,
				"var a = 2;\r\nvar b = a*2;\r\n",
				"sec1",
				0,
				null );

		cx.evaluateString( global,
				"var a = 'ok';\r\nvar b = a;\r\n",
				"sec2",
				0,
				null );

		cx.evaluateString( global,
				"\r\nvar a = 2;\r\nvar b = a*2;\r\n",
				"sec1",
				0,
				null );

		server.shutdown( cx );
	}
	catch ( Exception e )
	{
		e.printStackTrace( );
	}
}