diff options
author | Alexander Sulfrian <alexander@sulfrian.net> | 2010-06-08 08:22:05 +0200 |
---|---|---|
committer | Alexander Sulfrian <alexander@sulfrian.net> | 2010-06-08 08:22:05 +0200 |
commit | d7c5ad7d6263fd1baf9bfdbaa4c50b70ef2fbdb2 (patch) | |
tree | ae0b65da6432f4c26c8d5a7319efbda5d172846c /trunk/infrastructure/rhino1_7R1/examples | |
parent | fa61221dcd89fcd72cba2c97971626f456c86e5d (diff) | |
download | etherpad-d7c5ad7d6263fd1baf9bfdbaa4c50b70ef2fbdb2.tar.gz etherpad-d7c5ad7d6263fd1baf9bfdbaa4c50b70ef2fbdb2.tar.xz etherpad-d7c5ad7d6263fd1baf9bfdbaa4c50b70ef2fbdb2.zip |
reverted folder structure change for better mergeing with upstream
Diffstat (limited to 'trunk/infrastructure/rhino1_7R1/examples')
22 files changed, 3342 insertions, 0 deletions
diff --git a/trunk/infrastructure/rhino1_7R1/examples/Control.java b/trunk/infrastructure/rhino1_7R1/examples/Control.java new file mode 100644 index 0000000..d671181 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/Control.java @@ -0,0 +1,100 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * Example of controlling the JavaScript execution engine. + * + * We evaluate a script and then manipulate the result. + * + */ +public class Control { + + /** + * Main entry point. + * + * Process arguments as would a normal Java program. Also + * create a new Context and associate it with the current thread. + * Then set up the execution environment and begin to + * execute scripts. + */ + public static void main(String[] args) + { + Context cx = Context.enter(); + try { + // Set version to JavaScript1.2 so that we get object-literal style + // printing instead of "[object Object]" + cx.setLanguageVersion(Context.VERSION_1_2); + + // Initialize the standard objects (Object, Function, etc.) + // This must be done before scripts can be executed. + Scriptable scope = cx.initStandardObjects(); + + // Now we can evaluate a script. Let's create a new object + // using the object literal notation. + Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", + "MySource", 1, null); + + Scriptable obj = (Scriptable) scope.get("obj", scope); + + // Should print "obj == result" (Since the result of an assignment + // expression is the value that was assigned) + System.out.println("obj " + (obj == result ? "==" : "!=") + + " result"); + + // Should print "obj.a == 1" + System.out.println("obj.a == " + obj.get("a", obj)); + + Scriptable b = (Scriptable) obj.get("b", obj); + + // Should print "obj.b[0] == x" + System.out.println("obj.b[0] == " + b.get(0, b)); + + // Should print "obj.b[1] == y" + System.out.println("obj.b[1] == " + b.get(1, b)); + + // Should print {a:1, b:["x", "y"]} + Function fn = (Function) ScriptableObject.getProperty(obj, "toString"); + System.out.println(fn.call(cx, scope, obj, new Object[0])); + } finally { + Context.exit(); + } + } + +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/Counter.java b/trunk/infrastructure/rhino1_7R1/examples/Counter.java new file mode 100644 index 0000000..14c179a --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/Counter.java @@ -0,0 +1,59 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +public class Counter extends ScriptableObject { + // The zero-argument constructor used by Rhino runtime to create instances + public Counter() { } + + // Method jsConstructor defines the JavaScript constructor + public void jsConstructor(int a) { count = a; } + + // The class name is defined by the getClassName method + public String getClassName() { return "Counter"; } + + // The method jsGet_count defines the count property. + public int jsGet_count() { return count++; } + + // Methods can be defined using the jsFunction_ prefix. Here we define + // resetCount for JavaScript. + public void jsFunction_resetCount() { count = 0; } + + private int count; +} diff --git a/trunk/infrastructure/rhino1_7R1/examples/CounterTest.java b/trunk/infrastructure/rhino1_7R1/examples/CounterTest.java new file mode 100644 index 0000000..63dc74b --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/CounterTest.java @@ -0,0 +1,82 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * An example illustrating how to create a JavaScript object and retrieve + * properties and call methods. + * <p> + * Output should be: + * <pre> + * count = 0 + * count = 1 + * resetCount + * count = 0 + * </pre> + */ +public class CounterTest { + + public static void main(String[] args) throws Exception + { + Context cx = Context.enter(); + try { + Scriptable scope = cx.initStandardObjects(); + ScriptableObject.defineClass(scope, Counter.class); + + Scriptable testCounter = cx.newObject(scope, "Counter"); + + Object count = ScriptableObject.getProperty(testCounter, "count"); + System.out.println("count = " + count); + + count = ScriptableObject.getProperty(testCounter, "count"); + System.out.println("count = " + count); + + ScriptableObject.callMethod(testCounter, + "resetCount", + new Object[0]); + System.out.println("resetCount"); + + count = ScriptableObject.getProperty(testCounter, "count"); + System.out.println("count = " + count); + } finally { + Context.exit(); + } + } + +} diff --git a/trunk/infrastructure/rhino1_7R1/examples/DynamicScopes.java b/trunk/infrastructure/rhino1_7R1/examples/DynamicScopes.java new file mode 100644 index 0000000..10d53ac --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/DynamicScopes.java @@ -0,0 +1,204 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * Example of controlling the JavaScript with multiple scopes and threads. + */ +public class DynamicScopes { + + static boolean useDynamicScope; + + static class MyFactory extends ContextFactory + { + protected boolean hasFeature(Context cx, int featureIndex) + { + if (featureIndex == Context.FEATURE_DYNAMIC_SCOPE) { + return useDynamicScope; + } + return super.hasFeature(cx, featureIndex); + } + } + + static { + ContextFactory.initGlobal(new MyFactory()); + } + + + /** + * Main entry point. + * + * Set up the shared scope and then spawn new threads that execute + * relative to that shared scope. Try to run functions with and + * without dynamic scope to see the effect. + * + * The expected output is + * <pre> + * sharedScope + * nested:sharedScope + * sharedScope + * nested:sharedScope + * sharedScope + * nested:sharedScope + * thread0 + * nested:thread0 + * thread1 + * nested:thread1 + * thread2 + * nested:thread2 + * </pre> + * The final three lines may be permuted in any order depending on + * thread scheduling. + */ + public static void main(String[] args) + { + Context cx = Context.enter(); + try { + // Precompile source only once + String source = "" + +"var x = 'sharedScope';\n" + +"function f() { return x; }\n" + // Dynamic scope works with nested function too + +"function initClosure(prefix) {\n" + +" return function test() { return prefix+x; }\n" + +"}\n" + +"var closure = initClosure('nested:');\n" + +""; + Script script = cx.compileString(source, "sharedScript", 1, null); + + useDynamicScope = false; + runScripts(cx, script); + useDynamicScope = true; + runScripts(cx, script); + } finally { + Context.exit(); + } + } + + static void runScripts(Context cx, Script script) + { + // Initialize the standard objects (Object, Function, etc.) + // This must be done before scripts can be executed. The call + // returns a new scope that we will share. + ScriptableObject sharedScope = cx.initStandardObjects(null, true); + + // Now we can execute the precompiled script against the scope + // to define x variable and f function in the shared scope. + script.exec(cx, sharedScope); + + // Now we spawn some threads that execute a script that calls the + // function 'f'. The scope chain looks like this: + // <pre> + // ------------------ ------------------ + // | per-thread scope | -prototype-> | shared scope | + // ------------------ ------------------ + // ^ + // | + // parentScope + // | + // ------------------ + // | f's activation | + // ------------------ + // </pre> + // Both the shared scope and the per-thread scope have variables 'x' + // defined in them. If 'f' is compiled with dynamic scope enabled, + // the 'x' from the per-thread scope will be used. Otherwise, the 'x' + // from the shared scope will be used. The 'x' defined in 'g' (which + // calls 'f') should not be seen by 'f'. + final int threadCount = 3; + Thread[] t = new Thread[threadCount]; + for (int i=0; i < threadCount; i++) { + String source2 = "" + +"function g() { var x = 'local'; return f(); }\n" + +"java.lang.System.out.println(g());\n" + +"function g2() { var x = 'local'; return closure(); }\n" + +"java.lang.System.out.println(g2());\n" + +""; + t[i] = new Thread(new PerThread(sharedScope, source2, + "thread" + i)); + } + for (int i=0; i < threadCount; i++) + t[i].start(); + // Don't return in this thread until all the spawned threads have + // completed. + for (int i=0; i < threadCount; i++) { + try { + t[i].join(); + } catch (InterruptedException e) { + } + } + } + + static class PerThread implements Runnable { + + PerThread(Scriptable sharedScope, String source, String x) { + this.sharedScope = sharedScope; + this.source = source; + this.x = x; + } + + public void run() { + // We need a new Context for this thread. + Context cx = Context.enter(); + try { + // We can share the scope. + Scriptable threadScope = cx.newObject(sharedScope); + threadScope.setPrototype(sharedScope); + + // We want "threadScope" to be a new top-level + // scope, so set its parent scope to null. This + // means that any variables created by assignments + // will be properties of "threadScope". + threadScope.setParentScope(null); + + // Create a JavaScript property of the thread scope named + // 'x' and save a value for it. + threadScope.put("x", threadScope, x); + cx.evaluateString(threadScope, source, "threadScript", 1, null); + } finally { + Context.exit(); + } + } + private Scriptable sharedScope; + private String source; + private String x; + } + +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/E4X/e4x_example.js b/trunk/infrastructure/rhino1_7R1/examples/E4X/e4x_example.js new file mode 100644 index 0000000..7417404 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/E4X/e4x_example.js @@ -0,0 +1,223 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * John Schneider + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +print("----------------------------------------"); + +// Use the XML constructor to parse an string into an XML object +var John = "<employee><name>John</name><age>25</age></employee>"; +var Sue ="<employee><name>Sue</name><age>32</age></employee>"; +var tagName = "employees"; +var employees = new XML("<" + tagName +">" + John + Sue + "</" + tagName +">"); +print("The employees XML object constructed from a string is:\n" + employees); + +print("----------------------------------------"); + +// Use an XML literal to create an XML object +var order = <order> + <customer> + <firstname>John</firstname> + <lastname>Doe</lastname> + </customer> + <item> + <description>Big Screen Television</description> + <price>1299.99</price> + <quantity>1</quantity> + </item> +</order> + +// Construct the full customer name +var name = order.customer.firstname + " " + order.customer.lastname; + +// Calculate the total price +var total = order.item.price * order.item.quantity; + +print("The order XML object constructed using a literal is:\n" + order); +print("The total price of " + name + "'s order is " + total); + +print("----------------------------------------"); + +// construct a new XML object using expando and super-expando properties +var order = <order/>; +order.customer.name = "Fred Jones"; +order.customer.address.street = "123 Long Lang"; +order.customer.address.city = "Underwood"; +order.customer.address.state = "CA"; +order.item[0] = ""; +order.item[0].description = "Small Rodents"; +order.item[0].quantity = 10; +order.item[0].price = 6.95; + +print("The order custructed using expandos and super-expandos is:\n" + order); + +// append a new item to the order +order.item += <item><description>Catapult</description><price>139.95</price></item>; + +print("----------------------------------------"); + +print("The order after appending a new item is:\n" + order); + +print("----------------------------------------"); + +// dynamically construct an XML element using embedded expressions +var tagname = "name"; +var attributename = "id"; +var attributevalue = 5; +var content = "Fred"; + +var x = <{tagname} {attributename}={attributevalue}>{content}</{tagname}>; + +print("The dynamically computed element value is:\n" + x.toXMLString()); + +print("----------------------------------------"); + +// Create a SOAP message +var message = <soap:Envelope + xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" + soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> + <soap:Body> + <m:GetLastTradePrice xmlns:m="http://mycompany.com/stocks"> + <symbol>DIS</symbol> + </m:GetLastTradePrice> + </soap:Body> +</soap:Envelope> + +// declare the SOAP and stocks namespaces +var soap = new Namespace("http://schemas.xmlsoap.org/soap/envelope/"); +var stock = new Namespace ("http://mycompany.com/stocks"); + +// extract the soap encoding style and body from the soap message +var encodingStyle = message.@soap::encodingStyle; + +print("The encoding style of the soap message is specified by:\n" + encodingStyle); + +// change the stock symbol +message.soap::Body.stock::GetLastTradePrice.symbol = "MYCO"; + +var body = message.soap::Body; + +print("The body of the soap message is:\n" + body); + +print("----------------------------------------"); + +// create an manipulate an XML object using the default xml namespace + +default xml namespace = "http://default.namespace.com"; +var x = <x/>; +x.a = "one"; +x.b = "two"; +x.c = <c xmlns="http://some.other.namespace.com">three</c>; + +print("XML object constructed using the default xml namespace:\n" + x); + +default xml namespace=""; + +print("----------------------------------------"); + +var order = <order id = "123456" timestamp="Mon Mar 10 2003 16:03:25 GMT-0800 (PST)"> + <customer> + <firstname>John</firstname> + <lastname>Doe</lastname> + </customer> + <item id="3456"> + <description>Big Screen Television</description> + <price>1299.99</price> + <quantity>1</quantity> + </item> + <item id = "56789"> + <description>DVD Player</description> + <price>399.99</price> + <quantity>1</quantity> + </item> +</order>; + + +// get the customer element from the orderprint("The customer is:\n" + order.customer); + +// get the id attribute from the order +print("The order id is:" + order.@id); + +// get all the child elements from the order element +print("The children of the order are:\n" + order.*); + +// get the list of all item descriptions +print("The order descriptions are:\n" + order.item.description); + + +// get second item by numeric index +print("The second item is:\n" + order.item[1]); + +// get the list of all child elements in all item elements +print("The children of the items are:\n" + order.item.*); + +// get the second child element from the order by index +print("The second child of the order is:\n" + order.*[1]); + +// calculate the total price of the order +var totalprice = 0; +for each (i in order.item) { + totalprice += i.price * i.quantity; +} +print("The total price of the order is: " + totalprice); + +print("----------------------------------------"); + +var e = <employees> + <employee id="1"><name>Joe</name><age>20</age></employee> + <employee id="2"><name>Sue</name><age>30</age></employee> +</employees>; + +// get all the names in e +print("All the employee names are:\n" + e..name); + +// employees with name Joe +print("The employee named Joe is:\n" + e.employee.(name == "Joe")); + +// employees with id's 1 & 2 +print("Employees with ids 1 & 2:\n" + e.employee.(@id == 1 || @id == 2)); + +// name of employee with id 1 +print("Name of the the employee with ID=1: " + e.employee.(@id == 1).name); + +print("----------------------------------------"); + + + + + + + diff --git a/trunk/infrastructure/rhino1_7R1/examples/File.java b/trunk/infrastructure/rhino1_7R1/examples/File.java new file mode 100644 index 0000000..62bd980 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/File.java @@ -0,0 +1,348 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; +import java.io.*; +import java.util.Vector; + +/** + * Define a simple JavaScript File object. + * + * This isn't intended to be any sort of definitive attempt at a + * standard File object for JavaScript, but instead is an example + * of a more involved definition of a host object. + * + * Example of use of the File object: + * <pre> + * js> defineClass("File") + * js> file = new File("myfile.txt"); + * [object File] + * js> file.writeLine("one"); <i>only now is file actually opened</i> + * js> file.writeLine("two"); + * js> file.writeLine("thr", "ee"); + * js> file.close(); <i>must close file before we can reopen for reading</i> + * js> var a = file.readLines(); <i>creates and fills an array with the contents of the file</i> + * js> a; + * one,two,three + * js> + * </pre> + * + * + * File errors or end-of-file signaled by thrown Java exceptions will + * be wrapped as JavaScript exceptions when called from JavaScript, + * and may be caught within JavaScript. + * + * @author Norris Boyd + */ +public class File extends ScriptableObject { + + /** + * The zero-parameter constructor. + * + * When Context.defineClass is called with this class, it will + * construct File.prototype using this constructor. + */ + public File() { + } + + /** + * The Java method defining the JavaScript File constructor. + * + * If the constructor has one or more arguments, and the + * first argument is not undefined, the argument is converted + * to a string as used as the filename.<p> + * + * Otherwise System.in or System.out is assumed as appropriate + * to the use. + */ + public static Scriptable jsConstructor(Context cx, Object[] args, + Function ctorObj, + boolean inNewExpr) + { + File result = new File(); + if (args.length == 0 || args[0] == Context.getUndefinedValue()) { + result.name = ""; + result.file = null; + } else { + result.name = Context.toString(args[0]); + result.file = new java.io.File(result.name); + } + return result; + } + + /** + * Returns the name of this JavaScript class, "File". + */ + public String getClassName() { + return "File"; + } + + /** + * Get the name of the file. + * + * Used to define the "name" property. + */ + public String jsGet_name() { + return name; + } + + /** + * Read the remaining lines in the file and return them in an array. + * + * Implements a JavaScript function.<p> + * + * This is a good example of creating a new array and setting + * elements in that array. + * + * @exception IOException if an error occurred while accessing the file + * associated with this object + */ + public Object jsFunction_readLines() + throws IOException + { + Vector v = new Vector(); + String s; + while ((s = jsFunction_readLine()) != null) { + v.addElement(s); + } + Object[] lines = new Object[v.size()]; + v.copyInto(lines); + + Scriptable scope = ScriptableObject.getTopLevelScope(this); + Context cx = Context.getCurrentContext(); + return cx.newObject(scope, "Array", lines); + } + + /** + * Read a line. + * + * Implements a JavaScript function. + * @exception IOException if an error occurred while accessing the file + * associated with this object, or EOFException if the object + * reached the end of the file + */ + public String jsFunction_readLine() throws IOException { + return getReader().readLine(); + } + + /** + * Read a character. + * + * @exception IOException if an error occurred while accessing the file + * associated with this object, or EOFException if the object + * reached the end of the file + */ + public String jsFunction_readChar() throws IOException { + int i = getReader().read(); + if (i == -1) + return null; + char[] charArray = { (char) i }; + return new String(charArray); + } + + /** + * Write strings. + * + * Implements a JavaScript function. <p> + * + * This function takes a variable number of arguments, converts + * each argument to a string, and writes that string to the file. + * @exception IOException if an error occurred while accessing the file + * associated with this object + */ + public static void jsFunction_write(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + throws IOException + { + write0(thisObj, args, false); + } + + /** + * Write strings and a newline. + * + * Implements a JavaScript function. + * @exception IOException if an error occurred while accessing the file + * associated with this object + * + */ + public static void jsFunction_writeLine(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + throws IOException + { + write0(thisObj, args, true); + } + + public int jsGet_lineNumber() + throws FileNotFoundException + { + return getReader().getLineNumber(); + } + + /** + * Close the file. It may be reopened. + * + * Implements a JavaScript function. + * @exception IOException if an error occurred while accessing the file + * associated with this object + */ + public void jsFunction_close() throws IOException { + if (reader != null) { + reader.close(); + reader = null; + } else if (writer != null) { + writer.close(); + writer = null; + } + } + + /** + * Finalizer. + * + * Close the file when this object is collected. + */ + protected void finalize() { + try { + jsFunction_close(); + } + catch (IOException e) { + } + } + + /** + * Get the Java reader. + */ + public Object jsFunction_getReader() { + if (reader == null) + return null; + // Here we use toObject() to "wrap" the BufferedReader object + // in a Scriptable object so that it can be manipulated by + // JavaScript. + Scriptable parent = ScriptableObject.getTopLevelScope(this); + return Context.javaToJS(reader, parent); + } + + /** + * Get the Java writer. + * + * @see File#jsFunction_getReader + * + */ + public Object jsFunction_getWriter() { + if (writer == null) + return null; + Scriptable parent = ScriptableObject.getTopLevelScope(this); + return Context.javaToJS(writer, parent); + } + + /** + * Get the reader, checking that we're not already writing this file. + */ + private LineNumberReader getReader() throws FileNotFoundException { + if (writer != null) { + throw Context.reportRuntimeError("already writing file \"" + + name + + "\""); + } + if (reader == null) + reader = new LineNumberReader(file == null + ? new InputStreamReader(System.in) + : new FileReader(file)); + return reader; + } + + /** + * Perform the guts of write and writeLine. + * + * Since the two functions differ only in whether they write a + * newline character, move the code into a common subroutine. + * + */ + private static void write0(Scriptable thisObj, Object[] args, boolean eol) + throws IOException + { + File thisFile = checkInstance(thisObj); + if (thisFile.reader != null) { + throw Context.reportRuntimeError("already writing file \"" + + thisFile.name + + "\""); + } + if (thisFile.writer == null) + thisFile.writer = new BufferedWriter( + thisFile.file == null ? new OutputStreamWriter(System.out) + : new FileWriter(thisFile.file)); + for (int i=0; i < args.length; i++) { + String s = Context.toString(args[i]); + thisFile.writer.write(s, 0, s.length()); + } + if (eol) + thisFile.writer.newLine(); + } + + /** + * Perform the instanceof check and return the downcasted File object. + * + * This is necessary since methods may reside in the File.prototype + * object and scripts can dynamically alter prototype chains. For example: + * <pre> + * js> defineClass("File"); + * js> o = {}; + * [object Object] + * js> o.__proto__ = File.prototype; + * [object File] + * js> o.write("hi"); + * js: called on incompatible object + * </pre> + * The runtime will take care of such checks when non-static Java methods + * are defined as JavaScript functions. + */ + private static File checkInstance(Scriptable obj) { + if (obj == null || !(obj instanceof File)) { + throw Context.reportRuntimeError("called on incompatible object"); + } + return (File) obj; + } + + /** + * Some private data for this class. + */ + private String name; + private java.io.File file; // may be null, meaning to use System.out or .in + private LineNumberReader reader; + private BufferedWriter writer; +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/Foo.java b/trunk/infrastructure/rhino1_7R1/examples/Foo.java new file mode 100644 index 0000000..bca1b79 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/Foo.java @@ -0,0 +1,169 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * An example host object class. + * + * Here's a shell session showing the Foo object in action: + * <pre> + * js> defineClass("Foo") + * js> foo = new Foo(); <i>A constructor call, see <a href="#Foo">Foo</a> below.</i> + * [object Foo] <i>The "Foo" here comes from <a href"#getClassName">getClassName</a>.</i> + * js> foo.counter; <i>The counter property is defined by the <code>defineProperty</code></i> + * 0 <i>call below and implemented by the <a href="#getCounter">getCounter</a></i> + * js> foo.counter; <i>method below.</i> + * 1 + * js> foo.counter; + * 2 + * js> foo.resetCounter(); <i>Results in a call to <a href="#resetCounter">resetCounter</a>.</i> + * js> foo.counter; <i>Now the counter has been reset.</i> + * 0 + * js> foo.counter; + * 1 + * js> bar = new Foo(37); <i>Create a new instance.</i> + * [object Foo] + * js> bar.counter; <i>This instance's counter is distinct from</i> + * 37 <i>the other instance's counter.</i> + * js> foo.varargs(3, "hi"); <i>Calls <a href="#varargs">varargs</a>.</i> + * this = [object Foo]; args = [3, hi] + * js> foo[7] = 34; <i>Since we extended ScriptableObject, we get</i> + * 34 <i>all the behavior of a JavaScript object</i> + * js> foo.a = 23; <i>for free.</i> + * 23 + * js> foo.a + foo[7]; + * 57 + * js> + * </pre> + * + * @see org.mozilla.javascript.Context + * @see org.mozilla.javascript.Scriptable + * @see org.mozilla.javascript.ScriptableObject + * + * @author Norris Boyd + */ + +public class Foo extends ScriptableObject { + + /** + * The zero-parameter constructor. + * + * When Context.defineClass is called with this class, it will + * construct Foo.prototype using this constructor. + */ + public Foo() { + } + + /** + * The Java method defining the JavaScript Foo constructor. + * + * Takes an initial value for the counter property. + * Note that in the example Shell session above, we didn't + * supply a argument to the Foo constructor. This means that + * the Undefined value is used as the value of the argument, + * and when the argument is converted to an integer, Undefined + * becomes 0. + */ + public Foo(int counterStart) { + counter = counterStart; + } + + /** + * Returns the name of this JavaScript class, "Foo". + */ + public String getClassName() { + return "Foo"; + } + + /** + * The Java method defining the JavaScript resetCounter function. + * + * Resets the counter to 0. + */ + public void jsFunction_resetCounter() { + counter = 0; + } + + /** + * The Java method implementing the getter for the counter property. + * <p> + * If "setCounter" had been defined in this class, the runtime would + * call the setter when the property is assigned to. + */ + public int jsGet_counter() { + return counter++; + } + + /** + * An example of a variable-arguments method. + * + * All variable arguments methods must have the same number and + * types of parameters, and must be static. <p> + * @param cx the Context of the current thread + * @param thisObj the JavaScript 'this' value. + * @param args the array of arguments for this call + * @param funObj the function object of the invoked JavaScript function + * This value is useful to compute a scope using + * Context.getTopLevelScope(). + * @return computes the string values and types of 'this' and + * of each of the supplied arguments and returns them in a string. + * + * @see org.mozilla.javascript.ScriptableObject#getTopLevelScope + */ + public static Object jsFunction_varargs(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + { + StringBuffer buf = new StringBuffer(); + buf.append("this = "); + buf.append(Context.toString(thisObj)); + buf.append("; args = ["); + for (int i=0; i < args.length; i++) { + buf.append(Context.toString(args[i])); + if (i+1 != args.length) + buf.append(", "); + } + buf.append("]"); + return buf.toString(); + } + + /** + * A piece of private data for this class. + */ + private int counter; +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/Matrix.java b/trunk/infrastructure/rhino1_7R1/examples/Matrix.java new file mode 100644 index 0000000..87e4b8a --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/Matrix.java @@ -0,0 +1,279 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; +import java.util.Vector; + +/** + * Matrix: An example host object class that implements the Scriptable interface. + * + * Built-in JavaScript arrays don't handle multiple dimensions gracefully: the + * script writer must create every array in an array of arrays. The Matrix class + * takes care of that by automatically allocating arrays for every index that + * is accessed. What's more, the Matrix constructor takes a integer argument + * that specifies the dimension of the Matrix. If m is a Matrix with dimension 3, + * then m[0] will be a Matrix with dimension 1, and m[0][0] will be an Array. + * + * Here's a shell session showing the Matrix object in action: + * <pre> + * js> defineClass("Matrix") + * js> m = new Matrix(2); <i>A constructor call, see <a href="#Matrix">Matrix</a> below.</i> + * [object Matrix] <i>The "Matrix" here comes from <a href"#getClassName">getClassName</a>.</i> + * js> version(120); <i>switch to JavaScript1.2 to see arrays better</i> + * 0 + * js> m[0][0] = 3; + * 3 + * js> m[0]; <i>an array was created automatically!</i> + * [3] + * js> m[1]; <i>array is created even if we don't set a value</i> + * [] + * js> m.dim; <i>we can access the "dim" property</i> + * 2 + * js> m.dim = 3; + * 3 + * js> m.dim; <i>but not modify it</i> + * 2 + * </pre> + * + * @see org.mozilla.javascript.Context + * @see org.mozilla.javascript.Scriptable + * + * @author Norris Boyd + */ +public class Matrix implements Scriptable { + + /** + * The zero-parameter constructor. + * + * When ScriptableObject.defineClass is called with this class, it will + * construct Matrix.prototype using this constructor. + */ + public Matrix() { + } + + /** + * The Java constructor, also used to define the JavaScript constructor. + */ + public Matrix(int dimension) { + if (dimension <= 0) { + throw Context.reportRuntimeError( + "Dimension of Matrix must be greater than zero"); + } + dim = dimension; + v = new Vector(); + } + + /** + * Returns the name of this JavaScript class, "Matrix". + */ + public String getClassName() { + return "Matrix"; + } + + /** + * Defines the "dim" property by returning true if name is + * equal to "dim". + * <p> + * Defines no other properties, i.e., returns false for + * all other names. + * + * @param name the name of the property + * @param start the object where lookup began + */ + public boolean has(String name, Scriptable start) { + return name.equals("dim"); + } + + /** + * Defines all numeric properties by returning true. + * + * @param index the index of the property + * @param start the object where lookup began + */ + public boolean has(int index, Scriptable start) { + return true; + } + + /** + * Get the named property. + * <p> + * Handles the "dim" property and returns NOT_FOUND for all + * other names. + * @param name the property name + * @param start the object where the lookup began + */ + public Object get(String name, Scriptable start) { + if (name.equals("dim")) + return new Integer(dim); + + return NOT_FOUND; + } + + /** + * Get the indexed property. + * <p> + * Look up the element in the associated vector and return + * it if it exists. If it doesn't exist, create it.<p> + * @param index the index of the integral property + * @param start the object where the lookup began + */ + public Object get(int index, Scriptable start) { + if (index >= v.size()) + v.setSize(index+1); + Object result = v.elementAt(index); + if (result != null) + return result; + if (dim > 2) { + Matrix m = new Matrix(dim-1); + m.setParentScope(getParentScope()); + m.setPrototype(getPrototype()); + result = m; + } else { + Context cx = Context.getCurrentContext(); + Scriptable scope = ScriptableObject.getTopLevelScope(start); + result = cx.newArray(scope, 0); + } + v.setElementAt(result, index); + return result; + } + + /** + * Set a named property. + * + * We do nothing here, so all properties are effectively read-only. + */ + public void put(String name, Scriptable start, Object value) { + } + + /** + * Set an indexed property. + * + * We do nothing here, so all properties are effectively read-only. + */ + public void put(int index, Scriptable start, Object value) { + } + + /** + * Remove a named property. + * + * This method shouldn't even be called since we define all properties + * as PERMANENT. + */ + public void delete(String id) { + } + + /** + * Remove an indexed property. + * + * This method shouldn't even be called since we define all properties + * as PERMANENT. + */ + public void delete(int index) { + } + + /** + * Get prototype. + */ + public Scriptable getPrototype() { + return prototype; + } + + /** + * Set prototype. + */ + public void setPrototype(Scriptable prototype) { + this.prototype = prototype; + } + + /** + * Get parent. + */ + public Scriptable getParentScope() { + return parent; + } + + /** + * Set parent. + */ + public void setParentScope(Scriptable parent) { + this.parent = parent; + } + + /** + * Get properties. + * + * We return an empty array since we define all properties to be DONTENUM. + */ + public Object[] getIds() { + return new Object[0]; + } + + /** + * Default value. + * + * Use the convenience method from Context that takes care of calling + * toString, etc. + */ + public Object getDefaultValue(Class typeHint) { + return "[object Matrix]"; + } + + /** + * instanceof operator. + * + * We mimick the normal JavaScript instanceof semantics, returning + * true if <code>this</code> appears in <code>value</code>'s prototype + * chain. + */ + public boolean hasInstance(Scriptable value) { + Scriptable proto = value.getPrototype(); + while (proto != null) { + if (proto.equals(this)) + return true; + proto = proto.getPrototype(); + } + + return false; + } + + /** + * Some private data for this class. + */ + private int dim; + private Vector v; + private Scriptable prototype, parent; +} diff --git a/trunk/infrastructure/rhino1_7R1/examples/NervousText.html b/trunk/infrastructure/rhino1_7R1/examples/NervousText.html new file mode 100644 index 0000000..0e3c7dd --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/NervousText.html @@ -0,0 +1,53 @@ +<!-- ***** BEGIN LICENSE BLOCK ***** + - Version: MPL 1.1/GPL 2.0 + - + - The contents of this file are subject to the Mozilla Public License Version + - 1.1 (the "License"); you may not use this file except in compliance with + - the License. You may obtain a copy of the License at + - http://www.mozilla.org/MPL/ + - + - Software distributed under the License is distributed on an "AS IS" basis, + - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + - for the specific language governing rights and limitations under the + - License. + - + - The Original Code is Rhino code, released May 6, 1999. + - + - The Initial Developer of the Original Code is + - Netscape Communications Corporation. + - Portions created by the Initial Developer are Copyright (C) 1997-1999 + - the Initial Developer. All Rights Reserved. + - + - Contributor(s): + - + - Alternatively, the contents of this file may be used under the terms of + - the GNU General Public License Version 2 or later (the "GPL"), in which + - case the provisions of the GPL are applicable instead of those above. If + - you wish to allow use of your version of this file only under the terms of + - the GPL and not to allow others to use your version of this file under the + - MPL, indicate your decision by deleting the provisions above and replacing + - them with the notice and other provisions required by the GPL. If you do + - not delete the provisions above, a recipient may use your version of this + - file under either the MPL or the GPL. + - + - ***** END LICENSE BLOCK ***** --> + +<html> +<body> +This is the NervousText applet in javascript: +<applet archive="js.jar" code=NervousText width=200 height=50 > +</applet> + +<hr> +The test assumes that applet code is generated with: +<pre> +java -classpath js.jar org.mozilla.javascript.tools.jsc.Main \ + -extends java.applet.Applet \ + -implements java.lang.Runnable \ + NervousText.js +</pre> +and the resulting 2 classes, NervousText.class extending java.applet.Applet and implementing java.lang.Runnable and NervousText1.class which represents compiled JavaScript code, are placed in the same directory as NervousText.html. +<p> +The test also assumes that js.jar from Rhino distribution is available in the same directory. +</body> +</html> diff --git a/trunk/infrastructure/rhino1_7R1/examples/NervousText.js b/trunk/infrastructure/rhino1_7R1/examples/NervousText.js new file mode 100644 index 0000000..a2f82fe --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/NervousText.js @@ -0,0 +1,109 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +// The Java "NervousText" example ported to JavaScript. +// Compile using java org.mozilla.javascript.tools.jsc.Main -extends java.applet.Applet -implements java.lang.Runnable NervousText.js +/* +Adapted from Java code by + Daniel Wyszynski + Center for Applied Large-Scale Computing (CALC) + 04-12-95 + + Test of text animation. + + kwalrath: Changed string; added thread suspension. 5-9-95 +*/ +var Font = java.awt.Font; +var Thread = java.lang.Thread; +var separated; +var s = null; +var killme = null; +var i; +var x_coord = 0, y_coord = 0; +var num; +var speed=35; +var counter =0; +var threadSuspended = false; //added by kwalrath + +function init() { + this.resize(150,50); + this.setFont(new Font("TimesRoman",Font.BOLD,36)); + s = this.getParameter("text"); + if (s == null) { + s = "Rhino"; + } + separated = s.split(''); +} + +function start() { + if(killme == null) + { + killme = new java.lang.Thread(java.lang.Runnable(this)); + killme.start(); + } +} + +function stop() { + killme = null; +} + +function run() { + while (killme != null) { + try {Thread.sleep(100);} catch (e){} + this.repaint(); + } + killme = null; +} + +function paint(g) { + for(i=0;i<separated.length;i++) + { + x_coord = Math.random()*10+15*i; + y_coord = Math.random()*10+36; + g.drawChars(separated, i,1,x_coord,y_coord); + } +} + +/* Added by kwalrath. */ +function mouseDown(evt, x, y) { + if (threadSuspended) { + killme.resume(); + } + else { + killme.suspend(); + } + threadSuspended = !threadSuspended; + return true; +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/PrimitiveWrapFactory.java b/trunk/infrastructure/rhino1_7R1/examples/PrimitiveWrapFactory.java new file mode 100644 index 0000000..4157a11 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/PrimitiveWrapFactory.java @@ -0,0 +1,72 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * An example WrapFactory that can be used to avoid wrapping of Java types + * that can be converted to ECMA primitive values. + * So java.lang.String is mapped to ECMA string, all java.lang.Numbers are + * mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans + * instead of being wrapped as objects. Additionally java.lang.Character is + * converted to ECMA string with length 1. + * Other types have the default behavior. + * <p> + * Note that calling "new java.lang.String('foo')" in JavaScript with this + * wrap factory enabled will still produce a wrapped Java object since the + * WrapFactory.wrapNewObject method is not overridden. + * <p> + * The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory + * on that context. + */ +public class PrimitiveWrapFactory extends WrapFactory { + + public Object wrap(Context cx, Scriptable scope, Object obj, + Class staticType) + { + if (obj instanceof String || obj instanceof Number || + obj instanceof Boolean) + { + return obj; + } else if (obj instanceof Character) { + char[] a = { ((Character)obj).charValue() }; + return new String(a); + } + return super.wrap(cx, scope, obj, staticType); + } +} diff --git a/trunk/infrastructure/rhino1_7R1/examples/RunScript.java b/trunk/infrastructure/rhino1_7R1/examples/RunScript.java new file mode 100644 index 0000000..758ac64 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/RunScript.java @@ -0,0 +1,78 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * RunScript: simplest example of controlling execution of Rhino. + * + * Collects its arguments from the command line, executes the + * script, and prints the result. + * + * @author Norris Boyd + */ +public class RunScript { + public static void main(String args[]) + { + // Creates and enters a Context. The Context stores information + // about the execution environment of a script. + Context cx = Context.enter(); + try { + // Initialize the standard objects (Object, Function, etc.) + // This must be done before scripts can be executed. Returns + // a scope object that we use in later calls. + Scriptable scope = cx.initStandardObjects(); + + // Collect the arguments into a single string. + String s = ""; + for (int i=0; i < args.length; i++) { + s += args[i]; + } + + // Now evaluate the string we've colected. + Object result = cx.evaluateString(scope, s, "<cmd>", 1, null); + + // Convert the result to a string and print it. + System.err.println(Context.toString(result)); + + } finally { + // Exit from the context. + Context.exit(); + } + } +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/RunScript2.java b/trunk/infrastructure/rhino1_7R1/examples/RunScript2.java new file mode 100644 index 0000000..cb02896 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/RunScript2.java @@ -0,0 +1,69 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * RunScript2: Like RunScript, but reflects the System.out into JavaScript. + * + * @author Norris Boyd + */ +public class RunScript2 { + public static void main(String args[]) + { + Context cx = Context.enter(); + try { + Scriptable scope = cx.initStandardObjects(); + + // Add a global variable "out" that is a JavaScript reflection + // of System.out + Object jsOut = Context.javaToJS(System.out, scope); + ScriptableObject.putProperty(scope, "out", jsOut); + + String s = ""; + for (int i=0; i < args.length; i++) { + s += args[i]; + } + Object result = cx.evaluateString(scope, s, "<cmd>", 1, null); + System.err.println(Context.toString(result)); + } finally { + Context.exit(); + } + } + +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/RunScript3.java b/trunk/infrastructure/rhino1_7R1/examples/RunScript3.java new file mode 100644 index 0000000..7baeba8 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/RunScript3.java @@ -0,0 +1,88 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * RunScript3: Example of using JavaScript objects + * + * Collects its arguments from the command line, executes the + * script, and then ... + * + * @author Norris Boyd + */ +public class RunScript3 { + public static void main(String args[]) + { + Context cx = Context.enter(); + try { + Scriptable scope = cx.initStandardObjects(); + + // Collect the arguments into a single string. + String s = ""; + for (int i=0; i < args.length; i++) { + s += args[i]; + } + + // Now evaluate the string we've colected. We'll ignore the result. + cx.evaluateString(scope, s, "<cmd>", 1, null); + + // Print the value of variable "x" + Object x = scope.get("x", scope); + if (x == Scriptable.NOT_FOUND) { + System.out.println("x is not defined."); + } else { + System.out.println("x = " + Context.toString(x)); + } + + // Call function "f('my arg')" and print its result. + Object fObj = scope.get("f", scope); + if (!(fObj instanceof Function)) { + System.out.println("f is undefined or not a function."); + } else { + Object functionArgs[] = { "my arg" }; + Function f = (Function)fObj; + Object result = f.call(cx, scope, scope, functionArgs); + String report = "f('my args') = " + Context.toString(result); + System.out.println(report); + } + } finally { + Context.exit(); + } + } +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/RunScript4.java b/trunk/infrastructure/rhino1_7R1/examples/RunScript4.java new file mode 100644 index 0000000..bd3d6f4 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/RunScript4.java @@ -0,0 +1,78 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; + +/** + * RunScript4: Execute scripts in an environment that includes the + * example Counter class. + * + * @author Norris Boyd + */ +public class RunScript4 { + public static void main(String args[]) + throws Exception + { + Context cx = Context.enter(); + try { + Scriptable scope = cx.initStandardObjects(); + + // Use the Counter class to define a Counter constructor + // and prototype in JavaScript. + ScriptableObject.defineClass(scope, Counter.class); + + // Create an instance of Counter and assign it to + // the top-level variable "myCounter". This is + // equivalent to the JavaScript code + // myCounter = new Counter(7); + Object[] arg = { new Integer(7) }; + Scriptable myCounter = cx.newObject(scope, "Counter", arg); + scope.put("myCounter", scope, myCounter); + + String s = ""; + for (int i=0; i < args.length; i++) { + s += args[i]; + } + Object result = cx.evaluateString(scope, s, "<cmd>", 1, null); + System.err.println(Context.toString(result)); + } finally { + Context.exit(); + } + } + +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/Shell.java b/trunk/infrastructure/rhino1_7R1/examples/Shell.java new file mode 100644 index 0000000..6316c6f --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/Shell.java @@ -0,0 +1,345 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +import org.mozilla.javascript.*; +import java.io.*; + +/** + * The shell program. + * + * Can execute scripts interactively or in batch mode at the command line. + * An example of controlling the JavaScript engine. + * + * @author Norris Boyd + */ +public class Shell extends ScriptableObject +{ + public String getClassName() + { + return "global"; + } + + /** + * Main entry point. + * + * Process arguments as would a normal Java program. Also + * create a new Context and associate it with the current thread. + * Then set up the execution environment and begin to + * execute scripts. + */ + public static void main(String args[]) { + // Associate a new Context with this thread + Context cx = Context.enter(); + try { + // Initialize the standard objects (Object, Function, etc.) + // This must be done before scripts can be executed. + Shell shell = new Shell(); + cx.initStandardObjects(shell); + + // Define some global functions particular to the shell. Note + // that these functions are not part of ECMA. + String[] names = { "print", "quit", "version", "load", "help" }; + shell.defineFunctionProperties(names, Shell.class, + ScriptableObject.DONTENUM); + + args = processOptions(cx, args); + + // Set up "arguments" in the global scope to contain the command + // line arguments after the name of the script to execute + Object[] array; + if (args.length == 0) { + array = new Object[0]; + } else { + int length = args.length - 1; + array = new Object[length]; + System.arraycopy(args, 1, array, 0, length); + } + Scriptable argsObj = cx.newArray(shell, array); + shell.defineProperty("arguments", argsObj, + ScriptableObject.DONTENUM); + + shell.processSource(cx, args.length == 0 ? null : args[0]); + } finally { + Context.exit(); + } + } + + /** + * Parse arguments. + */ + public static String[] processOptions(Context cx, String args[]) { + for (int i=0; i < args.length; i++) { + String arg = args[i]; + if (!arg.startsWith("-")) { + String[] result = new String[args.length - i]; + for (int j=i; j < args.length; j++) + result[j-i] = args[j]; + return result; + } + if (arg.equals("-version")) { + if (++i == args.length) + usage(arg); + double d = Context.toNumber(args[i]); + if (d != d) + usage(arg); + cx.setLanguageVersion((int) d); + continue; + } + usage(arg); + } + return new String[0]; + } + + /** + * Print a usage message. + */ + private static void usage(String s) { + p("Didn't understand \"" + s + "\"."); + p("Valid arguments are:"); + p("-version 100|110|120|130|140|150|160|170"); + System.exit(1); + } + + /** + * Print a help message. + * + * This method is defined as a JavaScript function. + */ + public void help() { + p(""); + p("Command Description"); + p("======= ==========="); + p("help() Display usage and help messages. "); + p("defineClass(className) Define an extension using the Java class"); + p(" named with the string argument. "); + p(" Uses ScriptableObject.defineClass(). "); + p("load(['foo.js', ...]) Load JavaScript source files named by "); + p(" string arguments. "); + p("loadClass(className) Load a class named by a string argument."); + p(" The class must be a script compiled to a"); + p(" class file. "); + p("print([expr ...]) Evaluate and print expressions. "); + p("quit() Quit the shell. "); + p("version([number]) Get or set the JavaScript version number."); + p(""); + } + + /** + * Print the string values of its arguments. + * + * This method is defined as a JavaScript function. + * Note that its arguments are of the "varargs" form, which + * allows it to handle an arbitrary number of arguments + * supplied to the JavaScript function. + * + */ + public static void print(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + { + for (int i=0; i < args.length; i++) { + if (i > 0) + System.out.print(" "); + + // Convert the arbitrary JavaScript value into a string form. + String s = Context.toString(args[i]); + + System.out.print(s); + } + System.out.println(); + } + + /** + * Quit the shell. + * + * This only affects the interactive mode. + * + * This method is defined as a JavaScript function. + */ + public void quit() + { + quitting = true; + } + + /** + * Get and set the language version. + * + * This method is defined as a JavaScript function. + */ + public static double version(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + { + double result = cx.getLanguageVersion(); + if (args.length > 0) { + double d = Context.toNumber(args[0]); + cx.setLanguageVersion((int) d); + } + return result; + } + + /** + * Load and execute a set of JavaScript source files. + * + * This method is defined as a JavaScript function. + * + */ + public static void load(Context cx, Scriptable thisObj, + Object[] args, Function funObj) + { + Shell shell = (Shell)getTopLevelScope(thisObj); + for (int i = 0; i < args.length; i++) { + shell.processSource(cx, Context.toString(args[i])); + } + } + + + /** + * Evaluate JavaScript source. + * + * @param cx the current context + * @param filename the name of the file to compile, or null + * for interactive mode. + */ + private void processSource(Context cx, String filename) + { + if (filename == null) { + BufferedReader in = new BufferedReader + (new InputStreamReader(System.in)); + String sourceName = "<stdin>"; + int lineno = 1; + boolean hitEOF = false; + do { + int startline = lineno; + System.err.print("js> "); + System.err.flush(); + try { + String source = ""; + // Collect lines of source to compile. + while(true) { + String newline; + newline = in.readLine(); + if (newline == null) { + hitEOF = true; + break; + } + source = source + newline + "\n"; + lineno++; + // Continue collecting as long as more lines + // are needed to complete the current + // statement. stringIsCompilableUnit is also + // true if the source statement will result in + // any error other than one that might be + // resolved by appending more source. + if (cx.stringIsCompilableUnit(source)) + break; + } + Object result = cx.evaluateString(this, source, + sourceName, startline, + null); + if (result != Context.getUndefinedValue()) { + System.err.println(Context.toString(result)); + } + } + catch (WrappedException we) { + // Some form of exception was caught by JavaScript and + // propagated up. + System.err.println(we.getWrappedException().toString()); + we.printStackTrace(); + } + catch (EvaluatorException ee) { + // Some form of JavaScript error. + System.err.println("js: " + ee.getMessage()); + } + catch (JavaScriptException jse) { + // Some form of JavaScript error. + System.err.println("js: " + jse.getMessage()); + } + catch (IOException ioe) { + System.err.println(ioe.toString()); + } + if (quitting) { + // The user executed the quit() function. + break; + } + } while (!hitEOF); + System.err.println(); + } else { + FileReader in = null; + try { + in = new FileReader(filename); + } + catch (FileNotFoundException ex) { + Context.reportError("Couldn't open file \"" + filename + "\"."); + return; + } + + try { + // Here we evalute the entire contents of the file as + // a script. Text is printed only if the print() function + // is called. + cx.evaluateReader(this, in, filename, 1, null); + } + catch (WrappedException we) { + System.err.println(we.getWrappedException().toString()); + we.printStackTrace(); + } + catch (EvaluatorException ee) { + System.err.println("js: " + ee.getMessage()); + } + catch (JavaScriptException jse) { + System.err.println("js: " + jse.getMessage()); + } + catch (IOException ioe) { + System.err.println(ioe.toString()); + } + finally { + try { + in.close(); + } + catch (IOException ioe) { + System.err.println(ioe.toString()); + } + } + } + } + + private static void p(String s) { + System.out.println(s); + } + + private boolean quitting; +} + diff --git a/trunk/infrastructure/rhino1_7R1/examples/SwingApplication.js b/trunk/infrastructure/rhino1_7R1/examples/SwingApplication.js new file mode 100644 index 0000000..a527aad --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/SwingApplication.js @@ -0,0 +1,111 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * SwingApplication.js - a translation into JavaScript of + * SwingApplication.java, a java.sun.com Swing example. + * + * @author Roger E Critchlow, Jr. + */ + +var swingNames = JavaImporter(); + +swingNames.importPackage(Packages.javax.swing); +swingNames.importPackage(Packages.java.awt); +swingNames.importPackage(Packages.java.awt.event); + +function createComponents() +{ + with (swingNames) { + var labelPrefix = "Number of button clicks: "; + var numClicks = 0; + var label = new JLabel(labelPrefix + numClicks); + var button = new JButton("I'm a Swing button!"); + button.mnemonic = KeyEvent.VK_I; + // Since Rhino 1.5R5 JS functions can be passed to Java method if + // corresponding argument type is Java interface with single method + // or all its methods have the same number of arguments and the + // corresponding arguments has the same type. See also comments for + // frame.addWindowListener bellow + button.addActionListener(function() { + numClicks += 1; + label.setText(labelPrefix + numClicks); + }); + label.setLabelFor(button); + + /* + * An easy way to put space between a top-level container + * and its contents is to put the contents in a JPanel + * that has an "empty" border. + */ + var pane = new JPanel(); + pane.border = BorderFactory.createEmptyBorder(30, //top + 30, //left + 10, //bottom + 30); //right + pane.setLayout(new GridLayout(0, 1)); + pane.add(button); + pane.add(label); + + return pane; + } +} + +with (swingNames) { + try { + UIManager. + setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); + } catch (e) { } + + //Create the top-level container and add contents to it. + var frame = new swingNames.JFrame("SwingApplication"); + frame.getContentPane().add(createComponents(), BorderLayout.CENTER); + + // Pass JS function as implementation of WindowListener. It is allowed since + // all methods in WindowListener have the same signature. To distinguish + // between methods Rhino passes to JS function the name of corresponding + // method as the last argument + frame.addWindowListener(function(event, methodName) { + if (methodName == "windowClosing") { + java.lang.System.exit(0); + } + }); + + //Finish setting up the frame, and show it. + frame.pack(); + frame.setVisible(true); +} + + + diff --git a/trunk/infrastructure/rhino1_7R1/examples/checkParam.js b/trunk/infrastructure/rhino1_7R1/examples/checkParam.js new file mode 100644 index 0000000..51910d5 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/checkParam.js @@ -0,0 +1,137 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * checkParam.js + * + * The files given as arguments on the command line are assumed to be + * Java source code files. This program checks to see that the @param + * tags in the documentation comments match with the parameters for + * the associated Java methods. + * <p> + * Any errors found are reported. + * + */ +defineClass("File") + +// Return true if "str" ends with "suffix". +function stringEndsWith(str, suffix) { + return str.substring(str.length - suffix.length) == suffix; +} + +/** + * Perform processing once the end of a documentation comment is seen. + * + * Look for a parameter list following the end of the comment and + * collect the parameters and compare to the @param entries. + * Report any discrepancies. + * @param f the current file + * @param a an array of parameters from @param comments + * @param line the string containing the comment end (in case the + * parameters are on the same line) + */ +function processCommentEnd(f, a, line) { + while (line != null && !line.match(/\(/)) + line = f.readLine(); + while (line != null && !line.match(/\)/)) + line += f.readLine(); + if (line === null) + return; + var m = line.match(/\(([^\)]+)\)/); + var args = m ? m[1].split(",") : []; + if (a.length != args.length) { + print('"' + f.name + + '"; line ' + f.lineNumber + + ' mismatch: had a different number' + + ' of @param entries and parameters.'); + } else { + for (var i=0; i < a.length; i++) { + if (!stringEndsWith(args[i], a[i])) { + print('"' + f.name + + '"; line ' + f.lineNumber + + ' mismatch: had "' + a[i] + + '" and "' + args[i] + '".'); + break; + } + } + } +} + +/** + * Process the given file, looking for mismatched @param lists and + * parameter lists. + * @param f the file to process + */ +function processFile(f) { + var line; + var m; + var i = 0; + var a = []; + outer: + while ((line = f.readLine()) != null) { + if (line.match(/@param/)) { + while (m = line.match(/@param[ ]+([^ ]+)/)) { + a[i++] = m[1]; + line = f.readLine(); + if (line == null) + break outer; + } + } + if (i != 0 && line.match(/\*\//)) { + processCommentEnd(f, a, line); + i = 0; + a = []; + } + } + if (i != 0) { + print('"' + f.name + + '"; line ' + f.lineNumber + + ' missing parameters at end of file.'); + } +} + +// main script: process each file in arguments list + +for (var i=0; i < arguments.length; i++) { + var filename = String(arguments[i]); + print("Checking " + filename + "..."); + var f = new File(filename); + processFile(f); +} +print("done."); + diff --git a/trunk/infrastructure/rhino1_7R1/examples/enum.js b/trunk/infrastructure/rhino1_7R1/examples/enum.js new file mode 100644 index 0000000..02034bc --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/enum.js @@ -0,0 +1,69 @@ +/* -*- tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Patrick Beard + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* +Implementing the interface java.util.Enumeration passing the object +with JavaScript implementation directly to the constructor. +This is a shorthand for JavaAdapter constructor: + +elements = new JavaAdapter(java.util.Enumeration, { + index: 0, + elements: array, + hasMoreElements: function ... + nextElement: function ... + }); + */ + +// an array to enumerate. +var array = [0, 1, 2]; + +// create an array enumeration. +var elements = new java.util.Enumeration({ + index: 0, + elements: array, + hasMoreElements: function() { + return (this.index < this.elements.length); + }, + nextElement: function() { + return this.elements[this.index++]; + } + }); + +// now print out the array by enumerating through the Enumeration +while (elements.hasMoreElements()) + print(elements.nextElement()); diff --git a/trunk/infrastructure/rhino1_7R1/examples/jsdoc.js b/trunk/infrastructure/rhino1_7R1/examples/jsdoc.js new file mode 100644 index 0000000..3d44e48 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/jsdoc.js @@ -0,0 +1,556 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * Roland Pennings + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * Process a JavaScript source file and process special comments + * to produce an HTML file of documentation, similar to javadoc. + * @author Norris Boyd + * @see rhinotip.jar + * @lastmodified xx + * @version 1.2 Roland Pennings: Allow multiple files for a function. + * @version 1.3 Roland Pennings: Removes ../.. from the input directory name + */ +defineClass("File") + +var functionDocArray = []; +var inputDirName = ""; +var indexFileArray = []; +var indexFile = ""; +var indexFileName = "index_files"; +var indexFunctionArray = []; +var indexFunction = ""; +var indexFunctionName = "index_functions"; +var FileList = []; +var DirList = []; +var outputdir = null; +var debug = 0; + + + +/** + * Process JavaScript source file <code>f</code>, writing jsdoc to + * file <code>out</code>. + * @param f input file + * @param fname name of the input file (without the path) + * @param inputdir directory of the input file + * @param out output file + */ +function processFile(f, fname, inputdir, out) { + var s; + var firstLine = true; + indexFileArray[fname] = ""; + + // write the header of the output file + out.writeLine('<HTML><HEADER><TITLE>' + fname + '</TITLE><BODY>'); + if (inputdir != null) { + outstr = '<a name=\"_top_\"></a><pre><a href=\"' + indexFile + '\">Index Files</a> '; + outstr += '<a href=\"' + indexFunction + '\">Index Functions</a></pre><hr>'; + out.writeLine(outstr); + } + + // process the input file + var comment = ""; + while ((s = f.readLine()) != null) { + var m = s.match(/\/\*\*(.*)/); + if (m != null) { + // Found a comment start. + s = "*" + m[1]; + do { + m = s.match(/(.*)\*\//); + if (m != null) { + // Found end of comment. + comment += m[1]; + break; + } + // Strip leading whitespace and "*". + comment += s.replace(/^\s*\*/, ""); + s = f.readLine(); + } while (s != null); + + if (debug) + print("Found comment " + comment); + + if (firstLine) { + // We have a comment for the whole file. + out.writeLine('<H1>File ' + fname + '</H1>'); + out.writeLine(processComment(comment,firstLine,fname)); + out.writeLine('<HR>'); + firstLine = false; + comment = ""; + continue; + } + } + // match the beginning of the function + // NB we also match functions without a comment! + // if we have two comments one after another only the last one will be taken + m = s.match(/^\s*function\s+((\w+)|(\w+)(\s+))\(([^)]*)\)/); + if (m != null) + { + // Found a function start + var htmlText = processFunction(m[1], m[5], comment); // sjm changed from 2nd to 5th arg + + // Save the text in a global variable, so we + // can write out a table of contents first. + functionDocArray[functionDocArray.length] = {name:m[1], text:htmlText}; + + // Store the function also in the indexFunctionArray + // so we can have a separate file with the function table of contents + if (indexFunctionArray[m[1]]) { + // print("ERROR: function: " + m[1] + " is defined more than once!"); + // Allow multiple files for a function + with (indexFunctionArray[m[1]]) { + filename = filename + "|" + fname; + // print("filename = " + filename); + } + } + else { + indexFunctionArray[m[1]] = {filename:fname}; + } + //reset comment + comment = ""; + } + // match a method being bound to a prototype + m = s.match(/^\s*(\w*)\.prototype\.(\w*)\s*=\s*function\s*\(([^)]*)\)/); + if (m != null) + { + // Found a method being bound to a prototype. + var htmlText = processPrototypeMethod(m[1], m[2], m[3], comment); + + // Save the text in a global variable, so we + // can write out a table of contents first. + functionDocArray[functionDocArray.length] = {name:m[1]+".prototype."+m[2], text:htmlText}; + + // Store the function also in the indexFunctionArray + // so we can have a separate file with the function table of contents + if (indexFunctionArray[m[1]]) { + // print("ERROR: function: " + m[1] + " is defined more than once!"); + // Allow multiple files for a function + with (indexFunctionArray[m[1]]) { + filename = filename + "|" + fname; + // print("filename = " + filename); + } + } + else { + indexFunctionArray[m[1]] = {filename:fname}; + } + //reset comment + comment = ""; + } + + + firstLine = false; + } + + // Write table of contents. + for (var i=0; i < functionDocArray.length; i++) { + with (functionDocArray[i]) { + out.writeLine('function <A HREF=#' + name + + '>' + name + '</A><BR>'); + } + } + out.writeLine('<HR>'); + + // Now write the saved function documentation. + for (i=0; i < functionDocArray.length; i++) { + with (functionDocArray[i]) { + out.writeLine('<A NAME=' + name + '>'); + out.writeLine(text); + } + } + out.writeLine('</BODY></HTML>'); + + // Now clean up the doc array + functionDocArray = []; +} + +/** + * Process function and associated comment. + * @param name the name of the function + * @param args the args of the function as a single string + * @param comment the text of the comment + * @return a string for the HTML text of the documentation + */ +function processFunction(name, args, comment) { + if (debug) + print("Processing " + name + " " + args + " " + comment); + return "<H2>Function " + name + "</H2>" + + "<PRE>" + + "function " + name + "(" + args + ")" + + "</PRE>" + + processComment(comment,0,name) + + "<P><BR><BR>"; +} + +/** + * Process a method being bound to a prototype. + * @param proto the name of the prototype + * @param name the name of the function + * @param args the args of the function as a single string + * @param comment the text of the comment + * @return a string for the HTML text of the documentation + */ +function processPrototypeMethod(proto, name, args, comment) { + if (debug) + print("Processing " + proto + ".prototype." + name + " " + args + " " + comment); + return "<H2> Method " + proto + ".prototype." + name + "</H2>" + + "<PRE>" + + proto + ".prototype." + name + " = function(" + args + ")" + + "</PRE>" + + processComment(comment,0,name) + + "<P><BR><BR>"; +} + + +/** + * Process comment. + * @param comment the text of the comment + * @param firstLine shows if comment is at the beginning of the file + * @param fname name of the file (without path) + * @return a string for the HTML text of the documentation + */ +function processComment(comment,firstLine,fname) { + var tags = {}; + // Use the "lambda" form of regular expression replace, + // where the replacement object is a function rather + // than a string. The function is called with the + // matched text and any parenthetical matches as + // arguments, and the result of the function used as the + // replacement text. + // Here we use the function to build up the "tags" object, + // which has a property for each "@" tag that is the name + // of the tag, and whose value is an array of the + // text following that tag. + comment = comment.replace(/@(\w+)\s+([^@]*)/g, + function (s, name, text) { + var a = tags[name] || []; + a.push(text); + tags[name] = a; + return ""; + }); + + // if we have a comment at the beginning of a file + // store the comment for the index file + if (firstLine) { + indexFileArray[fname] = comment; + } + + var out = comment + '<P>'; + if (tags["param"]) { + // Create a table of parameters and their descriptions. + var array = tags["param"]; + var params = ""; + for (var i=0; i < array.length; i++) { + var m = array[i].match(/(\w+)\s+(.*)/); + params += '<TR><TD><I>'+m[1]+'</I></TD>' + + '<TD>'+m[2]+'</TD></TR>'; + } + out += '<TABLE WIDTH="90%" BORDER=1>'; + out += '<TR BGCOLOR=0xdddddddd>'; + out += '<TD><B>Parameter</B></TD>'; + out += '<TD><B>Description</B></TD></TR>'; + out += params; + out += '</TABLE><P>'; + } + if (tags["return"]) { + out += "<DT><B>Returns:</B><DD>"; + out += tags["return"][0] + "</DL><P>"; + } + if (tags["author"]) { + // List the authors together, separated by commas. + out += '<DT><B>Author:</B><DD>'; + var array = tags["author"]; + for (var i=0; i < array.length; i++) { + out += array[i]; + if (i+1 < array.length) + out += ", "; + } + out += '</DL><P>'; + } + if (tags["version"]) { + // Show the version. + out += '<DT><B>Version:</B><DD>'; + var array = tags["version"]; + for (var i=0; i < array.length; i++) { + out += array[i]; + if (i+1 < array.length) + out += "<BR><DD>"; + } + out += '</DL><P>'; + } + if (tags["see"]) { + // List the see modules together, separated by <BR>. + out += '<DT><B>Dependencies:</B><DD>'; + var array = tags["see"]; + for (var i=0; i < array.length; i++) { + out += array[i]; + if (i+1 < array.length) + out += "<BR><DD>"; + } + out += '</DL><P>'; + } + if (tags["lastmodified"]) { + // Shows a last modified description with client-side js. + out += '<DT><B>Last modified:</B><DD>'; + out += '<script><!--\n'; + out += 'document.writeln(document.lastModified);\n'; + out += '// ---></script>\n'; + out += '</DL><P>'; + } + + // additional tags can be added here (i.e., "if (tags["see"])...") + return out; +} + +/** + * Create an html output file + * @param outputdir directory to put the file + * @param htmlfile name of the file +*/ +function CreateOutputFile(outputdir,htmlfile) +{ + if (outputdir==null) + { + var outname = htmlfile; + } + else + { + var separator = Packages.java.io.File.separator; + var outname = outputdir + separator + htmlfile.substring(htmlfile.lastIndexOf(separator),htmlfile.length); + } + print("output file: " + outname); + return new File(outname); +} + +/** + * Process a javascript file. Puts the generated HTML file in the outdir + * @param filename name of the javascript file + * @inputdir input directory of the file (default null) + */ +function processJSFile(filename,inputdir) +{ + if (debug) print("filename = " + filename + " inputdir = " + inputdir); + + if (!filename.match(/\.js$/)) { + print("Expected filename to end in '.js'; had instead " + + filename + ". I don't treat the file."); + } else { + if (inputdir==null) + { + var inname = filename; + } + else + { + var separator = Packages.java.io.File.separator; + var inname = inputdir + separator + filename; + } + print("Processing file " + inname); + + var f = new File(inname); + + // create the output file + var htmlfile = filename.replace(/\.js$/, ".html"); + + var out = CreateOutputFile(outputdir,htmlfile); + + processFile(f, filename, inputdir, out); + out.close(); + } +} + +/** + * Generate index files containing links to the processed javascript files + * and the generated functions + */ +function GenerateIndex(dirname) +{ + // construct the files index file + var out = CreateOutputFile(outputdir,indexFile); + + // write the beginning of the file + out.writeLine('<HTML><HEADER><TITLE>File Index - directory: ' + dirname + '</TITLE><BODY>'); + out.writeLine('<H1>File Index - directory: ' + dirname + '</H1>\n'); + out.writeLine('<TABLE WIDTH="90%" BORDER=1>'); + out.writeLine('<TR BGCOLOR=0xdddddddd>'); + out.writeLine('<TD><B>File</B></TD>'); + out.writeLine('<TD><B>Description</B></TD></TR>'); + + var separator = Packages.java.io.File.separator; + + // sort the index file array + var SortedFileArray = []; + for (var fname in indexFileArray) + SortedFileArray.push(fname); + SortedFileArray.sort(); + + for (var i=0; i < SortedFileArray.length; i++) { + var fname = SortedFileArray[i]; + var htmlfile = fname.replace(/\.js$/, ".html"); + out.writeLine('<TR><TD><A HREF=\"' + htmlfile + '\">' + fname + '</A></TD></TD><TD>'); + if (indexFileArray[fname]) + out.writeLine(indexFileArray[fname]); + else + out.writeLine('No comments'); + out.writeLine('</TD></TR>\n'); + } + out.writeLine('</TABLE></BODY></HTML>'); + out.close(); + + // construct the functions index file + var out = CreateOutputFile(outputdir,indexFunction); + + // write the beginning of the file + out.writeLine('<HTML><HEADER><TITLE>Function Index - directory: ' + dirname + '</TITLE><BODY>'); + out.writeLine('<H1>Function Index - directory: ' + dirname + '</H1>\n'); + out.writeLine('<TABLE WIDTH="90%" BORDER=1>'); + out.writeLine('<TR BGCOLOR=0xdddddddd>'); + out.writeLine('<TD><B>Function</B></TD>'); + out.writeLine('<TD><B>Files</B></TD></TR>'); + + // sort the function array + var SortedFunctionArray = []; + for (var functionname in indexFunctionArray) + SortedFunctionArray.push(functionname); + SortedFunctionArray.sort(); + + for (var j=0; j < SortedFunctionArray.length; j++) { + var funcname = SortedFunctionArray[j]; + with (indexFunctionArray[funcname]) { + var outstr = '<TR><TD>' + funcname + '</TD><TD>'; + var filelst = filename.split("|"); + for (var i in filelst) { + var htmlfile = filelst[i].replace(/\.js$/, ".html"); + outstr += '<A HREF=\"' + htmlfile + '#' + funcname + '\">' + filelst[i] + '</A> '; + } + outstr += '</TD></TR>'; + out.writeLine(outstr); + } + } + out.writeLine('</TABLE></BODY></HTML>'); + out.close(); +} + + +/** + * prints the options for JSDoc +*/ +function PrintOptions() +{ + print("You can use the following options:\n"); + print("-d: specify an output directory for the generated html files\n"); + print("-i: processes all files in an input directory (you can specify several directories)\n"); + quit(); +} + + +// Main Script +// first read the arguments +if (! arguments) + PrintOptions(); + +for (var i=0; i < arguments.length; i++) { + if (debug) print("argument: + \'" + arguments[i] + "\'"); + if (arguments[i].match(/^\-/)) { + if (String(arguments[i])=="-d"){ + // output directory for the generated html files + + outputdir = String(arguments[i+1]); + if (debug) print("outputdir: + \'" + outputdir + "\'"); + + i++; + } + else if (String(arguments[i])=="-i"){ + // process all files in an input directory + + DirList.push(String(arguments[i+1])); +if (debug) print("inputdir: + \'" + arguments[i+1] + "\'"); + i++; + } + else { + print("Unknown option: " + arguments[i] + "\n"); + PrintOptions(); + } + } + else + { + // we have a single file + if (debug) print("file: + \'" + arguments[i] + "\'"); + + FileList.push(String(arguments[i])); + } +} + +// first handle the single files +for (var i in FileList) + processJSFile(FileList[i],null); + +// then handle the input directories +for (var j in DirList) { + var inputdir = String(DirList[j]); + + print("Process input directory: " + inputdir); + + // clean up index arrays + var indexFileArray = []; + var indexFunctionArray = []; + + // for the directory name get rid of ../../ or ..\..\ + inputDirName = inputdir.replace(/\.\.\/|\.\.\\/g,""); + + indexFile = indexFileName + "_" + inputDirName + ".html"; + indexFunction = indexFunctionName + "_" + inputDirName + ".html"; + +print("indexFile = " + indexFile); +print("indexFunction = " + indexFunction); + + // read the files in the directory + var DirFile = new java.io.File(inputdir); + var lst = DirFile.list(); + var separator = Packages.java.io.File.separator; + + for (var i=0; i < lst.length; i++) + { + processJSFile(String(lst[i]),inputdir); + } + + // generate the index files for the input directory + GenerateIndex(inputDirName); +} + + + diff --git a/trunk/infrastructure/rhino1_7R1/examples/liveConnect.js b/trunk/infrastructure/rhino1_7R1/examples/liveConnect.js new file mode 100644 index 0000000..7befc08 --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/liveConnect.js @@ -0,0 +1,57 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * liveConnect.js: a simple demonstration of JavaScript-to-Java connectivity + */ + +// Create a new StringBuffer. Note that the class name must be fully qualified +// by its package. Packages other than "java" must start with "Packages", i.e., +// "Packages.javax.servlet...". +var sb = new java.lang.StringBuffer(); + +// Now add some stuff to the buffer. +sb.append("hi, mom"); +sb.append(3); // this will add "3.0" to the buffer since all JS numbers + // are doubles by default +sb.append(true); + +// Now print it out. (The toString() method of sb is automatically called +// to convert the buffer to a string.) +// Should print "hi, mom3.0true". +print(sb); diff --git a/trunk/infrastructure/rhino1_7R1/examples/unique.js b/trunk/infrastructure/rhino1_7R1/examples/unique.js new file mode 100644 index 0000000..a4274bb --- /dev/null +++ b/trunk/infrastructure/rhino1_7R1/examples/unique.js @@ -0,0 +1,56 @@ +/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Rhino code, released + * May 6, 1999. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1997-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Norris Boyd + * + * Alternatively, the contents of this file may be used under the terms of + * the GNU General Public License Version 2 or later (the "GPL"), in which + * case the provisions of the GPL are applicable instead of those above. If + * you wish to allow use of your version of this file only under the terms of + * the GPL and not to allow others to use your version of this file under the + * MPL, indicate your decision by deleting the provisions above and replacing + * them with the notice and other provisions required by the GPL. If you do + * not delete the provisions above, a recipient may use your version of this + * file under either the MPL or the GPL. + * + * ***** END LICENSE BLOCK ***** */ + +// unique.js: read the contents of a file and print out the unique lines + +defineClass("File") + +// "arguments[0]" refers to the first argument at the command line to the +// script, if present. If not present, "arguments[0]" will be undefined, +// which will cause f to read from System.in. +var f = new File(arguments[0]); +var o = {} +var line; +while ((line = f.readLine()) != null) { + // Use JavaScript objects' inherent nature as an associative + // array to provide uniqueness + o[line] = true; +} +for (i in o) { + print(i); +} |