8367157: Remove jrunscript tool

Reviewed-by: erikj, ayang, ihse, alanb
This commit is contained in:
Jaikiran Pai 2025-10-14 06:10:09 +00:00
parent 5bf1bab5b3
commit 2eb0898fef
24 changed files with 4 additions and 2364 deletions

View File

@ -27,7 +27,5 @@
DOCLINT += -Xdoclint:all/protected \
'-Xdoclint/package:java.*,javax.*'
COPY += .js
CLEAN += .properties
################################################################################

View File

@ -1,39 +0,0 @@
#
# Copyright (c) 2011, 2025, 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.
#
################################################################################
include LauncherCommon.gmk
################################################################################
## Build jrunscript
################################################################################
$(eval $(call SetupBuildLauncher, jrunscript, \
MAIN_CLASS := com.sun.tools.script.shell.Main, \
JAVA_ARGS := --add-modules ALL-DEFAULT, \
))
################################################################################

View File

@ -1,595 +0,0 @@
/*
* Copyright (c) 2005, 2025, 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.
*/
package com.sun.tools.script.shell;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.text.*;
import java.util.*;
import javax.script.*;
/**
* This is the main class for Java script shell.
*/
public class Main {
/**
* main entry point to the command line tool
* @param args command line argument array
*/
public static void main(String[] args) {
// print deprecation warning
getError().println(getMessage("deprecated.warning",
new Object[] { PROGRAM_NAME }));
// parse command line options
String[] scriptArgs = processOptions(args);
// process each script command
for (Command cmd : scripts) {
cmd.run(scriptArgs);
}
System.exit(EXIT_SUCCESS);
}
// Each -e or -f or interactive mode is represented
// by an instance of Command.
private static interface Command {
public void run(String[] arguments);
}
/**
* Parses and processes command line options.
* @param args command line argument array
*/
private static String[] processOptions(String[] args) {
// current scripting language selected
String currentLanguage = DEFAULT_LANGUAGE;
// current script file encoding selected
String currentEncoding = null;
// check for -classpath or -cp first
checkClassPath(args);
// have we seen -e or -f ?
boolean seenScript = false;
// have we seen -f - already?
boolean seenStdin = false;
for (int i=0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("-classpath") ||
arg.equals("-cp")) {
// handled already, just continue
i++;
continue;
}
// collect non-option arguments and pass these as script arguments
if (!arg.startsWith("-")) {
int numScriptArgs;
int startScriptArg;
if (seenScript) {
// if we have seen -e or -f already all non-option arguments
// are passed as script arguments
numScriptArgs = args.length - i;
startScriptArg = i;
} else {
// if we have not seen -e or -f, first non-option argument
// is treated as script file name and rest of the non-option
// arguments are passed to script as script arguments
numScriptArgs = args.length - i - 1;
startScriptArg = i + 1;
ScriptEngine se = getScriptEngine(currentLanguage);
addFileSource(se, args[i], currentEncoding);
}
// collect script arguments and return to main
String[] result = new String[numScriptArgs];
System.arraycopy(args, startScriptArg, result, 0, numScriptArgs);
return result;
}
if (arg.startsWith("-D")) {
String value = arg.substring(2);
int eq = value.indexOf('=');
if (eq != -1) {
System.setProperty(value.substring(0, eq),
value.substring(eq + 1));
} else {
if (!value.isEmpty()) {
System.setProperty(value, "");
} else {
// do not allow empty property name
usage(EXIT_CMD_NO_PROPNAME);
}
}
continue;
} else if (arg.equals("-?") ||
arg.equals("-h") ||
arg.equals("--help") ||
// -help: legacy.
arg.equals("-help")) {
usage(EXIT_SUCCESS);
} else if (arg.equals("-e")) {
seenScript = true;
if (++i == args.length)
usage(EXIT_CMD_NO_SCRIPT);
ScriptEngine se = getScriptEngine(currentLanguage);
addStringSource(se, args[i]);
continue;
} else if (arg.equals("-encoding")) {
if (++i == args.length)
usage(EXIT_CMD_NO_ENCODING);
currentEncoding = args[i];
continue;
} else if (arg.equals("-f")) {
seenScript = true;
if (++i == args.length)
usage(EXIT_CMD_NO_FILE);
ScriptEngine se = getScriptEngine(currentLanguage);
if (args[i].equals("-")) {
if (seenStdin) {
usage(EXIT_MULTIPLE_STDIN);
} else {
seenStdin = true;
}
addInteractiveMode(se);
} else {
addFileSource(se, args[i], currentEncoding);
}
continue;
} else if (arg.equals("-l")) {
if (++i == args.length)
usage(EXIT_CMD_NO_LANG);
currentLanguage = args[i];
continue;
} else if (arg.equals("-q")) {
listScriptEngines();
}
// some unknown option...
usage(EXIT_UNKNOWN_OPTION);
}
if (! seenScript) {
ScriptEngine se = getScriptEngine(currentLanguage);
addInteractiveMode(se);
}
return new String[0];
}
/**
* Adds interactive mode Command
* @param se ScriptEngine to use in interactive mode.
*/
private static void addInteractiveMode(final ScriptEngine se) {
scripts.add(new Command() {
public void run(String[] args) {
setScriptArguments(se, args);
processSource(se, "-", null);
}
});
}
/**
* Adds script source file Command
* @param se ScriptEngine used to evaluate the script file
* @param fileName script file name
* @param encoding script file encoding
*/
private static void addFileSource(final ScriptEngine se,
final String fileName,
final String encoding) {
scripts.add(new Command() {
public void run(String[] args) {
setScriptArguments(se, args);
processSource(se, fileName, encoding);
}
});
}
/**
* Adds script string source Command
* @param se ScriptEngine to be used to evaluate the script string
* @param source Script source string
*/
private static void addStringSource(final ScriptEngine se,
final String source) {
scripts.add(new Command() {
public void run(String[] args) {
setScriptArguments(se, args);
String oldFile = setScriptFilename(se, "<string>");
try {
evaluateString(se, source);
} finally {
setScriptFilename(se, oldFile);
}
}
});
}
/**
* Prints list of script engines available and exits.
*/
private static void listScriptEngines() {
List<ScriptEngineFactory> factories = engineManager.getEngineFactories();
for (ScriptEngineFactory factory: factories) {
getError().println(getMessage("engine.info",
new Object[] { factory.getLanguageName(),
factory.getLanguageVersion(),
factory.getEngineName(),
factory.getEngineVersion()
}));
}
System.exit(EXIT_SUCCESS);
}
/**
* Processes a given source file or standard input.
* @param se ScriptEngine to be used to evaluate
* @param filename file name, can be null
* @param encoding script file encoding, can be null
*/
private static void processSource(ScriptEngine se, String filename,
String encoding) {
if (filename.equals("-")) {
Charset charset = Charset.forName(System.getProperty("stdin.encoding"), Charset.defaultCharset());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, charset));
boolean hitEOF = false;
String prompt = getPrompt(se);
se.put(ScriptEngine.FILENAME, "<STDIN>");
while (!hitEOF) {
getError().print(prompt);
String source = "";
try {
source = in.readLine();
} catch (IOException ioe) {
getError().println(ioe.toString());
}
if (source == null) {
hitEOF = true;
break;
}
Object res = evaluateString(se, source, false);
if (res != null) {
res = res.toString();
if (res == null) {
res = "null";
}
getError().println(res);
}
}
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
} catch (FileNotFoundException fnfe) {
getError().println(getMessage("file.not.found",
new Object[] { filename }));
System.exit(EXIT_FILE_NOT_FOUND);
}
evaluateStream(se, fis, filename, encoding);
}
}
/**
* Evaluates given script source
* @param se ScriptEngine to evaluate the string
* @param script Script source string
* @param exitOnError whether to exit the process on script error
*/
private static Object evaluateString(ScriptEngine se,
String script, boolean exitOnError) {
try {
return se.eval(script);
} catch (ScriptException sexp) {
getError().println(getMessage("string.script.error",
new Object[] { sexp.getMessage() }));
if (exitOnError)
System.exit(EXIT_SCRIPT_ERROR);
} catch (Exception exp) {
exp.printStackTrace(getError());
if (exitOnError)
System.exit(EXIT_SCRIPT_ERROR);
}
return null;
}
/**
* Evaluate script string source and exit on script error
* @param se ScriptEngine to evaluate the string
* @param script Script source string
*/
private static void evaluateString(ScriptEngine se, String script) {
evaluateString(se, script, true);
}
/**
* Evaluates script from given reader
* @param se ScriptEngine to evaluate the string
* @param reader Reader from which is script is read
* @param name file name to report in error.
*/
private static Object evaluateReader(ScriptEngine se,
Reader reader, String name) {
String oldFilename = setScriptFilename(se, name);
try {
return se.eval(reader);
} catch (ScriptException sexp) {
getError().println(getMessage("file.script.error",
new Object[] { name, sexp.getMessage() }));
System.exit(EXIT_SCRIPT_ERROR);
} catch (Exception exp) {
exp.printStackTrace(getError());
System.exit(EXIT_SCRIPT_ERROR);
} finally {
setScriptFilename(se, oldFilename);
}
return null;
}
/**
* Evaluates given input stream
* @param se ScriptEngine to evaluate the string
* @param is InputStream from which script is read
* @param name file name to report in error
*/
private static Object evaluateStream(ScriptEngine se,
InputStream is, String name,
String encoding) {
BufferedReader reader = null;
if (encoding != null) {
try {
reader = new BufferedReader(new InputStreamReader(is,
encoding));
} catch (UnsupportedEncodingException uee) {
getError().println(getMessage("encoding.unsupported",
new Object[] { encoding }));
System.exit(EXIT_NO_ENCODING_FOUND);
}
} else {
reader = new BufferedReader(new InputStreamReader(is));
}
return evaluateReader(se, reader, name);
}
/**
* Prints usage message and exits
* @param exitCode process exit code
*/
private static void usage(int exitCode) {
getError().println(getMessage("main.usage",
new Object[] { PROGRAM_NAME }));
System.exit(exitCode);
}
/**
* Gets prompt for interactive mode
* @return prompt string to use
*/
private static String getPrompt(ScriptEngine se) {
List<String> names = se.getFactory().getNames();
return names.get(0) + "> ";
}
/**
* Get formatted, localized error message
*/
private static String getMessage(String key, Object[] params) {
return MessageFormat.format(msgRes.getString(key), params);
}
// stream to print error messages
private static PrintStream getError() {
return System.err;
}
// get current script engine
private static ScriptEngine getScriptEngine(String lang) {
ScriptEngine se = engines.get(lang);
if (se == null) {
se = engineManager.getEngineByName(lang);
if (se == null) {
getError().println(getMessage("engine.not.found",
new Object[] { lang }));
System.exit(EXIT_ENGINE_NOT_FOUND);
}
// initialize the engine
initScriptEngine(se);
// to avoid re-initialization of engine, store it in a map
engines.put(lang, se);
}
return se;
}
// initialize a given script engine
private static void initScriptEngine(ScriptEngine se) {
// put engine global variable
se.put("engine", se);
// load init.<ext> file from resource
List<String> exts = se.getFactory().getExtensions();
InputStream sysIn = null;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
for (String ext : exts) {
try {
sysIn = Main.class.getModule().getResourceAsStream("com/sun/tools/script/shell/init." + ext);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
if (sysIn != null) break;
}
if (sysIn != null) {
evaluateStream(se, sysIn, "<system-init>", null);
}
}
/**
* Checks for -classpath, -cp in command line args. Creates a ClassLoader
* and sets it as Thread context loader for current thread.
*
* @param args command line argument array
*/
private static void checkClassPath(String[] args) {
String classPath = null;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-classpath") ||
args[i].equals("-cp")) {
if (++i == args.length) {
// just -classpath or -cp with no value
usage(EXIT_CMD_NO_CLASSPATH);
} else {
classPath = args[i];
}
}
}
if (classPath != null) {
/* We create a class loader, configure it with specified
* classpath values and set the same as context loader.
* Note that ScriptEngineManager uses context loader to
* load script engines. So, this ensures that user defined
* script engines will be loaded. For classes referred
* from scripts, Rhino engine uses thread context loader
* but this is script engine dependent. We don't have
* script engine independent solution anyway. Unless we
* know the class loader used by a specific engine, we
* can't configure correct loader.
*/
URL[] urls = pathToURLs(classPath);
URLClassLoader loader = new URLClassLoader(urls);
Thread.currentThread().setContextClassLoader(loader);
}
// now initialize script engine manager. Note that this has to
// be done after setting the context loader so that manager
// will see script engines from user specified classpath
engineManager = new ScriptEngineManager();
}
/**
* Utility method for converting a search path string to an array
* of directory and JAR file URLs.
*
* @param path the search path string
* @return the resulting array of directory and JAR file URLs
*/
private static URL[] pathToURLs(String path) {
String[] components = path.split(File.pathSeparator);
URL[] urls = new URL[components.length];
int count = 0;
while(count < components.length) {
URL url = fileToURL(new File(components[count]));
if (url != null) {
urls[count++] = url;
}
}
if (urls.length != count) {
URL[] tmp = new URL[count];
System.arraycopy(urls, 0, tmp, 0, count);
urls = tmp;
}
return urls;
}
/**
* Returns the directory or JAR file URL corresponding to the specified
* local file name.
*
* @param file the File object
* @return the resulting directory or JAR file URL, or null if unknown
*/
private static URL fileToURL(File file) {
String name;
try {
name = file.getCanonicalPath();
} catch (IOException e) {
name = file.getAbsolutePath();
}
name = name.replace(File.separatorChar, '/');
if (!name.startsWith("/")) {
name = "/" + name;
}
// If the file does not exist, then assume that it's a directory
if (!file.isFile()) {
name = name + "/";
}
try {
@SuppressWarnings("deprecation")
var result = new URL("file", "", name);
return result;
} catch (MalformedURLException e) {
throw new IllegalArgumentException("file");
}
}
private static void setScriptArguments(ScriptEngine se, String[] args) {
se.put("arguments", args);
se.put(ScriptEngine.ARGV, args);
}
private static String setScriptFilename(ScriptEngine se, String name) {
String oldName = (String) se.get(ScriptEngine.FILENAME);
se.put(ScriptEngine.FILENAME, name);
return oldName;
}
// exit codes
private static final int EXIT_SUCCESS = 0;
private static final int EXIT_CMD_NO_CLASSPATH = 1;
private static final int EXIT_CMD_NO_FILE = 2;
private static final int EXIT_CMD_NO_SCRIPT = 3;
private static final int EXIT_CMD_NO_LANG = 4;
private static final int EXIT_CMD_NO_ENCODING = 5;
private static final int EXIT_CMD_NO_PROPNAME = 6;
private static final int EXIT_UNKNOWN_OPTION = 7;
private static final int EXIT_ENGINE_NOT_FOUND = 8;
private static final int EXIT_NO_ENCODING_FOUND = 9;
private static final int EXIT_SCRIPT_ERROR = 10;
private static final int EXIT_FILE_NOT_FOUND = 11;
private static final int EXIT_MULTIPLE_STDIN = 12;
// default scripting language
private static final String DEFAULT_LANGUAGE = "js";
// list of scripts to process
private static List<Command> scripts;
// the script engine manager
private static ScriptEngineManager engineManager;
// map of engines we loaded
private static Map<String, ScriptEngine> engines;
// error messages resource
private static ResourceBundle msgRes;
private static String BUNDLE_NAME = "com.sun.tools.script.shell.messages";
private static String PROGRAM_NAME = "jrunscript";
static {
scripts = new ArrayList<Command>();
engines = new HashMap<String, ScriptEngine>();
msgRes = ResourceBundle.getBundle(BUNDLE_NAME, Locale.getDefault());
}
}

