| 1 | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- |
| 2 | * |
| 3 | * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 | |
| 7 | import org.mozilla.javascript.*; |
| 8 | |
| 9 | /** |
| 10 | * Example of controlling the JavaScript execution engine. |
| 11 | * |
| 12 | * We evaluate a script and then manipulate the result. |
| 13 | * |
| 14 | */ |
| 15 | public class Control { |
| 16 | |
| 17 | /** |
| 18 | * Main entry point. |
| 19 | * |
| 20 | * Process arguments as would a normal Java program. Also |
| 21 | * create a new Context and associate it with the current thread. |
| 22 | * Then set up the execution environment and begin to |
| 23 | * execute scripts. |
| 24 | */ |
| 25 | public static void main(String[] args) |
| 26 | { |
| 27 | Context cx = Context.enter(); |
| 28 | try { |
| 29 | // Set version to JavaScript1.2 so that we get object-literal style |
| 30 | // printing instead of "[object Object]" |
| 31 | cx.setLanguageVersion(Context.VERSION_1_2); |
| 32 | |
| 33 | // Initialize the standard objects (Object, Function, etc.) |
| 34 | // This must be done before scripts can be executed. |
| 35 | Scriptable scope = cx.initStandardObjects(); |
| 36 | |
| 37 | // Now we can evaluate a script. Let's create a new object |
| 38 | // using the object literal notation. |
| 39 | Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", |
| 40 | "MySource", 1, null); |
| 41 | |
| 42 | Scriptable obj = (Scriptable) scope.get("obj", scope); |
| 43 | |
| 44 | // Should print "obj == result" (Since the result of an assignment |
| 45 | // expression is the value that was assigned) |
| 46 | System.out.println("obj " + (obj == result ? "==" : "!=") + |
| 47 | " result"); |
| 48 | |
| 49 | // Should print "obj.a == 1" |
| 50 | System.out.println("obj.a == " + obj.get("a", obj)); |
| 51 | |
| 52 | Scriptable b = (Scriptable) obj.get("b", obj); |
| 53 | |
| 54 | // Should print "obj.b[0] == x" |
| 55 | System.out.println("obj.b[0] == " + b.get(0, b)); |
| 56 | |
| 57 | // Should print "obj.b[1] == y" |
| 58 | System.out.println("obj.b[1] == " + b.get(1, b)); |
| 59 | |
| 60 | // Should print {a:1, b:["x", "y"]} |
| 61 | Function fn = (Function) ScriptableObject.getProperty(obj, "toString"); |
| 62 | System.out.println(fn.call(cx, scope, obj, new Object[0])); |
| 63 | } finally { |
| 64 | Context.exit(); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | } |
| 69 |