提交 4a9e7c12 编写于 作者: S sundar

8010136: Make jrunscript's init.js to work on nashorn

Reviewed-by: lagergren, hannesw
上级 f257643d
/* /*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
*/ */
/** /**
* Creates an object that delegates all method calls on * Creates an object that delegates all method calls on
* it to the 'invoke' method on the given delegate object.<br> * it to the 'invoke' method on the given delegate object.<br>
* *
* Example: * Example:
...@@ -43,13 +43,13 @@ ...@@ -43,13 +43,13 @@
* @constructor * @constructor
*/ */
function JSInvoker(obj) { function JSInvoker(obj) {
return new JSAdapter({ return new JSAdapter({
__get__ : function(name) { __get__ : function(name) {
return function() { return function() {
return obj.invoke(name, arguments); return obj.invoke(name, arguments);
} }
} }
}); });
} }
/** /**
...@@ -58,24 +58,24 @@ function JSInvoker(obj) { ...@@ -58,24 +58,24 @@ function JSInvoker(obj) {
* example, env.PATH will return PATH value configured. * example, env.PATH will return PATH value configured.
*/ */
var env = new JSAdapter({ var env = new JSAdapter({
__get__ : function (name) { __get__ : function (name) {
return java.lang.System.getenv(name); return java.lang.System.getenv(name);
}, },
__has__ : function (name) { __has__ : function (name) {
return java.lang.System.getenv().containsKey(name); return java.lang.System.getenv().containsKey(name);
}, },
__getIds__ : function() { __getIds__ : function() {
return java.lang.System.getenv().keySet().toArray(); return java.lang.System.getenv().keySet().toArray();
}, },
__delete__ : function(name) { __delete__ : function(name) {
println("can't delete env item"); println("can't delete env item");
}, },
__put__ : function (name, value) { __put__ : function (name, value) {
println("can't change env item"); println("can't change env item");
}, },
toString: function() { toString: function() {
return java.lang.System.getenv().toString(); return java.lang.System.getenv().toString();
} }
}); });
/** /**
...@@ -91,36 +91,36 @@ var env = new JSAdapter({ ...@@ -91,36 +91,36 @@ var env = new JSAdapter({
* delete y['java.class.path']; // remove java.class.path System property * delete y['java.class.path']; // remove java.class.path System property
* </code> * </code>
* </pre> * </pre>
* *
* @param map java.util.Map instance that will be wrapped * @param map java.util.Map instance that will be wrapped
* @constructor * @constructor
*/ */
function jmap(map) { function jmap(map) {
return new JSAdapter({ return new JSAdapter({
__get__ : function(name) { __get__ : function(name) {
if (map.containsKey(name)) { if (map.containsKey(name)) {
return map.get(name); return map.get(name);
} else { } else {
return undefined; return undefined;
} }
}, },
__has__ : function(name) { __has__ : function(name) {
return map.containsKey(name); return map.containsKey(name);
}, },
__delete__ : function (name) { __delete__ : function (name) {
return map.remove(name); return map.remove(name);
}, },
__put__ : function(name, value) { __put__ : function(name, value) {
map.put(name, value); map.put(name, value);
}, },
__getIds__ : function() { __getIds__ : function() {
return map.keySet().toArray(); return map.keySet().toArray();
}, },
toString: function() { toString: function() {
return map.toString(); return map.toString();
} }
}); });
} }
/** /**
...@@ -146,52 +146,72 @@ function jmap(map) { ...@@ -146,52 +146,72 @@ function jmap(map) {
* @constructor * @constructor
*/ */
function jlist(list) { function jlist(list) {
function isValid(index) { function isValid(index) {
return typeof(index) == 'number' && return typeof(index) == 'number' &&
index > -1 && index < list.size(); index > -1 && index < list.size();
} }
return new JSAdapter({ return new JSAdapter({
__get__ : function(name) { __get__ : function(name) {
if (isValid(name)) { if (isValid(name)) {
return list.get(name); return list.get(name);
} else if (name == 'length') { } else if (name == 'length') {
return list.size(); return list.size();
} else { } else {
return undefined; return undefined;
} }
}, },
__has__ : function (name) { __has__ : function (name) {
return isValid(name) || name == 'length'; return isValid(name) || name == 'length';
}, },
__delete__ : function(name) { __delete__ : function(name) {
if (isValid(name)) { if (isValid(name)) {
list.remove(name); list.remove(name);
} }
}, },
__put__ : function(name, value) { __put__ : function(name, value) {
if (isValid(name)) { if (isValid(name)) {
list.set(name, value); list.set(name, value);
} }
}, },
__getIds__: function() { __getIds__: function() {
var res = new Array(list.size()); var res = new Array(list.size());
for (var i = 0; i < res.length; i++) { for (var i = 0; i < res.length; i++) {
res[i] = i; res[i] = i;
} }
return res; return res;
}, },
toString: function() { toString: function() {
return list.toString(); return list.toString();
} }
}); });
} }
/** /**
* This is java.lang.System properties wrapped by jmap. * This is java.lang.System properties wrapped by JSAdapter.
* For eg. to access java.class.path property, you can use * For eg. to access java.class.path property, you can use
* the syntax sysProps["java.class.path"] * the syntax sysProps["java.class.path"]
*/ */
var sysProps = jmap(java.lang.System.getProperties()); var sysProps = new JSAdapter({
__get__ : function (name) {
return java.lang.System.getProperty(name);
},
__has__ : function (name) {
return java.lang.System.getProperty(name) != null;
},
__getIds__ : function() {
return java.lang.System.getProperties().keySet().toArray();
},
__delete__ : function(name) {
java.lang.System.clearProperty(name);
return true;
},
__put__ : function (name, value) {
java.lang.System.setProperty(name, value);
},
toString: function() {
return "<system properties>";
}
});
// stdout, stderr & stdin // stdout, stderr & stdin
var out = java.lang.System.out; var out = java.lang.System.out;
...@@ -199,76 +219,85 @@ var err = java.lang.System.err; ...@@ -199,76 +219,85 @@ var err = java.lang.System.err;
// can't use 'in' because it is a JavaScript keyword :-( // can't use 'in' because it is a JavaScript keyword :-(
var inp = java.lang.System["in"]; var inp = java.lang.System["in"];
// useful imports for often used io, net classes var BufferedInputStream = java.io.BufferedInputStream;
importPackage(java.io); var BufferedOutputStream = java.io.BufferedOutputStream;
importPackage(java.net); var BufferedReader = java.io.BufferedReader;
var DataInputStream = java.io.DataInputStream;
var File = java.io.File;
var FileInputStream = java.io.FileInputStream;
var FileOutputStream = java.io.FileOutputStream;
var InputStream = java.io.InputStream;
var InputStreamReader = java.io.InputStreamReader;
var OutputStream = java.io.OutputStream;
var Reader = java.io.Reader;
var URL = java.net.URL;
/** /**
* Generic any object to input stream mapper * Generic any object to input stream mapper
* @param str input file name, URL or InputStream * @param str input file name, URL or InputStream
* @return InputStream object * @return InputStream object
* @private * @private
*/ */
function inStream(str) { function inStream(str) {
if (typeof(str) == "string") { if (typeof(str) == "string") {
// '-' means standard input // '-' means standard input
if (str == '-') { if (str == '-') {
return java.lang.System["in"]; return java.lang.System["in"];
} }
// try file first // try file first
var file = null; var file = null;
try { try {
file = pathToFile(str); file = pathToFile(str);
} catch (e) { } catch (e) {
} }
if (file && file.exists()) { if (file && file.exists()) {
return new FileInputStream(file); return new FileInputStream(file);
} else { } else {
try { try {
// treat the string as URL // treat the string as URL
return new URL(str).openStream(); return new URL(str).openStream();
} catch (e) { } catch (e) {
throw 'file or URL ' + str + ' not found'; throw 'file or URL ' + str + ' not found';
} }
} }
} else { } else {
if (str instanceof InputStream) { if (str instanceof InputStream) {
return str; return str;
} else if (str instanceof URL) { } else if (str instanceof URL) {
return str.openStream(); return str.openStream();
} else if (str instanceof File) { } else if (str instanceof File) {
return new FileInputStream(str); return new FileInputStream(str);
} }
} }
// everything failed, just give input stream // everything failed, just give input stream
return java.lang.System["in"]; return java.lang.System["in"];
} }
/** /**
* Generic any object to output stream mapper * Generic any object to output stream mapper
* *
* @param out output file name or stream * @param out output file name or stream
* @return OutputStream object * @return OutputStream object
* @private * @private
*/ */
function outStream(out) { function outStream(out) {
if (typeof(out) == "string") { if (typeof(out) == "string") {
if (out == '>') { if (out == '>') {
return java.lang.System.out; return java.lang.System.out;
} else { } else {
// treat it as file // treat it as file
return new FileOutputStream(pathToFile(out)); return new FileOutputStream(pathToFile(out));
} }
} else { } else {
if (out instanceof OutputStream) { if (out instanceof OutputStream) {
return out; return out;
} else if (out instanceof File) { } else if (out instanceof File) {
return new FileOutputStream(out); return new FileOutputStream(out);
} }
} }
// everything failed, just return System.out // everything failed, just return System.out
return java.lang.System.out; return java.lang.System.out;
} }
/** /**
...@@ -276,17 +305,17 @@ function outStream(out) { ...@@ -276,17 +305,17 @@ function outStream(out) {
* @private * @private
*/ */
function streamClose(stream) { function streamClose(stream) {
if (stream) { if (stream) {
if (stream != java.lang.System["in"] && if (stream != java.lang.System["in"] &&
stream != java.lang.System.out && stream != java.lang.System.out &&
stream != java.lang.System.err) { stream != java.lang.System.err) {
try { try {
stream.close(); stream.close();
} catch (e) { } catch (e) {
println(e); println(e);
} }
} }
} }
} }
/** /**
...@@ -302,18 +331,20 @@ function streamClose(stream) { ...@@ -302,18 +331,20 @@ function streamClose(stream) {
* *
* @param str input from which script is loaded and evaluated * @param str input from which script is loaded and evaluated
*/ */
function load(str) { if (typeof(load) == 'undefined') {
var stream = inStream(str); var load = function(str) {
var bstream = new BufferedInputStream(stream); var stream = inStream(str);
var reader = new BufferedReader(new InputStreamReader(bstream)); var bstream = new BufferedInputStream(stream);
var oldFilename = engine.get(engine.FILENAME); var reader = new BufferedReader(new InputStreamReader(bstream));
engine.put(engine.FILENAME, str); var oldFilename = engine.get(engine.FILENAME);
try { engine.put(engine.FILENAME, str);
engine.eval(reader); try {
} finally { engine.eval(reader);
engine.put(engine.FILENAME, oldFilename); } finally {
streamClose(stream); engine.put(engine.FILENAME, oldFilename);
} streamClose(stream);
}
}
} }
// file system utilities // file system utilities
...@@ -324,7 +355,7 @@ function load(str) { ...@@ -324,7 +355,7 @@ function load(str) {
* @private * @private
*/ */
function javaByteArray(len) { function javaByteArray(len) {
return java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, len); return java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, len);
} }
var curDir = new File('.'); var curDir = new File('.');
...@@ -333,7 +364,7 @@ var curDir = new File('.'); ...@@ -333,7 +364,7 @@ var curDir = new File('.');
* Print present working directory * Print present working directory
*/ */
function pwd() { function pwd() {
println(curDir.getAbsolutePath()); println(curDir.getAbsolutePath());
} }
/** /**
...@@ -341,17 +372,17 @@ function pwd() { ...@@ -341,17 +372,17 @@ function pwd() {
* @param target directory to change to. optional, defaults to user's HOME * @param target directory to change to. optional, defaults to user's HOME
*/ */
function cd(target) { function cd(target) {
if (target == undefined) { if (target == undefined) {
target = sysProps["user.home"]; target = sysProps["user.home"];
} }
if (!(target instanceof File)) { if (!(target instanceof File)) {
target = pathToFile(target); target = pathToFile(target);
} }
if (target.exists() && target.isDirectory()) { if (target.exists() && target.isDirectory()) {
curDir = target; curDir = target;
} else { } else {
println(target + " is not a directory"); println(target + " is not a directory");
} }
} }
/** /**
...@@ -361,15 +392,15 @@ function cd(target) { ...@@ -361,15 +392,15 @@ function cd(target) {
* @private * @private
*/ */
function pathToFile(pathname) { function pathToFile(pathname) {
var tmp = pathname; var tmp = pathname;
if (!(tmp instanceof File)) { if (!(tmp instanceof File)) {
tmp = new File(tmp); tmp = new File(tmp);
} }
if (!tmp.isAbsolute()) { if (!tmp.isAbsolute()) {
return new File(curDir, pathname); return new File(curDir, pathname);
} else { } else {
return tmp; return tmp;
} }
} }
/** /**
...@@ -379,22 +410,22 @@ function pathToFile(pathname) { ...@@ -379,22 +410,22 @@ function pathToFile(pathname) {
* @param to output stream or file * @param to output stream or file
*/ */
function cp(from, to) { function cp(from, to) {
if (from == to) { if (from == to) {
println("file " + from + " cannot be copied onto itself!"); println("file " + from + " cannot be copied onto itself!");
return; return;
} }
var inp = inStream(from); var inp = inStream(from);
var out = outStream(to); var out = outStream(to);
var binp = new BufferedInputStream(inp); var binp = new BufferedInputStream(inp);
var bout = new BufferedOutputStream(out); var bout = new BufferedOutputStream(out);
var buff = javaByteArray(1024); var buff = javaByteArray(1024);
var len; var len;
while ((len = binp.read(buff)) > 0 ) while ((len = binp.read(buff)) > 0 )
bout.write(buff, 0, len); bout.write(buff, 0, len);
bout.flush(); bout.flush();
streamClose(inp); streamClose(inp);
streamClose(out); streamClose(out);
} }
/** /**
...@@ -403,37 +434,37 @@ function cp(from, to) { ...@@ -403,37 +434,37 @@ function cp(from, to) {
* <pre> * <pre>
* <code> * <code>
* cat('test.txt'); // show test.txt file contents * cat('test.txt'); // show test.txt file contents
* cat('http://java.net'); // show the contents from the URL http://java.net * cat('http://java.net'); // show the contents from the URL http://java.net
* </code> * </code>
* </pre> * </pre>
* @param obj input to show * @param obj input to show
* @param pattern optional. show only the lines matching the pattern * @param pattern optional. show only the lines matching the pattern
*/ */
function cat(obj, pattern) { function cat(obj, pattern) {
if (obj instanceof File && obj.isDirectory()) { if (obj instanceof File && obj.isDirectory()) {
ls(obj); ls(obj);
return; return;
} }
var inp = null; var inp = null;
if (!(obj instanceof Reader)) { if (!(obj instanceof Reader)) {
inp = inStream(obj); inp = inStream(obj);
obj = new BufferedReader(new InputStreamReader(inp)); obj = new BufferedReader(new InputStreamReader(inp));
} }
var line; var line;
if (pattern) { if (pattern) {
var count = 1; var count = 1;
while ((line=obj.readLine()) != null) { while ((line=obj.readLine()) != null) {
if (line.match(pattern)) { if (line.match(pattern)) {
println(count + "\t: " + line); println(count + "\t: " + line);
} }
count++; count++;
} }
} else { } else {
while ((line=obj.readLine()) != null) { while ((line=obj.readLine()) != null) {
println(line); println(line);
} }
} }
} }
/** /**
...@@ -443,13 +474,13 @@ function cat(obj, pattern) { ...@@ -443,13 +474,13 @@ function cat(obj, pattern) {
* @return directory part of the given file name * @return directory part of the given file name
*/ */
function dirname(pathname) { function dirname(pathname) {
var dirName = "."; var dirName = ".";
// Normalize '/' to local file separator before work. // Normalize '/' to local file separator before work.
var i = pathname.replace('/', File.separatorChar ).lastIndexOf( var i = pathname.replace('/', File.separatorChar ).lastIndexOf(
File.separator ); File.separator );
if ( i != -1 ) if ( i != -1 )
dirName = pathname.substring(0, i); dirName = pathname.substring(0, i);
return dirName; return dirName;
} }
/** /**
...@@ -458,34 +489,34 @@ function dirname(pathname) { ...@@ -458,34 +489,34 @@ function dirname(pathname) {
* @param dir name of the new directory * @param dir name of the new directory
*/ */
function mkdir(dir) { function mkdir(dir) {
var dir = pathToFile(dir); dir = pathToFile(dir);
println(dir.mkdir()? "created" : "can not create dir"); println(dir.mkdir()? "created" : "can not create dir");
} }
/** /**
* Creates the directory named by given pathname, including * Creates the directory named by given pathname, including
* any necessary but nonexistent parent directories. * any necessary but nonexistent parent directories.
* *
* @param dir input path name * @param dir input path name
*/ */
function mkdirs(dir) { function mkdirs(dir) {
var dir = pathToFile(dir); dir = pathToFile(dir);
println(dir.mkdirs()? "created" : "can not create dirs"); println(dir.mkdirs()? "created" : "can not create dirs");
} }
/** /**
* Removes a given file * Removes a given file
* *
* @param pathname name of the file * @param pathname name of the file
*/ */
function rm(pathname) { function rm(pathname) {
file = pathToFile(pathname); var file = pathToFile(pathname);
if (!file.exists()) { if (!file.exists()) {
println("file not found: " + pathname); println("file not found: " + pathname);
return false; return false;
} }
// note that delete is a keyword in JavaScript! // note that delete is a keyword in JavaScript!
println(file["delete"]()? "deleted" : "can not delete"); println(file["delete"]()? "deleted" : "can not delete");
} }
/** /**
...@@ -494,14 +525,14 @@ function rm(pathname) { ...@@ -494,14 +525,14 @@ function rm(pathname) {
* @param pathname name of the directory * @param pathname name of the directory
*/ */
function rmdir(pathname) { function rmdir(pathname) {
rm(pathname); rm(pathname);
} }
/** /**
* Synonym for 'rm' * Synonym for 'rm'
*/ */
function del(pathname) { function del(pathname) {
rm(pathname); rm(pathname);
} }
/** /**
...@@ -511,62 +542,62 @@ function del(pathname) { ...@@ -511,62 +542,62 @@ function del(pathname) {
* @param to new name for the file * @param to new name for the file
*/ */
function mv(from, to) { function mv(from, to) {
println(pathToFile(from).renameTo(pathToFile(to))? println(pathToFile(from).renameTo(pathToFile(to))?
"moved" : "can not move"); "moved" : "can not move");
} }
/** /**
* Synonym for 'mv'. * Synonym for 'mv'.
*/ */
function ren(from, to) { function ren(from, to) {
mv(from, to); mv(from, to);
} }
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
/** /**
* Helper function called by ls * Helper function called by ls
* @private * @private
*/ */
function printFile(f) { function printFile(f) {
var sb = new java.lang.StringBuffer(); var sb = new java.lang.StringBuffer();
sb.append(f.isDirectory()? "d" : "-"); sb.append(f.isDirectory()? "d" : "-");
sb.append(f.canRead() ? "r": "-" ); sb.append(f.canRead() ? "r": "-" );
sb.append(f.canWrite() ? "w": "-" ); sb.append(f.canWrite() ? "w": "-" );
sb.append(" "); sb.append(" ");
var d = new java.util.Date(f.lastModified()); var d = new java.util.Date(f.lastModified());
var c = new java.util.GregorianCalendar(); var c = new java.util.GregorianCalendar();
c.setTime(d); c.setTime(d);
var day = c.get(java.util.Calendar.DAY_OF_MONTH); var day = c.get(java.util.Calendar.DAY_OF_MONTH);
sb.append(months[c.get(java.util.Calendar.MONTH)] sb.append(months[c.get(java.util.Calendar.MONTH)]
+ " " + day ); + " " + day );
if (day < 10) { if (day < 10) {
sb.append(" "); sb.append(" ");
} }
// to get fixed length 'length' field // to get fixed length 'length' field
var fieldlen = 8; var fieldlen = 8;
var len = new java.lang.StringBuffer(); var len = new java.lang.StringBuffer();
for(var j=0; j<fieldlen; j++) for(var j=0; j<fieldlen; j++)
len.append(" "); len.append(" ");
len.insert(0, java.lang.Long.toString(f.length())); len.insert(0, java.lang.Long.toString(f.length()));
len.setLength(fieldlen); len.setLength(fieldlen);
// move the spaces to the front // move the spaces to the front
var si = len.toString().indexOf(" "); var si = len.toString().indexOf(" ");
if ( si != -1 ) { if ( si != -1 ) {
var pad = len.toString().substring(si); var pad = len.toString().substring(si);
len.setLength(si); len.setLength(si);
len.insert(0, pad); len.insert(0, pad);
} }
sb.append(len.toString()); sb.append(len.toString());
sb.append(" "); sb.append(" ");
sb.append(f.getName()); sb.append(f.getName());
if (f.isDirectory()) { if (f.isDirectory()) {
sb.append('/'); sb.append('/');
} }
println(sb.toString()); println(sb.toString());
} }
/** /**
...@@ -576,32 +607,32 @@ function printFile(f) { ...@@ -576,32 +607,32 @@ function printFile(f) {
* @param filter pattern to filter the files listed. optional, default is '.'. * @param filter pattern to filter the files listed. optional, default is '.'.
*/ */
function ls(dir, filter) { function ls(dir, filter) {
if (dir) { if (dir) {
dir = pathToFile(dir); dir = pathToFile(dir);
} else { } else {
dir = curDir; dir = curDir;
} }
if (dir.isDirectory()) { if (dir.isDirectory()) {
var files = dir.listFiles(); var files = dir.listFiles();
for (var i in files) { for (var i in files) {
var f = files[i]; var f = files[i];
if (filter) { if (filter) {
if(!f.getName().match(filter)) { if(!f.getName().match(filter)) {
continue; continue;
} }
} }
printFile(f); printFile(f);
} }
} else { } else {
printFile(dir); printFile(dir);
} }
} }
/** /**
* Synonym for 'ls'. * Synonym for 'ls'.
*/ */
function dir(d, filter) { function dir(d, filter) {
ls(d, filter); ls(d, filter);
} }
/** /**
...@@ -611,24 +642,24 @@ function dir(d, filter) { ...@@ -611,24 +642,24 @@ function dir(d, filter) {
* @param files one or more files * @param files one or more files
*/ */
function grep(pattern, files /*, one or more files */) { function grep(pattern, files /*, one or more files */) {
if (arguments.length < 2) return; if (arguments.length < 2) return;
for (var i = 1; i < arguments.length; i++) { for (var i = 1; i < arguments.length; i++) {
println(arguments[i] + ":"); println(arguments[i] + ":");
cat(arguments[i], pattern); cat(arguments[i], pattern);
} }
} }
/** /**
* Find in files. Calls arbitrary callback function * Find in files. Calls arbitrary callback function
* for each matching file.<br> * for each matching file.<br>
* *
* Examples: * Examples:
* <pre> * <pre>
* <code> * <code>
* find('.') * find('.')
* find('.', '.*\.class', rm); // remove all .class files * find('.', '.*\.class', rm); // remove all .class files
* find('.', '.*\.java'); // print fullpath of each .java file * find('.', '.*\.java'); // print fullpath of each .java file
* find('.', '.*\.java', cat); // print all .java files * find('.', '.*\.java', cat); // print all .java files
* </code> * </code>
* </pre> * </pre>
* *
...@@ -637,23 +668,23 @@ function grep(pattern, files /*, one or more files */) { ...@@ -637,23 +668,23 @@ function grep(pattern, files /*, one or more files */) {
* @param callback function to call for matching files * @param callback function to call for matching files
*/ */
function find(dir, pattern, callback) { function find(dir, pattern, callback) {
dir = pathToFile(dir); dir = pathToFile(dir);
if (!callback) callback = print; if (!callback) callback = print;
var files = dir.listFiles(); var files = dir.listFiles();
for (var f in files) { for (var f in files) {
var file = files[f]; var file = files[f];
if (file.isDirectory()) { if (file.isDirectory()) {
find(file, pattern, callback); find(file, pattern, callback);
} else { } else {
if (pattern) { if (pattern) {
if (file.getName().match(pattern)) { if (file.getName().match(pattern)) {
callback(file); callback(file);
} }
} else { } else {
callback(file); callback(file);
} }
} }
} }
} }
// process utilities // process utilities
...@@ -664,40 +695,44 @@ function find(dir, pattern, callback) { ...@@ -664,40 +695,44 @@ function find(dir, pattern, callback) {
* @param cmd command to execute in child process * @param cmd command to execute in child process
*/ */
function exec(cmd) { function exec(cmd) {
var process = java.lang.Runtime.getRuntime().exec(cmd); var process = java.lang.Runtime.getRuntime().exec(cmd);
var inp = new DataInputStream(process.getInputStream()); var inp = new DataInputStream(process.getInputStream());
var line = null; var line = null;
while ((line = inp.readLine()) != null) { while ((line = inp.readLine()) != null) {
println(line); println(line);
} }
process.waitFor(); process.waitFor();
$exit = process.exitValue(); $exit = process.exitValue();
} }
/** if (typeof(exit) == 'undefined') {
* Exit the shell program. /**
* * Exit the shell program.
* @param exitCode integer code returned to OS shell. *
* optional, defaults to 0 * @param exitCode integer code returned to OS shell.
*/ * optional, defaults to 0
function exit(code) { */
if (code) { var exit = function (code) {
java.lang.System.exit(code + 0); if (code) {
} else { java.lang.System.exit(code + 0);
java.lang.System.exit(0); } else {
} java.lang.System.exit(0);
} }
}
/** }
* synonym for exit
*/ if (typeof(quit) == 'undefined') {
function quit(code) { /**
exit(code); * synonym for exit
*/
var quit = function (code) {
exit(code);
}
} }
// XML utilities // XML utilities
/** /**
* Converts input to DOM Document object * Converts input to DOM Document object
* *
* @param inp file or reader. optional, without this param, * @param inp file or reader. optional, without this param,
...@@ -705,17 +740,17 @@ function quit(code) { ...@@ -705,17 +740,17 @@ function quit(code) {
* @return returns a DOM Document object * @return returns a DOM Document object
*/ */
function XMLDocument(inp) { function XMLDocument(inp) {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
var builder = factory.newDocumentBuilder(); var builder = factory.newDocumentBuilder();
if (inp) { if (inp) {
if (typeof(inp) == "string") { if (typeof(inp) == "string") {
return builder.parse(pathToFile(inp)); return builder.parse(pathToFile(inp));
} else { } else {
return builder.parse(inp); return builder.parse(inp);
} }
} else { } else {
return builder.newDocument(); return builder.newDocument();
} }
} }
/** /**
...@@ -725,14 +760,14 @@ function XMLDocument(inp) { ...@@ -725,14 +760,14 @@ function XMLDocument(inp) {
* @return XMLSource object * @return XMLSource object
*/ */
function XMLSource(inp) { function XMLSource(inp) {
if (inp instanceof javax.xml.transform.Source) { if (inp instanceof javax.xml.transform.Source) {
return inp; return inp;
} else if (inp instanceof Packages.org.w3c.dom.Document) { } else if (inp instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMSource(inp); return new javax.xml.transform.dom.DOMSource(inp);
} else { } else {
inp = new BufferedInputStream(inStream(inp)); inp = new BufferedInputStream(inStream(inp));
return new javax.xml.transform.stream.StreamSource(inp); return new javax.xml.transform.stream.StreamSource(inp);
} }
} }
/** /**
...@@ -742,73 +777,73 @@ function XMLSource(inp) { ...@@ -742,73 +777,73 @@ function XMLSource(inp) {
* @return XMLResult object * @return XMLResult object
*/ */
function XMLResult(out) { function XMLResult(out) {
if (out instanceof javax.xml.transform.Result) { if (out instanceof javax.xml.transform.Result) {
return out; return out;
} else if (out instanceof Packages.org.w3c.dom.Document) { } else if (out instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMResult(out); return new javax.xml.transform.dom.DOMResult(out);
} else { } else {
out = new BufferedOutputStream(outStream(out)); out = new BufferedOutputStream(outStream(out));
return new javax.xml.transform.stream.StreamResult(out); return new javax.xml.transform.stream.StreamResult(out);
} }
} }
/** /**
* Perform XSLT transform * Perform XSLT transform
* *
* @param inp Input XML to transform (URL, File or InputStream) * @param inp Input XML to transform (URL, File or InputStream)
* @param style XSL Stylesheet to be used (URL, File or InputStream). optional. * @param style XSL Stylesheet to be used (URL, File or InputStream). optional.
* @param out Output XML (File or OutputStream * @param out Output XML (File or OutputStream
*/ */
function XSLTransform(inp, style, out) { function XSLTransform(inp, style, out) {
switch (arguments.length) { switch (arguments.length) {
case 2: case 2:
inp = arguments[0]; inp = arguments[0];
out = arguments[1]; out = arguments[1];
break; break;
case 3: case 3:
inp = arguments[0]; inp = arguments[0];
style = arguments[1]; style = arguments[1];
out = arguments[2]; out = arguments[2];
break; break;
default: default:
println("XSL tranform requires 2 or 3 arguments"); println("XSL tranform requires 2 or 3 arguments");
return; return;
} }
var factory = javax.xml.transform.TransformerFactory.newInstance(); var factory = javax.xml.transform.TransformerFactory.newInstance();
var tranformer; var transformer;
if (style) { if (style) {
transformer = factory.newTransformer(XMLSource(style)); transformer = factory.newTransformer(XMLSource(style));
} else { } else {
transformer = factory.newTransformer(); transformer = factory.newTransformer();
} }
var source = XMLSource(inp); var source = XMLSource(inp);
var result = XMLResult(out); var result = XMLResult(out);
transformer.transform(source, result); transformer.transform(source, result);
if (source.getInputStream) { if (source.getInputStream) {
streamClose(source.getInputStream()); streamClose(source.getInputStream());
} }
if (result.getOutputStream) { if (result.getOutputStream) {
streamClose(result.getOutputStream()); streamClose(result.getOutputStream());
} }
} }
// miscellaneous utilities // miscellaneous utilities
/** /**
* Prints which command is selected from PATH * Prints which command is selected from PATH
* *
* @param cmd name of the command searched from PATH * @param cmd name of the command searched from PATH
*/ */
function which(cmd) { function which(cmd) {
var st = new java.util.StringTokenizer(env.PATH, File.pathSeparator); var st = new java.util.StringTokenizer(env.PATH, File.pathSeparator);
while (st.hasMoreTokens()) { while (st.hasMoreTokens()) {
var file = new File(st.nextToken(), cmd); var file = new File(st.nextToken(), cmd);
if (file.exists()) { if (file.exists()) {
println(file.getAbsolutePath()); println(file.getAbsolutePath());
return; return;
} }
} }
} }
/** /**
...@@ -817,41 +852,43 @@ function which(cmd) { ...@@ -817,41 +852,43 @@ function which(cmd) {
* @param name domain name * @param name domain name
*/ */
function ip(name) { function ip(name) {
var addrs = InetAddress.getAllByName(name); var addrs = InetAddress.getAllByName(name);
for (var i in addrs) { for (var i in addrs) {
println(addrs[i]); println(addrs[i]);
} }
} }
/** /**
* Prints current date in current locale * Prints current date in current locale
*/ */
function date() { function date() {
println(new Date().toLocaleString()); println(new Date().toLocaleString());
} }
/** /**
* Echoes the given string arguments * Echoes the given string arguments
*/ */
function echo(x) { function echo(x) {
for (var i = 0; i < arguments.length; i++) { for (var i = 0; i < arguments.length; i++) {
println(arguments[i]); println(arguments[i]);
} }
} }
/** if (typeof(printf) == 'undefined') {
* This is C-like printf /**
* * This is C-like printf
* @param format string to format the rest of the print items *
* @param args variadic argument list * @param format string to format the rest of the print items
*/ * @param args variadic argument list
function printf(format, args/*, more args*/) { */
var array = java.lang.reflect.Array.newInstance(java.lang.Object, var printf = function (format, args/*, more args*/) {
arguments.length - 1); var array = java.lang.reflect.Array.newInstance(java.lang.Object,
for (var i = 0; i < array.length; i++) { arguments.length - 1);
array[i] = arguments[i+1]; for (var i = 0; i < array.length; i++) {
} array[i] = arguments[i+1];
return java.lang.System.out.printf(format, array); }
java.lang.System.out.printf(format, array);
}
} }
/** /**
...@@ -861,24 +898,48 @@ function printf(format, args/*, more args*/) { ...@@ -861,24 +898,48 @@ function printf(format, args/*, more args*/) {
* @param multiline to tell whether to read single line or multiple lines * @param multiline to tell whether to read single line or multiple lines
*/ */
function read(prompt, multiline) { function read(prompt, multiline) {
if (!prompt) { if (!prompt) {
prompt = '>'; prompt = '>';
} }
var inp = java.lang.System["in"]; var inp = java.lang.System["in"];
var reader = new BufferedReader(new InputStreamReader(inp)); var reader = new BufferedReader(new InputStreamReader(inp));
if (multiline) { if (multiline) {
var line = ''; var line = '';
while (true) { while (true) {
java.lang.System.err.print(prompt); java.lang.System.err.print(prompt);
java.lang.System.err.flush(); java.lang.System.err.flush();
var tmp = reader.readLine(); var tmp = reader.readLine();
if (tmp == '' || tmp == null) break; if (tmp == '' || tmp == null) break;
line += tmp + '\n'; line += tmp + '\n';
} }
return line; return line;
} else { } else {
java.lang.System.err.print(prompt); java.lang.System.err.print(prompt);
java.lang.System.err.flush(); java.lang.System.err.flush();
return reader.readLine(); return reader.readLine();
} }
}
if (typeof(println) == 'undefined') {
var print = function(str, newline) {
if (typeof(str) == 'undefined') {
str = 'undefined';
} else if (str == null) {
str = 'null';
}
if (!(out instanceof java.io.PrintWriter)) {
out = new java.io.PrintWriter(out);
}
out.print(String(str));
if (newline) {
out.print('\n');
}
out.flush();
}
var println = function(str) {
print(str, true);
};
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册