View File

@ -1,927 +0,0 @@
/*
* Copyright (c) 2005, 2013, 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 JSAdapter.
* For eg. to access java.class.path property, you can use
* the syntax sysProps["java.class.path"]
*/
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
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"];
var BufferedInputStream = java.io.BufferedInputStream;
var BufferedOutputStream = java.io.BufferedOutputStream;
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
* @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
*/
if (typeof(load) == 'undefined') {
this.load = function(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) {
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) {
dir = pathToFile(dir);
println(dir.mkdirs()? "created" : "can not create dirs");
}
/**
* Removes a given file
*
* @param pathname name of the file
*/
function rm(pathname) {
var 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);
}
/**
* Synonym for 'rm'
*/
function del(pathname) {
rm(pathname);
}
/**
* Moves a file to another
*
* @param from original name of the file
* @param to new name for the file
*/
function mv(from, to) {
println(pathToFile(from).renameTo(pathToFile(to))?
"moved" : "can not move");
}
/**
* Synonym for 'mv'.
*/
function ren(from, to) {
mv(from, to);
}
var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
/**
* Helper function called by ls
* @private
*/
function printFile(f) {
var sb = new java.lang.StringBuffer();
sb.append(f.isDirectory()? "d" : "-");
sb.append(f.canRead() ? "r": "-" );
sb.append(f.canWrite() ? "w": "-" );
sb.append(" ");
var d = new java.util.Date(f.lastModified());
var c = new java.util.GregorianCalendar();
c.setTime(d);
var day = c.get(java.util.Calendar.DAY_OF_MONTH);
sb.append(months[c.get(java.util.Calendar.MONTH)]
+ " " + day );
if (day < 10) {
sb.append(" ");
}
// to get fixed length 'length' field
var fieldlen = 8;
var len = new java.lang.StringBuffer();
for(var j=0; j<fieldlen; j++)
len.append(" ");
len.insert(0, java.lang.Long.toString(f.length()));
len.setLength(fieldlen);
// move the spaces to the front
var si = len.toString().indexOf(" ");
if ( si != -1 ) {
var pad = len.toString().substring(si);
len.setLength(si);
len.insert(0, pad);
}
sb.append(len.toString());
sb.append(" ");
sb.append(f.getName());
if (f.isDirectory()) {
sb.append('/');
}
println(sb.toString());
}
/**
* Lists the files in a directory
*
* @param dir directory from which to list the files. optional, default to pwd
* @param filter pattern to filter the files listed. optional, default is '.'.
*/
function ls(dir, filter) {
if (dir) {
dir = pathToFile(dir);
} else {
dir = curDir;
}
if (dir.isDirectory()) {
var files = dir.listFiles();
for (var i in files) {
var f = files[i];
if (filter) {
if(!f.getName().match(filter)) {
continue;
}
}
printFile(f);
}
} else {
printFile(dir);
}
}
/**
* Synonym for 'ls'.
*/
function dir(d, filter) {
ls(d, filter);
}
/**
* Unix-like grep, but accepts JavaScript regex patterns
*
* @param pattern to search in files
* @param files one or more files
*/
function grep(pattern, files /*, one or more files */) {
if (arguments.length < 2) return;
for (var i = 1; i < arguments.length; i++) {
println(arguments[i] + ":");
cat(arguments[i], pattern);
}
}
/**
* Find in files. Calls arbitrary callback function
* for each matching file.<br>
*
* Examples:
* <pre>
* <code>
* find('.')
* find('.', '.*\.class', rm); // remove all .class files
* find('.', '.*\.java'); // print fullpath of each .java file
* find('.', '.*\.java', cat); // print all .java files
* </code>
* </pre>
*
* @param dir directory to search files
* @param pattern to search in the files
* @param callback function to call for matching files
*/
function find(dir, pattern, callback) {
dir = pathToFile(dir);
if (!callback) callback = print;
var files = dir.listFiles();
for (var f in files) {
var file = files[f];
if (file.isDirectory()) {
find(file, pattern, callback);
} else {
if (pattern) {
if (file.getName().match(pattern)) {
callback(file);
}
} else {
callback(file);
}
}
}
}
// process utilities
/**
* Exec's a child process, waits for completion &amp; returns exit code
*
* @param cmd command to execute in child process
*/
function exec(cmd) {
var process = java.lang.Runtime.getRuntime().exec(cmd);
var inp = new DataInputStream(process.getInputStream());
var line = null;
while ((line = inp.readLine()) != null) {
println(line);
}
process.waitFor();
$exit = process.exitValue();
}
if (typeof(exit) == 'undefined') {
/**
* Exit the shell program.
*
* @param exitCode integer code returned to OS shell.
* optional, defaults to 0
*/
this.exit = function (code) {
if (code) {
java.lang.System.exit(code + 0);
} else {
java.lang.System.exit(0);
}
}
}
if (typeof(quit) == 'undefined') {
/**
* synonym for exit
*/
this.quit = function (code) {
exit(code);
}
}
// XML utilities
/**
* Converts input to DOM Document object
*
* @param inp file or reader. optional, without this param,
* this function returns a new DOM Document.
* @return returns a DOM Document object
*/
function XMLDocument(inp) {
var factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
var builder = factory.newDocumentBuilder();
if (inp) {
if (typeof(inp) == "string") {
return builder.parse(pathToFile(inp));
} else {
return builder.parse(inp);
}
} else {
return builder.newDocument();
}
}
/**
* Converts arbitrary stream, file, URL to XMLSource
*
* @param inp input stream or file or URL
* @return XMLSource object
*/
function XMLSource(inp) {
if (inp instanceof javax.xml.transform.Source) {
return inp;
} else if (inp instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMSource(inp);
} else {
inp = new BufferedInputStream(inStream(inp));
return new javax.xml.transform.stream.StreamSource(inp);
}
}
/**
* Converts arbitrary stream, file to XMLResult
*
* @param inp output stream or file
* @return XMLResult object
*/
function XMLResult(out) {
if (out instanceof javax.xml.transform.Result) {
return out;
} else if (out instanceof Packages.org.w3c.dom.Document) {
return new javax.xml.transform.dom.DOMResult(out);
} else {
out = new BufferedOutputStream(outStream(out));
return new javax.xml.transform.stream.StreamResult(out);
}
}
/**
* Perform XSLT transform
*
* @param inp Input XML to transform (URL, File or InputStream)
* @param style XSL Stylesheet to be used (URL, File or InputStream). optional.
* @param out Output XML (File or OutputStream
*/
function XSLTransform(inp, style, out) {
switch (arguments.length) {
case 2:
inp = arguments[0];
out = arguments[1];
break;
case 3:
inp = arguments[0];
style = arguments[1];
out = arguments[2];
break;
default:
println("XSL transform requires 2 or 3 arguments");
return;
}
var factory = javax.xml.transform.TransformerFactory.newInstance();
var transformer;
if (style) {
transformer = factory.newTransformer(XMLSource(style));
} else {
transformer = factory.newTransformer();
}
var source = XMLSource(inp);
var result = XMLResult(out);
transformer.transform(source, result);
if (source.getInputStream) {
streamClose(source.getInputStream());
}
if (result.getOutputStream) {
streamClose(result.getOutputStream());
}
}
// miscellaneous utilities
/**
* Prints which command is selected from PATH
*
* @param cmd name of the command searched from PATH
*/
function which(cmd) {
var st = new java.util.StringTokenizer(env.PATH, File.pathSeparator);
while (st.hasMoreTokens()) {
var file = new File(st.nextToken(), cmd);
if (file.exists()) {
println(file.getAbsolutePath());
return;
}
}
}
/**
* Prints IP addresses of given domain name
*
* @param name domain name
*/
function ip(name) {
var addrs = InetAddress.getAllByName(name);
for (var i in addrs) {
println(addrs[i]);
}
}
/**
* Prints current date in current locale
*/
function date() {
println(new Date().toLocaleString());
}
/**
* Echoes the given string arguments
*/
function echo(x) {
for (var i = 0; i < arguments.length; i++) {
println(arguments[i]);
}
}
if (typeof(printf) == 'undefined') {
/**
* This is C-like printf
*
* @param format string to format the rest of the print items
* @param args variadic argument list
*/
this.printf = function (format, args/*, more args*/) {
var array = java.lang.reflect.Array.newInstance(java.lang.Object,
arguments.length - 1);
for (var i = 0; i < array.length; i++) {
array[i] = arguments[i+1];
}
java.lang.System.out.printf(format, array);
}
}
/**
* Reads one or more lines from stdin after printing prompt
*
* @param prompt optional, default is '>'
* @param multiline to tell whether to read single line or multiple lines
*/
function read(prompt, multiline) {
if (!prompt) {
prompt = '>';
}
var inp = java.lang.System["in"];
var reader = new BufferedReader(new InputStreamReader(inp));
if (multiline) {
var line = '';
while (true) {
java.lang.System.err.print(prompt);
java.lang.System.err.flush();
var tmp = reader.readLine();
if (tmp == '' || tmp == null) break;
line += tmp + '\n';
}
return line;
} else {
java.lang.System.err.print(prompt);
java.lang.System.err.flush();
return reader.readLine();
}
}
if (typeof(println) == 'undefined') {
// just synonym to print
this.println = print;
}

