/* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * jrunscript JavaScript built-in functions and objects. */ /** * Creates an object that delegates all method calls on * it to the 'invoke' method on the given delegate object.<br> * * Example: * <pre> * <code> * var x = { invoke: function(name, args) { //code...} * var y = new JSInvoker(x); * y.func(3, 3); // calls x.invoke('func', args); where args is array of arguments * </code> * </pre> * @param obj object to be wrapped by JSInvoker * @constructor */function JSInvoker(obj) { return new JSAdapter({ __get__ : function(name) { return function() { return obj.invoke(name, arguments); } } });} /** * This variable represents OS environment. Environment * variables can be accessed as fields of this object. For * example, env.PATH will return PATH value configured. */var env = new JSAdapter({ __get__ : function (name) { return java.lang.System.getenv(name); }, __has__ : function (name) { return java.lang.System.getenv().containsKey(name); }, __getIds__ : function() { return java.lang.System.getenv().keySet().toArray(); }, __delete__ : function(name) { println("can't delete env item"); }, __put__ : function (name, value) { println("can't change env item"); }, toString: function() { return java.lang.System.getenv().toString(); } }); /** * Creates a convenient script object to deal with java.util.Map instances. * The result script object's field names are keys of the Map. For example, * scriptObj.keyName can be used to access value associated with given key.<br> * Example: * <pre> * <code> * var x = java.lang.SystemProperties(); * var y = jmap(x); * println(y['java.class.path']); // prints java.class.path System property * delete y['java.class.path']; // remove java.class.path System property * </code> * </pre> * * @param map java.util.Map instance that will be wrapped * @constructor */function jmap(map) { return new JSAdapter({ __get__ : function(name) { if (map.containsKey(name)) { return map.get(name); } else { return undefined; } }, __has__ : function(name) { return map.containsKey(name); }, __delete__ : function (name) { return map.remove(name); }, __put__ : function(name, value) { map.put(name, value); }, __getIds__ : function() { return map.keySet().toArray(); }, toString: function() { return map.toString(); } });} /** * Creates a convenient script object to deal with java.util.List instances. * The result script object behaves like an array. For example, * scriptObj[index] syntax can be used to access values in the List instance. * 'length' field gives size of the List. <br> * * Example: * <pre> * <code> * var x = new java.util.ArrayList(4); * x.add('Java'); * x.add('JavaScript'); * x.add('SQL'); * x.add('XML'); * * var y = jlist(x); * println(y[2]); // prints third element of list * println(y.length); // prints size of the list * * @param map java.util.List instance that will be wrapped * @constructor */function jlist(list) { function isValid(index) { return typeof(index) == 'number' && index > -1 && index < list.size(); } return new JSAdapter({ __get__ : function(name) { if (isValid(name)) { return list.get(name); } else if (name == 'length') { return list.size(); } else { return undefined; } }, __has__ : function (name) { return isValid(name) || name == 'length'; }, __delete__ : function(name) { if (isValid(name)) { list.remove(name); } }, __put__ : function(name, value) { if (isValid(name)) { list.set(name, value); } }, __getIds__: function() { var res = new Array(list.size()); for (var i = 0; i < res.length; i++) { res[i] = i; } return res; }, toString: function() { return list.toString(); } });} /** * This is java.lang.System properties wrapped by jmap. * For eg. to access java.class.path property, you can use * the syntax sysProps["java.class.path"] */var sysProps = jmap(java.lang.System.getProperties()); // stdout, stderr & stdinvar out = java.lang.System.out;var err = java.lang.System.err;// can't use 'in' because it is a JavaScript keyword :-(var inp = java.lang.System["in"]; // useful imports for often used io, net classesimportPackage(java.io);importPackage(java.net); /** * Generic any object to input stream mapper * @param str input file name, URL or InputStream * @return InputStream object * @private */function inStream(str) { if (typeof(str) == "string") { // '-' means standard input if (str == '-') { return java.lang.System["in"]; } // try file first var file = null; try { file = pathToFile(str); } catch (e) { } if (file && file.exists()) { return new FileInputStream(file); } else { try { // treat the string as URL return new URL(str).openStream(); } catch (e) { throw 'file or URL ' + str + ' not found'; } } } else { if (str instanceof InputStream) { return str; } else if (str instanceof URL) { return str.openStream(); } else if (str instanceof File) { return new FileInputStream(str); } } // everything failed, just give input stream return java.lang.System["in"];} /** * Generic any object to output stream mapper * * @param out output file name or stream * @return OutputStream object * @private */function outStream(out) { if (typeof(out) == "string") { if (out == '>') { return java.lang.System.out; } else { // treat it as file return new FileOutputStream(pathToFile(out)); } } else { if (out instanceof OutputStream) { return out; } else if (out instanceof File) { return new FileOutputStream(out); } } // everything failed, just return System.out return java.lang.System.out;} /** * stream close takes care not to close stdin, out & err. * @private */function streamClose(stream) { if (stream) { if (stream != java.lang.System["in"] && stream != java.lang.System.out && stream != java.lang.System.err) { try { stream.close(); } catch (e) { println(e); } } }} /** * Loads and evaluates JavaScript code from a stream or file or URL<br> * * Examples: * <pre> * <code> * load('test.js'); // load script file 'test.js' * load('http://java.sun.com/foo.js'); // load from a URL * </code> * </pre> * * @param str input from which script is loaded and evaluated */function load(str) { var stream = inStream(str); var bstream = new BufferedInputStream(stream); var reader = new BufferedReader(new InputStreamReader(bstream)); var oldFilename = engine.get(engine.FILENAME); engine.put(engine.FILENAME, str); try { engine.eval(reader); } finally { engine.put(engine.FILENAME, oldFilename); streamClose(stream); }} // file system utilities /** * Creates a Java byte[] of given length * @param len size of the array to create * @private */function javaByteArray(len) { return java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, len);} var curDir = new File('.'); /** * Print present working directory */function pwd() { println(curDir.getAbsolutePath());} /** * Changes present working directory to given directory * @param target directory to change to. optional, defaults to user's HOME */function cd(target) { if (target == undefined) { target = sysProps["user.home"]; } if (!(target instanceof File)) { target = pathToFile(target); } if (target.exists() && target.isDirectory()) { curDir = target; } else { println(target + " is not a directory"); }} /** * Converts path to java.io.File taking care of shell present working dir * * @param pathname file path to be converted * @private */function pathToFile(pathname) { var tmp = pathname; if (!(tmp instanceof File)) { tmp = new File(tmp); } if (!tmp.isAbsolute()) { return new File(curDir, pathname); } else { return tmp; }} /** * Copies a file or URL or stream to another file or stream * * @param from input file or URL or stream * @param to output stream or file */function cp(from, to) { if (from == to) { println("file " + from + " cannot be copied onto itself!"); return; } var inp = inStream(from); var out = outStream(to); var binp = new BufferedInputStream(inp); var bout = new BufferedOutputStream(out); var buff = javaByteArray(1024); var len; while ((len = binp.read(buff)) > 0 ) bout.write(buff, 0, len); bout.flush(); streamClose(inp); streamClose(out); } /** * Shows the content of a file or URL or any InputStream<br> * Examples: * <pre> * <code> * cat('test.txt'); // show test.txt file contents * cat('http://java.net'); // show the contents from the URL http://java.net * </code> * </pre> * @param obj input to show * @param pattern optional. show only the lines matching the pattern */function cat(obj, pattern) { if (obj instanceof File && obj.isDirectory()) { ls(obj); return; } var inp = null; if (!(obj instanceof Reader)) { inp = inStream(obj); obj = new BufferedReader(new InputStreamReader(inp)); } var line; if (pattern) { var count = 1; while ((line=obj.readLine()) != null) { if (line.match(pattern)) { println(count + "\t: " + line); } count++; } } else { while ((line=obj.readLine()) != null) { println(line); } }} /** * Returns directory part of a filename * * @param pathname input path name * @return directory part of the given file name */function dirname(pathname) { var dirName = "."; // Normalize '/' to local file separator before work. var i = pathname.replace('/', File.separatorChar ).lastIndexOf( File.separator ); if ( i != -1 ) dirName = pathname.substring(0, i); return dirName;} /** * Creates a new dir of given name * * @param dir name of the new directory */function mkdir(dir) { var dir = pathToFile(dir); println(dir.mkdir()? "created" : "can not create dir");} /** * Creates the directory named by given pathname, including * any necessary but nonexistent parent directories. * * @param dir input path name */function mkdirs(dir) { var dir = pathToFile(dir); println(dir.mkdirs()? "created" : "can not create dirs");} /** * Removes a given file * * @param pathname name of the file */function rm(pathname) { file = pathToFile(pathname); if (!file.exists()) { println("file not found: " + pathname); return false; } // note that delete is a keyword in JavaScript! println(file["delete"]()? "deleted" : "can not delete");} /** * Removes a given directory * * @param pathname name of the directory */function rmdir(pathname) { rm(pathname);} /**Lines 1–500 of 884. Load more
/* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * jrunscript JavaScript built-in functions and objects. */ /** * Creates an object that delegates all method calls on * it to the 'invoke' method on the given delegate object.<br> * * Example: * <pre> * <code> * var x = { invoke: function(name, args) { //code...} * var y = new JSInvoker(x); * y.func(3, 3); // calls x.invoke('func', args); where args is array of arguments * </code> * </pre> * @param obj object to be wrapped by JSInvoker * @constructor */ function JSInvoker(obj) { return new JSAdapter({ __get__ : function(name) { return function() { return obj.invoke(name, arguments); } } }); } /** * This variable represents OS environment. Environment * variables can be accessed as fields of this object. For * example, env.PATH will return PATH value configured. */ var env = new JSAdapter({ __get__ : function (name) { return java.lang.System.getenv(name); }, __has__ : function (name) { return java.lang.System.getenv().containsKey(name); }, __getIds__ : function() { return java.lang.System.getenv().keySet().toArray(); }, __delete__ : function(name) { println("can't delete env item"); }, __put__ : function (name, value) { println("can't change env item"); }, toString: function() { return java.lang.System.getenv().toString(); } }); /** * Creates a convenient script object to deal with java.util.Map instances. * The result script object's field names are keys of the Map. For example, * scriptObj.keyName can be used to access value associated with given key.<br> * Example: * <pre> * <code> * var x = java.lang.SystemProperties(); * var y = jmap(x); * println(y['java.class.path']); // prints java.class.path System property * delete y['java.class.path']; // remove java.class.path System property * </code> * </pre> * * @param map java.util.Map instance that will be wrapped * @constructor */ function jmap(map) { return new JSAdapter({ __get__ : function(name) { if (map.containsKey(name)) { return map.get(name); } else { return undefined; } }, __has__ : function(name) { return map.containsKey(name); }, __delete__ : function (name) { return map.remove(name); }, __put__ : function(name, value) { map.put(name, value); }, __getIds__ : function() { return map.keySet().toArray(); }, toString: function() { return map.toString(); } }); } /** * Creates a convenient script object to deal with java.util.List instances. * The result script object behaves like an array. For example, * scriptObj[index] syntax can be used to access values in the List instance. * 'length' field gives size of the List. <br> * * Example: * <pre> * <code> * var x = new java.util.ArrayList(4); * x.add('Java'); * x.add('JavaScript'); * x.add('SQL'); * x.add('XML'); * * var y = jlist(x); * println(y[2]); // prints third element of list * println(y.length); // prints size of the list * * @param map java.util.List instance that will be wrapped * @constructor */ function jlist(list) { function isValid(index) { return typeof(index) == 'number' && index > -1 && index < list.size(); } return new JSAdapter({ __get__ : function(name) { if (isValid(name)) { return list.get(name); } else if (name == 'length') { return list.size(); } else { return undefined; } }, __has__ : function (name) { return isValid(name) || name == 'length'; }, __delete__ : function(name) { if (isValid(name)) { list.remove(name); } }, __put__ : function(name, value) { if (isValid(name)) { list.set(name, value); } }, __getIds__: function() { var res = new Array(list.size()); for (var i = 0; i < res.length; i++) { res[i] = i; } return res; }, toString: function() { return list.toString(); } }); } /** * This is java.lang.System properties wrapped by jmap. * For eg. to access java.class.path property, you can use * the syntax sysProps["java.class.path"] */ var sysProps = jmap(java.lang.System.getProperties()); // stdout, stderr & stdin var out = java.lang.System.out; var err = java.lang.System.err; // can't use 'in' because it is a JavaScript keyword :-( var inp = java.lang.System["in"]; // useful imports for often used io, net classes importPackage(java.io); importPackage(java.net); /** * Generic any object to input stream mapper * @param str input file name, URL or InputStream * @return InputStream object * @private */ function inStream(str) { if (typeof(str) == "string") { // '-' means standard input if (str == '-') { return java.lang.System["in"]; } // try file first var file = null; try { file = pathToFile(str); } catch (e) { } if (file && file.exists()) { return new FileInputStream(file); } else { try { // treat the string as URL return new URL(str).openStream(); } catch (e) { throw 'file or URL ' + str + ' not found'; } } } else { if (str instanceof InputStream) { return str; } else if (str instanceof URL) { return str.openStream(); } else if (str instanceof File) { return new FileInputStream(str); } } // everything failed, just give input stream return java.lang.System["in"]; } /** * Generic any object to output stream mapper * * @param out output file name or stream * @return OutputStream object * @private */ function outStream(out) { if (typeof(out) == "string") { if (out == '>') { return java.lang.System.out; } else { // treat it as file return new FileOutputStream(pathToFile(out)); } } else { if (out instanceof OutputStream) { return out; } else if (out instanceof File) { return new FileOutputStream(out); } } // everything failed, just return System.out return java.lang.System.out; } /** * stream close takes care not to close stdin, out & err. * @private */ function streamClose(stream) { if (stream) { if (stream != java.lang.System["in"] && stream != java.lang.System.out && stream != java.lang.System.err) { try { stream.close(); } catch (e) { println(e); } } } } /** * Loads and evaluates JavaScript code from a stream or file or URL<br> * * Examples: * <pre> * <code> * load('test.js'); // load script file 'test.js' * load('http://java.sun.com/foo.js'); // load from a URL * </code> * </pre> * * @param str input from which script is loaded and evaluated */ function load(str) { var stream = inStream(str); var bstream = new BufferedInputStream(stream); var reader = new BufferedReader(new InputStreamReader(bstream)); var oldFilename = engine.get(engine.FILENAME); engine.put(engine.FILENAME, str); try { engine.eval(reader); } finally { engine.put(engine.FILENAME, oldFilename); streamClose(stream); } } // file system utilities /** * Creates a Java byte[] of given length * @param len size of the array to create * @private */ function javaByteArray(len) { return java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, len); } var curDir = new File('.'); /** * Print present working directory */ function pwd() { println(curDir.getAbsolutePath()); } /** * Changes present working directory to given directory * @param target directory to change to. optional, defaults to user's HOME */ function cd(target) { if (target == undefined) { target = sysProps["user.home"]; } if (!(target instanceof File)) { target = pathToFile(target); } if (target.exists() && target.isDirectory()) { curDir = target; } else { println(target + " is not a directory"); } } /** * Converts path to java.io.File taking care of shell present working dir * * @param pathname file path to be converted * @private */ function pathToFile(pathname) { var tmp = pathname; if (!(tmp instanceof File)) { tmp = new File(tmp); } if (!tmp.isAbsolute()) { return new File(curDir, pathname); } else { return tmp; } } /** * Copies a file or URL or stream to another file or stream * * @param from input file or URL or stream * @param to output stream or file */ function cp(from, to) { if (from == to) { println("file " + from + " cannot be copied onto itself!"); return; } var inp = inStream(from); var out = outStream(to); var binp = new BufferedInputStream(inp); var bout = new BufferedOutputStream(out); var buff = javaByteArray(1024); var len; while ((len = binp.read(buff)) > 0 ) bout.write(buff, 0, len); bout.flush(); streamClose(inp); streamClose(out); } /** * Shows the content of a file or URL or any InputStream<br> * Examples: * <pre> * <code> * cat('test.txt'); // show test.txt file contents * cat('http://java.net'); // show the contents from the URL http://java.net * </code> * </pre> * @param obj input to show * @param pattern optional. show only the lines matching the pattern */ function cat(obj, pattern) { if (obj instanceof File && obj.isDirectory()) { ls(obj); return; } var inp = null; if (!(obj instanceof Reader)) { inp = inStream(obj); obj = new BufferedReader(new InputStreamReader(inp)); } var line; if (pattern) { var count = 1; while ((line=obj.readLine()) != null) { if (line.match(pattern)) { println(count + "\t: " + line); } count++; } } else { while ((line=obj.readLine()) != null) { println(line); } } } /** * Returns directory part of a filename * * @param pathname input path name * @return directory part of the given file name */ function dirname(pathname) { var dirName = "."; // Normalize '/' to local file separator before work. var i = pathname.replace('/', File.separatorChar ).lastIndexOf( File.separator ); if ( i != -1 ) dirName = pathname.substring(0, i); return dirName; } /** * Creates a new dir of given name * * @param dir name of the new directory */ function mkdir(dir) { var dir = pathToFile(dir); println(dir.mkdir()? "created" : "can not create dir"); } /** * Creates the directory named by given pathname, including * any necessary but nonexistent parent directories. * * @param dir input path name */ function mkdirs(dir) { var dir = pathToFile(dir); println(dir.mkdirs()? "created" : "can not create dirs"); } /** * Removes a given file * * @param pathname name of the file */ function rm(pathname) { file = pathToFile(pathname); if (!file.exists()) { println("file not found: " + pathname); return false; } // note that delete is a keyword in JavaScript! println(file["delete"]()? "deleted" : "can not delete"); } /** * Removes a given directory * * @param pathname name of the directory */ function rmdir(pathname) { rm(pathname); } /**