View File

@ -1,68 +0,0 @@
#
# Copyright (c) 2005, 2024, 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.
#
string.script.error=\
script error: {0}
file.script.error=\
script error in file {0} : {1}
file.not.found=\
script file {0} is not found
engine.not.found=\
script engine for language {0} can not be found
engine.info=\
Language {0} {1} implementation "{2}" {3}
encoding.unsupported=\
encoding {0} is not supported
main.usage=\
Usage: {0} [options] [arguments...]\n\
\n\
where [options] include:\n\
\ \-classpath <path> Specify where to find user class files \n\
\ \-cp <path> Specify where to find user class files \n\
\ \-D<name>=<value> Set a system property \n\
\ \-J<flag> Pass <flag> directly to the runtime system \n\
\ \-l <language> Use specified scripting language \n\
\ \-e <script> Evaluate given script \n\
\ \-encoding <encoding> Specify character encoding used by script files \n\
\ \-f <script file> Evaluate given script file \n\
\ \-f - Interactive mode, read script from standard input \n\
\ \ If this is used, this should be the last -f option \n\
\ \-? -h --help -help Print this help message and exit \n\
\ \-q List all scripting engines available and exit \n\
\ \n\
If [arguments..] are present and if no -e or -f option is used, then first\n\
argument is script file and the rest of the arguments, if any, are passed\n\
as script arguments. If [arguments..] and -e or -f option is used, then all\n\
[arguments..] are passed as script arguments. If [arguments..], -e, -f are\n\
missing, then interactive mode is used.
deprecated.warning=\
Warning: {0} is deprecated and will be removed in a future release.

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2025, 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
@ -26,15 +26,6 @@
/**
* Defines the Scripting API.
*
* <p> The JDK implementation of this module includes a language-independent
* command-line script shell, <em>{@index jrunscript jrunscript tool}</em>,
* that supports executing JavaScript and other languages if its corresponding
* script engine is installed.
* <p> The {@code jrunscript} tool is deprecated and will be removed
* in a future release.
*
* @toolGuide jrunscript
*
* @uses javax.script.ScriptEngineFactory
*
* @moduleGraph

View File

@ -1,141 +0,0 @@
---
# Copyright (c) 2006, 2024, 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.
#
# 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.
#
title: 'JRUNSCRIPT(1) JDK @@VERSION_SHORT@@ | JDK Commands'
date: @@COPYRIGHT_YEAR@@
lang: en
---
## Name
jrunscript - run a command-line script shell that supports interactive and
batch modes
## Synopsis
**Note:**
This tool is **experimental** and unsupported. It is deprecated and will be
removed in a future release.
`jrunscript` \[*options*\] \[*arguments*\]
*options*
: This represents the `jrunscript` command-line options that can be used. See
[Options for the jrunscript Command].
*arguments*
: Arguments, when used, follow immediately after options or the command name.
See [Arguments].
## Description
The `jrunscript` command is a language-independent command-line script shell.
The `jrunscript` command supports both an interactive (read-eval-print) mode
and a batch (`-f` option) mode of script execution. By default, JavaScript is
the language used, but the `-l` option can be used to specify a different
language. By using Java to scripting language communication, the `jrunscript`
command supports an exploratory programming style.
If JavaScript is used, then before it evaluates a user defined script, the
`jrunscript` command initializes certain built-in functions and objects, which
are documented in the API Specification for `jrunscript` JavaScript built-in
functions.
## Options for the jrunscript Command
`-cp` *path* or `-classpath` *path*
: Indicates where any class files are that the script needs to access.
`-D`*name*`=`*value*
: Sets a Java system property.
`-J`*flag*
: Passes *flag* directly to the Java Virtual Machine where the `jrunscript`
command is running.
`-l` *language*
: Uses the specified scripting language. By default, JavaScript is used. To
use other scripting languages, you must specify the corresponding script
engine's JAR file with the `-cp` or `-classpath` option.
`-e` *script*
: Evaluates the specified script. This option can be used to run one-line
scripts that are specified completely on the command line.
`-encoding` *encoding*
: Specifies the character encoding used to read script files.
`-f` *script-file*
: Evaluates the specified script file (batch mode).
`-f -`
: Enters interactive mode to read and evaluate a script from standard input.
`-help` or `-?`
: Displays a help message and exits.
`-q`
: Lists all script engines available and exits.
## Arguments
If arguments are present and if no `-e` or `-f` option is used, then the first
argument is the script file and the rest of the arguments, if any, are passed
as script arguments. If arguments and the `-e` or the `-f` option are used,
then all arguments are passed as script arguments. If arguments `-e` and `-f`
are missing, then the interactive mode is used.
## Example of Executing Inline Scripts
> `jrunscript -e "print('hello world')"`
> `jrunscript -e "cat('http://www.example.com')"`
## Example of Using Specified Language and Evaluate the Script File
> `jrunscript -l js -f test.js`
## Example of Interactive Mode
```
jrunscript
js> print('Hello World\n');
Hello World
js> 34 + 55
89.0
js> t = new java.lang.Thread(function() { print('Hello World\n'); })
Thread[Thread-0,5,main]
js> t.start()
js> Hello World
js>
```
## Run Script File with Script Arguments
In this example, the `test.js` file is the script file. The `arg1`, `arg2`, and
`arg3` arguments are passed to the script. The script can access these
arguments with an arguments array.
> `jrunscript test.js arg1 arg2 arg3`

View File

@ -317,13 +317,11 @@ jdk_loom = \
core_tools = \
tools \
-tools/jpackage \
jdk/internal/jrtfs \
sun/tools/jrunscript
jdk/internal/jrtfs
svc_tools = \
com/sun/tools/attach \
sun/tools \
-sun/tools/jrunscript \
sun/jvmstat
jdk_tools = \

View File

@ -1,36 +0,0 @@
/*
* Copyright (c) 2008, 2013, 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.
*
* 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.
*/
import javax.script.*;
/*
* If the JDK being tested is <b>not</b> a Sun product JDK and a js
* engine is not present, return an exit code of 2 to indicate that
* the jrunscript tests which assume a js engine can be vacuously
* passed.
*/
public class CheckEngine {
public static void main(String... args) {
System.exit(2);
}
}

View File

@ -1,34 +0,0 @@
/*
* Copyright (c) 2005, 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.
*
* 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.
*/
/**
* This is a test program used in the test jrunscript-cp.sh
*
*
*/
public class Hello {
public Hello() {}
public String getString() {
return "hello";
}
}

View File

@ -1,66 +0,0 @@
#
# Copyright (c) 2005, 2012, 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.
#
# 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.
#
#
setup() {
# Verify directory context variables are set
if [ "${TESTJAVA}" = "" ] ; then
echo "TESTJAVA not set. Test cannot execute. Failed."
exit 1
fi
if [ "${TESTCLASSES}" = "" ] ; then
TESTCLASSES="."
fi
if [ "${TESTSRC}" = "" ] ; then
TESTSRC="."
fi
OS=`uname -s`
case ${OS} in
Windows_*)
PS=";"
FS="\\"
# MKS diff deals with trailing CRs automatically
golden_diff="diff"
;;
CYGWIN*)
PS=":"
FS="/"
# Cygwin diff needs to be told to ignore trailing CRs
golden_diff="diff --strip-trailing-cr"
;;
*)
PS=":"
FS="/"
# Assume any other platform doesn't have the trailing CR stuff
golden_diff="diff"
;;
esac
JRUNSCRIPT="${TESTJAVA}/bin/jrunscript"
JAVAC="${TESTJAVA}/bin/javac"
JAVA="${TESTJAVA}/bin/java"
}

View File

@ -1 +0,0 @@
hello

View File

@ -1 +0,0 @@
hello

View File

@ -1,7 +0,0 @@
/*
*
*
* This is the test JavaScript program used in jrunscript-f.sh
*/
println('hello');

View File

@ -1,55 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2008, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscript-DTest.sh
# @summary Test that output of 'jrunscript -D'
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
# test whether value specifieD by -D option is passed
# to script as java.lang.System property. sysProps is
# jrunscript shell built-in variable for System properties.
${JRUNSCRIPT} -l nashorn -Djrunscript.foo=bar <<EOF
if (sysProps["jrunscript.foo"] == "bar") { println("Passed"); exit(0); }
// unexpected value
println("Unexpected System property value");
exit(1);
EOF
if [ $? -ne 0 ]; then
exit 1
fi

View File

@ -1,60 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2012, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscript-argsTest.sh
# @summary Test passing of script arguments from command line
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
# we check whether "excess" args are passed as script arguments
${JRUNSCRIPT} -l nashorn -J-Djava.awt.headless=true -f - hello world <<EOF
if (typeof(arguments) == 'undefined') { println("arguments expected"); exit(1); }
if (arguments.length != 2) { println("2 arguments are expected here"); exit(1); }
if (arguments[0] != 'hello') { println("First arg should be 'hello'"); exit(1); }
if (arguments[1] != 'world') { println("Second arg should be 'world'"); exit(1); }
println("Passed");
exit(0);
EOF
if [ $? -ne 0 ]; then
exit 1
fi

View File

@ -1,73 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2008, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscript-cpTest.sh
# @summary Test -cp option to set classpath
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
rm -f Hello.class
${JAVAC} ${TESTTOOLVMOPTS} ${TESTJAVACOPTS} ${TESTSRC}/Hello.java -d .
# we check whether classpath setting for app classes
# work with jrunscript. Script should be able to
# access Java class "Hello".
${JRUNSCRIPT} -l nashorn -cp . <<EOF
var v;
try { v = new Packages.Hello(); } catch (e) { println(e); exit(1) }
if (v.string != 'hello') { println("Unexpected property value"); exit(1); }
EOF
if [ $? -ne 0 ]; then
exit 1
fi
# -classpath and -cp are synonyms
${JRUNSCRIPT} -l nashorn -classpath . <<EOF
var v;
try { v = new Packages.Hello(); } catch (e) { println(e); exit(1) }
if (v.string != 'hello') { println("unexpected property value"); exit(1); }
EOF
if [ $? -ne 0 ]; then
exit 1
fi
rm -f Hello.class
echo "Passed"
exit 0

View File

@ -1,57 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2021, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscript-eTest.sh
# @summary Test that output of 'jrunscript -e' matches the dash-e.out file
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
# -e option with JavaScript explicitly chosen as language
rm -f jrunscript-eTest.out 2>/dev/null
${JRUNSCRIPT} -J-Dnashorn.args.prepend=--no-deprecation-warning -J-Djava.awt.headless=true -l nashorn -e "println('hello')" > jrunscript-eTest.out 2>&1
$golden_diff jrunscript-eTest.out ${TESTSRC}/dash-e.out
if [ $? != 0 ]
then
echo "Output of jrunscript -e differ from expected output. Failed."
rm -f jrunscript-eTest.out 2>/dev/null
exit 1
fi
rm -f jrunscript-eTest.out
echo "Passed"
exit 0

View File

@ -1,58 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2012, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscript-fTest.sh
# @summary Test that output of 'jrunscript -f' matches the dash-f.out file
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
# -f option used with JavaScript as language chosen explicitly
# with -l option
rm -f jrunscript-fTest.out 2>/dev/null
${JRUNSCRIPT} -J-Dnashorn.args.prepend=--no-deprecation-warning -J-Djava.awt.headless=true -l nashorn -f ${TESTSRC}/hello.js > jrunscript-fTest.out 2>&1
$golden_diff jrunscript-fTest.out ${TESTSRC}/dash-f.out
if [ $? != 0 ]
then
echo "Output of jrunscript -f differ from expected output. Failed."
rm -f jrunscript-fTest.out 2>/dev/null
exit 1
fi
rm -f jrunscript-fTest.out
echo "Passed"
exit 0

View File

@ -1,58 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 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.
#
# 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.
#
# @test
# @bug 6265810
# @run shell jrunscript-helpTest.sh
# @summary Test that output of 'jrunscript -?' is not empty
. ${TESTSRC-.}/common.sh
setup
rm -f jrunscript-helpTest.out 2>/dev/null
${JRUNSCRIPT} -? > jrunscript-helpTest.out 2>&1
if [ ! -s jrunscript-helpTest.out ]
then
echo "Output of jrunscript -? is empty. Failed."
rm -f jrunscript-helpTest.out 2>/dev/null
exit 1
fi
rm -f jrunscript-helpTest.out 2>/dev/null
${JRUNSCRIPT} -help > jrunscript-helpTest.out 2>&1
if [ ! -s jrunscript-helpTest.out ]
then
echo "Output of jrunscript -help is empty. Failed."
rm -f jrunscript-helpTest.out 2>/dev/null
exit 1
fi
rm -f jrunscript-helpTest.out
echo "Passed"
exit 0

View File

@ -1,62 +0,0 @@
#!/bin/sh
#
# Copyright (c) 2005, 2012, 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.
#
# 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.
#
# @test
# @bug 6265810 6705893
# @build CheckEngine
# @run shell jrunscriptTest.sh
# @summary Test that output of 'jrunscript' interactive matches the repl.out file
. ${TESTSRC-.}/common.sh
setup
${JAVA} ${TESTVMOPTS} ${TESTJAVAOPTS} -cp ${TESTCLASSES} CheckEngine
if [ $? -eq 2 ]; then
echo "No js engine found and engine not required; test vacuously passes."
exit 0
fi
rm -f jrunscriptTest.out 2>/dev/null
${JRUNSCRIPT} -J-Dnashorn.args.prepend=--no-deprecation-warning -J-Djava.awt.headless=true -l nashorn > jrunscriptTest.out 2>&1 <<EOF
v = 2 + 5;
v *= 5; v.doubleValue();
v = v + " is the value";
if (v != 0) { println('yes v != 0'); }
java.lang.System.out.println('hello world from script');
new java.lang.Runnable() { run: function() { println('I am runnable'); }}.run();
EOF
$golden_diff jrunscriptTest.out ${TESTSRC}/repl.out
if [ $? != 0 ]
then
echo "Output of jrunscript -l nashorn differ from expected output. Failed."
rm -f jrunscriptTest.out 2>/dev/null
exit 1
fi
rm -f jrunscriptTest.out
echo "Passed"
exit 0

View File

@ -1,7 +0,0 @@
nashorn> 7
nashorn> 35.0
nashorn> 35 is the value
nashorn> yes v != 0
nashorn> hello world from script
nashorn> I am runnable
nashorn>

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2020 SAP SE. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
@ -142,7 +142,6 @@ public class HelpFlagsTest extends TestHelper {
new ToolHelpSpec("jmod", 1, 1, 1, 0, 1, 0, 2), // -?, -h, --help, -help accepted but not documented.
new ToolHelpSpec("jnativescan", 1, 1, 1, 0, 1, 0, 1), // -?, -h, --help, -help accepted but not documented.
new ToolHelpSpec("jps", 1, 1, 1, 0, 1, 1, 1), // -?, -h, --help -help, Documents -help
new ToolHelpSpec("jrunscript", 1, 1, 1, 0, 1, 1, 7), // -?, -h, --help -help, Documents -help
new ToolHelpSpec("jshell", 1, 1, 1, 0, 1, 0, 1), // -?, -h, --help, -help accepted but not documented.
new ToolHelpSpec("jstack", 1, 1, 1, 0, 1, 1, 1), // -?, -h, --help -help, Documents -help
new ToolHelpSpec("jstat", 1, 1, 1, 0, 1, 1, 1), // -?, -h, --help -help, Documents -help

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2025, 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
@ -93,7 +93,6 @@ public class VersionCheck extends TestHelper {
"jmc",
"jmc.ini",
"jps",
"jrunscript",
"jjs",
"jstack",
"jstat",