This commit is contained in:
Lana Steuck 2014-05-08 15:28:15 -07:00
commit cbe16a93ee
81 changed files with 3735 additions and 113 deletions

View File

@ -0,0 +1,110 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import jdk.nashorn.api.scripting.AbstractJSObject;
import java.nio.DoubleBuffer;
/**
* Simple class demonstrating pluggable script object
* implementation. By implementing jdk.nashorn.api.scripting.JSObject
* (or extending AbstractJSObject which implements it), you
* can supply a friendly script object. Nashorn will call
* 'magic' methods on such a class on 'obj.foo, obj.foo = 33,
* obj.bar()' etc. from script.
*
* In this example, Java nio DoubleBuffer object is wrapped
* as a friendly script object that provides indexed acces
* to buffer content and also support array-like "length"
* readonly property to retrieve buffer's capacity. This class
* also demonstrates a function valued property called "buf".
* On 'buf' method, we return the underlying nio buffer object
* that is being wrapped.
*/
public class BufferArray extends AbstractJSObject {
// underlying nio buffer
private final DoubleBuffer buf;
public BufferArray(int size) {
buf = DoubleBuffer.allocate(size);
}
public BufferArray(DoubleBuffer buf) {
this.buf = buf;
}
// called to check if indexed property exists
@Override
public boolean hasSlot(int index) {
return index > 0 && index < buf.capacity();
}
// get the value from that index
@Override
public Object getSlot(int index) {
return buf.get(index);
}
// set the value at that index
@Override
public void setSlot(int index, Object value) {
buf.put(index, ((Number)value).doubleValue());
}
// do you have a property of that given name?
@Override
public boolean hasMember(String name) {
return "length".equals(name) || "buf".equals(name);
}
// get the value of that named property
@Override
public Object getMember(String name) {
switch (name) {
case "length":
return buf.capacity();
case "buf":
// return a 'function' value for this property
return new AbstractJSObject() {
@Override
public Object call(Object thiz, Object... args) {
return BufferArray.this.buf;
}
// yes, I'm a function !
@Override
public boolean isFunction() {
return true;
}
};
}
return null;
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple java example with type casts.
// see javacastcounter.js.
class CastExample {
public final static int I = (int)23.33;
public final String str = (String)"hello";
}

1
nashorn/samples/README Normal file
View File

@ -0,0 +1 @@
Simple Nashorn examples that can be run with "jjs" tool.

View File

@ -0,0 +1,78 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Usage: jjs array_mapreduce.js
// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
// These functions accept ECMAScript array as well as
// many array-like objects including java arrays.
// So, you can do map/filter/reduce with Java streams or
// you can also use Array.prototype functions as below.
// See also http://en.wikipedia.org/wiki/MapReduce
var DoubleArray = Java.type("double[]");
var StringArray = Java.type("java.lang.String[]");
var map = Array.prototype.map;
var filter = Array.prototype.filter;
var reduce = Array.prototype.reduce;
var jarr = new StringArray(5);
jarr[0] = "nashorn";
jarr[1] = "ecmascript";
jarr[2] = "javascript";
jarr[3] = "js";
jarr[4] = "scheme";
// sum of word lengths
print("Sum word length:",
reduce.call(
map.call(jarr, function(x) x.length),
function(x, y) x + y)
);
// another array example involving numbers
jarr = new DoubleArray(10);
// make random array of numbers
for (var i = 0; i < jarr.length; i++)
jarr[i] = Math.random();
var forEach = Array.prototype.forEach;
// print numbers in the array
forEach.call(jarr, function(x) print(x));
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
map.call(jarr, function(x) x*x),
function(x, y) x + y)
);

View File

@ -0,0 +1,98 @@
#// Usage: jjs -scripting -fx astviewer.js -- <scriptfile>
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (!$OPTIONS._fx) {
print("Usage: jjs -scripting -fx astviewer.js -- <.js file>");
exit(1);
}
// Using JavaFX from Nashorn. See also:
// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
// This example shows AST of a script file as a JavaFX
// tree view in a window. If no file is specified, AST of
// this script file is shown. This script demonstrates
// 'load' function, JavaFX support by -fx, readFully function
// in scripting mode.
// JavaFX classes used
var StackPane = Java.type("javafx.scene.layout.StackPane");
var Scene = Java.type("javafx.scene.Scene");
var TreeItem = Java.type("javafx.scene.control.TreeItem");
var TreeView = Java.type("javafx.scene.control.TreeView");
// Create a javafx TreeItem to view a AST node
function treeItemForASTNode(ast, name) {
var item = new TreeItem(name);
for (var prop in ast) {
var node = ast[prop];
if (typeof node == 'object') {
if (node == null) {
// skip nulls
continue;
}
if (Array.isArray(node) && node.length == 0) {
// skip empty arrays
continue;
}
var subitem = treeItemForASTNode(node, prop);
} else {
var subitem = new TreeItem(prop + ": " + node);
}
item.children.add(subitem);
}
return item;
}
// do we have a script file passed? if not, use current script
var sourceName = arguments.length == 0? __FILE__ : arguments[0];
// load parser.js from nashorn resources
load("nashorn:parser.js");
// read the full content of the file and parse it
// to get AST of the script specified
var ast = parse(readFully(sourceName));
// JavaFX start method
function start(stage) {
stage.title = "AST Viewer";
var rootItem = treeItemForASTNode(ast, sourceName);
var tree = new TreeView(rootItem);
var root = new StackPane();
root.children.add(tree);
stage.scene = new Scene(root, 300, 450);
stage.show();
}

View File

@ -0,0 +1,116 @@
#// Usage: jjs -fx barchart_weather.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Example that retrieves weather data from a URL in JSON
// format and draws bar chart using JavaFX
// -fx check
if (! $OPTIONS._fx) {
print("Usage: jjs -fx barchart_weather.js");
exit(1);
}
// Java classes used
var URL = Java.type("java.net.URL");
var BufferedReader = Java.type("java.io.BufferedReader");
var InputStreamReader = Java.type("java.io.InputStreamReader");
// function to retrieve text content of the given URL
function readTextFromURL(url) {
var str = '';
var u = new URL(url);
var reader = new BufferedReader(
new InputStreamReader(u.openStream()));
try {
reader.lines().forEach(function(x) str += x);
return str;
} finally {
reader.close();
}
}
// change URL for your city here!
var url = "http://api.openweathermap.org/data/2.5/forecast?q=chennai,india&units=metric&mode=json";
// download JSON document and parse
var json = readTextFromURL(url);
var weather = JSON.parse(json);
// View JSON of this using site such as http://www.jsoneditoronline.org/ to know
// about the JSON data format used by this site
// Extracted data from the json object
var temp = weather.list.map(function(x) x.main.temp);
var temp_min = weather.list.map(function(x) x.main.temp_min);
var temp_max = weather.list.map(function(x) x.main.temp_max);
var date = weather.list.map(function(x) x.dt_txt);
// JavaFX classes used
var Scene = Java.type("javafx.scene.Scene");
var BarChart = Java.type("javafx.scene.chart.BarChart");
var CategoryAxis = Java.type("javafx.scene.chart.CategoryAxis");
var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
var XYChart = Java.type("javafx.scene.chart.XYChart");
function start(stage) {
stage.title="Chennai Weather Bar Chart";
var xAxis = new CategoryAxis();
xAxis.label = "date/time";
var yAxis = new NumberAxis();
yAxis.label = "temp in C";
var bc = new BarChart(xAxis, yAxis);
// 3 bars per datetime item - temp, min temp and max temp
var s1 = new XYChart.Series();
s1.name = "temp";
for (d in date) {
s1.data.add(new XYChart.Data(date[d], temp[d]));
}
var s2 = new XYChart.Series();
s2.name = "min temp";
for (d in date) {
s2.data.add(new XYChart.Data(date[d], temp_min[d]));
}
var s3 = new XYChart.Series();
s3.name = "max temp";
for (d in date) {
s3.data.add(new XYChart.Data(date[d], temp_max[d]));
}
bc.data.addAll(s1, s2, s3);
stage.scene = new Scene(bc, 800, 600);
stage.show();
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn allows you treat every Java8 lambda as a function
var JFunction = Java.type("java.util.function.Function");
var obj = new JFunction() {
apply: function(x) {
print(x + ", lambda");
}
};
// prints 'function'
print(typeof obj);
// call it!
obj("hello");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
@ -33,7 +33,11 @@
* This file can be run along with any script you want to run * This file can be run along with any script you want to run
* to print aggregate stat counters from nashorn. * to print aggregate stat counters from nashorn.
* *
* Usage: jjs <your-file.js> counters.js * Usage: jjs -J-Dnashorn.debug <your-file.js> counters.js
*/ */
Debug.dumpCounters(); if (java.lang.System.getProperty("nashorn.debug") == null) {
print("Usage: jjs -J-Dnashorn.debug <your-file.js> counters.js");
} else {
Debug.dumpCounters();
}

View File

@ -0,0 +1,36 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// __DIR__ variable is equivalent of `dirname $0` in
// shell scripts - expands to the directory where
// the current script is located.
print("This script is in the directory: " + __DIR__);

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Usage: jjs disassemble.js -- <.class-file-path>
// Simple .class disassembler that uses bundled ObjectWeb ASM
// classes in jdk8. WARNING: Bundled ObjectWeb ASM classes are
// not part of official jdk8 API. It can be changed/removed
// without notice. So, this script is brittle by design!
// This example demonstrates passing arguments to script
// from jjs command line, nio and ASM usage.
// classes used
var FileSystems = Java.type("java.nio.file.FileSystems");
var Files = Java.type("java.nio.file.Files");
var System = Java.type("java.lang.System");
var PrintWriter = Java.type("java.io.PrintWriter");
// WARNING: uses non-API classes of jdk8!
var ClassReader = Java.type("jdk.internal.org.objectweb.asm.ClassReader");
var TraceClassVisitor = Java.type("jdk.internal.org.objectweb.asm.util.TraceClassVisitor");
// convert file name to Path instance
function path(file) {
return FileSystems.default.getPath(file);
}
// read all file content as a byte[]
function readAllBytes(file) {
return Files.readAllBytes(path(file));
}
// disassemble .class byte[] and prints output to stdout
function disassemble(bytecode) {
var pw = new PrintWriter(System.out);
new ClassReader(bytecode).accept(new TraceClassVisitor(pw), 0);
}
// check for command line arg (for .class file name)
if (arguments.length == 0 || !arguments[0].endsWith('.class')) {
print("Usage: jjs disassemble -- <.class file>");
exit(1);
}
// disassemble the given .class file
disassemble(readAllBytes(arguments[0]));

View File

@ -0,0 +1 @@
Using javax.script engine API of nashorn from script!

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple example showing global variable access from caller
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code!
engine.eval("x = 'hello'");
// access global var from engine
print(engine.get('x'));

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// simple example showing how to call a global script
// function from caller
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code!
engine.eval("function func(name) { print('I am func, hello ' + name) }");
// invoke functions, methods of code evaluated by engine
// from javax.script.Invocable interface. But, hey,
// calling code is JavaScript and don't worry about types :)
engine.invokeFunction("func", "Nashorn");

View File

@ -0,0 +1,64 @@
#// Usage: jjs -scripting callmethod.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// simple example demonstrating calling a script object
// method from script engine user code
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code - too many script escapes?
// use heredoc !
engine.eval(<<CODE
var obj = {
func: function() {
print("I am func of " + this);
},
toString: function() {
return "Object 'obj'";
}
};
CODE);
// invoke methods of an object in script world
// from javax.script.Invocable interface. But, hey,
// calling code is JavaScript and don't worry about types :)
// get that script object on which to call a method
var scriptObj = engine.get("obj");
// call 'func' method on object 'obj'
engine.invokeMethod(scriptObj, "func");

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Example showing how to expose a script global var from caller
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// expose variable to engine
engine.put("name", "Nashorn");
// access it from script
engine.eval("print('Hello, ' + name)");

View File

@ -0,0 +1,71 @@
#// Usage: jjs -scripting foreignobject.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// cross nashorn engine scripting
// access script objects from other engines in natural syntax
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code!
engine.eval(<<CODE
var obj = {
foo: 42,
func: function() {
print("func: " + this.foo);
}
};
CODE);
// Nashorn engine returns script objects as instance of
// the class jdk.nashorn.api.scripting.ScriptObjectMirror
// But nashorn's dynalink linker can treat these objects
// specially to support natural script syntax to access..
// In Java code, you need to use ScriptObjectMirror's
// methods though. Once again, script world is simpler :-)
var foreignObj = engine.get("obj");
// access properties, functions of it
// with natural syntax
print(foreignObj.foo);
foreignObj.func();
print(typeof foreignObj.func);
// access engine's global
var foreignGlobal = engine.eval("this");
// create objects in engine's world from here!
print(new foreignGlobal.Object());
print(new foreignGlobal.Date());

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple hello world example showing create engine
// and eval simple script
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code!
engine.eval("print('hello world')");

View File

@ -0,0 +1,60 @@
#// Usage: jjs -scripting interface.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Example demonstrating how to implement a Java interface
// whose methods are backed by global script functions
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code - too many script escapes?
// use heredoc !
engine.eval(<<CODE
function run() {
print("run global function called");
}
CODE);
// create Java interface object whose methods are
// implemented by script functions. This is from
// javax.script.Invocable. But we are in JS world,
// don't worry about types :)
var Runnable = Java.type("java.lang.Runnable");
var r = engine.getInterface(Runnable.class);
print(r.class);
r.run();

View File

@ -0,0 +1,63 @@
#// Usage: jjs -scripting interface2.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple example demonstrating how to implement java interface
// whose methods are backed by script methods of a script object
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// eval code - too many script escapes?
// use heredoc !
engine.eval(<<CODE
var obj = {
run: function() {
print("I am run method of 'obj'");
}
};
CODE);
// create Java interface object whose methods are
// implemented by script methods of a script object
// This is from javax.script.Invocable. But we are
// in JS world, don't worry about types :)
var Runnable = Java.type("java.lang.Runnable");
var scriptObj = engine.get("obj");
var r = engine.getInterface(scriptObj, Runnable.class);
print(r.class);
r.run();

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple example demonstrating how to expose 'function's
// from embedding code. Any lambda object exposed to engine
// can be called as 'function' in script.
var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
// create manager
var manager = new ScriptEngineManager();
// create engine
var engine = manager.getEngineByName("js");
// Any lambda (@FunctionalInterface annotated type) object can be
// be exposed from script embedding code. Script can call
// it as a function
engine.put("upper", new java.util.function.Function() {
apply: function(x) x.toUpperCase()
});
print(engine.eval("upper('hello')"));

43
nashorn/samples/env.js Normal file
View File

@ -0,0 +1,43 @@
#// Usage: jjs -scripting env.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// In nashorn -scripting mode,
// "$ENV" object exposes process
// environment variables
print($ENV.PATH);
print($ENV.JAVA_HOME);
for (i in $ENV) {
print(i, "->", $ENV[i]);
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports expression closures extension of
// Mozilla JavaScript 1.8. See also
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
// leave {, } and 'return' keyword
function sqr(x) x*x;
// prints 289 (= 17*17)
print(sqr(17));

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports pseudo global variables __FILE__
// and __LINE__ that expands to currently executed
// script file name and current script line number
// prints current file and line number
print("executing " + __FILE__ + " @ " + __LINE__);

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// What is FizzBuzz? http://c2.com/cgi/wiki?FizzBuzzTest
// Yet another FizzBuzz impl. using Java 8 lambda and stream
// but using Nashorn. This is ECMAScript port of @stuartmarks'
// Java implementation
var IntStream = Java.type("java.util.stream.IntStream");
function ifmod(m, r, f) {
return function(i) { return i % m == 0? r : f(i); }
}
// pass script function for lambda
IntStream.rangeClosed(1, 100).
mapToObj(
ifmod(15, "FizzBuzz", ifmod(5, "Buzz", ifmod(3, "Fizz", String))))
.forEach(print);

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports for..each extension supported
// by Mozilla. See also
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in
var strs = [ "hello", "world" ];
for each (str in strs)
print(str);
// create a java int[] object
var JArray = Java.type("int[]");
var arr = new JArray(10);
// store squares as values
for (i in arr)
arr[i] = i*i;
// for .. each on java arrays
print("squares");
for each (i in arr)
print(i);
var System = Java.type("java.lang.System");
// for..each on java Iterables
// print System properties as name = value pairs
print("System properties");
for each (p in System.properties.entrySet()) {
print(p.key, "=", p.value);
}
// print process environment vars as name = value pairs
print("Process environment");
for each (e in System.env.entrySet()) {
print(e.key, "=", e.value);
}

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// print 100 Guassian distributed numbers
var Random = Java.type("java.util.Random");
var DoubleStream = Java.type("java.util.stream.DoubleStream");
var r = new Random();
// expression closure (see expression_closure.js as well)
// passed as lambda double generator. "print" passed as
// double consumer lambda to 'forEach' method.
DoubleStream
.generate(function() r.nextGaussian())
.limit(100)
.forEach(print);

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// print 100 Guassian distributed numbers
var Random = Java.type("java.util.Random");
var DoubleStream = Java.type("java.util.stream.DoubleStream");
// function as lambda double generator. "print" passed as
// double consumer lambda to 'forEach' method.
// Function.prototype.bind used to attach 'state' for the
// generator function.
DoubleStream
.generate(
function(r) {
return r.nextGaussian()
}.bind(this, new Random()))
.limit(100)
.forEach(print);

View File

@ -0,0 +1,142 @@
#// Usage: jjs -scripting gutenberg.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple example that demonstrates reading XML Rss feed
// to generate a HTML file from script and show it by browser
// Java classes used
var Characters = Java.type("javax.xml.stream.events.Characters");
var Factory = Java.type("javax.xml.stream.XMLInputFactory");
var File = Java.type("java.io.File");
var FileWriter = Java.type("java.io.FileWriter");
var PrintWriter = Java.type("java.io.PrintWriter");
var URL = Java.type("java.net.URL");
// read Rss feed from a URL. Returns an array
// of objects having only title and link properties
function readRssFeed(url) {
var fac = Factory.newInstance();
var reader = fac.createXMLEventReader(url.openStream());
// get text content from next event
function getChars() {
var result = "";
var e = reader.nextEvent();
if (e instanceof Characters) {
result = e.getData();
}
return result;
}
var items = [];
var title, link;
var inItem = false;
while (reader.hasNext()) {
var evt = reader.nextEvent();
if (evt.isStartElement()) {
var local = evt.name.localPart;
if (local == "item") {
// capture title, description now
inItem = true;
}
if (inItem) {
switch (local) {
case 'title':
title = getChars();
break;
case 'link':
link = getChars();
break;
}
}
} else if (evt.isEndElement()) {
var local = evt.name.localPart;
if (local == "item") {
// one item done, save it in result array
items.push({ title: title, link: link });
inItem = false;
}
}
}
return items;
}
// generate simple HTML for an RSS feed
function getBooksHtml() {
var url = new URL("http://www.gutenberg.org/cache/epub/feeds/today.rss");
var items = readRssFeed(url);
var str = "<ul>";
// Nashorn's string interpolation and heredoc
// support is very handy in generating text content
// that is filled with elements from runtime objects.
// We insert title and link in <li> elements here.
for each (i in items) {
str += <<EOF
<li>
<a href="${i.link}">${i.title}</a>
</li>
EOF
}
str += "</ul>";
return str;
}
// write the string to the given file
function writeTo(file, str) {
var w = new PrintWriter(new FileWriter(file));
try {
w.print(str);
} finally {
w.close();
}
}
// generate books HTML
var str = getBooksHtml();
// write to file. __DIR__ is directory where
// this script is stored.
var file = new File(__DIR__ + "books.html");
writeTo(file, str);
// show it by desktop browser
try {
var Desktop = Java.type("java.awt.Desktop");
Desktop.desktop.browse(file.toURI());
} catch (e) {
print(e);
}

View File

@ -0,0 +1,51 @@
#// Usage: jjs -scripting heredoc.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Nashorn supports Shell script like here-documents
// in -scripting mode. Here-docs are multi-line strings
// that are possibly interpolated with ${} expressions
// See also http://en.wikipedia.org/wiki/Here_document
var sender = "Buffy the Vampire Slayer";
var recipient = "Spike";
print(<<END
Dear ${recipient},
I wish you to leave Sunnydale and never return.
Not Quite Love,
${sender}
END);

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports Java interface implementation
// by script using anonymous class-like syntax
var Runnable = Java.type("java.lang.Runnable");
var Thread = Java.type("java.lang.Thread");
// use anonymous class-like new syntax
var r = new Runnable() {
run: function() {
print("I am a runnable " + Thread.currentThread());
}
}
r.run();
var t = new Thread(r);
t.start();
t.join();

View File

@ -0,0 +1,202 @@
#// Usage: jjs -fx javaastviewer.js -- <.java files>
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This example demonstrates Java subclassing by Java.extend
// and javac Compiler and Tree API. This example also uses
// -fx and javafx TreeView to visualize Java AST as TreeView
if (!$OPTIONS._fx || arguments.length == 0) {
print("Usage: jjs -fx javaastviewer.js -- <.java files>");
exit(1);
}
// Java types used
var Enum = Java.type("java.lang.Enum");
var HashSet = Java.type("java.util.HashSet");
var Name = Java.type("javax.lang.model.element.Name");
var List = Java.type("java.util.List");
var Set = Java.type("java.util.Set");
var SimpleTreeVisitor = Java.type("com.sun.source.util.SimpleTreeVisitor");
var StringArray = Java.type("java.lang.String[]");
var ToolProvider = Java.type("javax.tools.ToolProvider");
var Tree = Java.type("com.sun.source.tree.Tree");
function javaASTToScriptObject(args) {
// properties ignored (javac implementation class properties) in AST view.
// may not be exhaustive - any getAbc would become "abc" property or
// public field becomes a property of same name.
var ignoredProps = new HashSet();
for each (var word in
['extending', 'implementing', 'init', 'mods', 'clazz', 'defs',
'expr', 'tag', 'preferredPosition', 'qualid', 'recvparam',
'restype', 'params', 'startPosition', 'thrown',
'tree', 'typarams', 'typetag', 'vartype']) {
ignoredProps.add(word);
}
// get the system compiler tool
var compiler = ToolProvider.systemJavaCompiler;
// get standard file manager
var fileMgr = compiler.getStandardFileManager(null, null, null);
// make a list of compilation unit from command line argument file names
// Using Java.to convert script array (arguments) to a Java String[]
var compUnits = fileMgr.getJavaFileObjects(Java.to(args, StringArray));
// create a new compilation task
var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
// subclass SimpleTreeVisitor - converts Java AST node to
// a simple script object by walking through it
var ConverterVisitor = Java.extend(SimpleTreeVisitor);
var visitor = new ConverterVisitor() {
// convert java AST node to a friendly script object
// which can be viewed. Every node ends up in defaultAction
// method of SimpleTreeVisitor method.
defaultAction: function (node, p) {
var resultObj = {};
// Nashorn does not iterate properties and methods of Java objects
// But, we can bind properties of any object (including java objects)
// to a script object and iterate it!
var obj = {};
Object.bindProperties(obj, node);
// we don't want every property, method of java object
for (var prop in obj) {
var val = obj[prop];
var type = typeof val;
// ignore 'method' members
if (type == 'function' || type == 'undefined') {
continue;
}
// ignore properties from Javac implementation
// classes - hack by name!!
if (ignoredProps.contains(prop)) {
continue;
}
// subtree - recurse it
if (val instanceof Tree) {
resultObj[prop] = visitor.visit(val, p);
} else if (val instanceof List) {
// List of trees - recurse each and make an array
var len = val.size();
if (len != 0) {
var arr = [];
for (var j = 0; j < len; j++) {
var e = val[j];
if (e instanceof Tree) {
arr.push(visitor.visit(e, p));
}
}
resultObj[prop] = arr;
}
} else if (val instanceof Set) {
// Set - used for modifier flags
// make array
var len = val.size();
if (len != 0) {
var arr = [];
for each (var e in val) {
if (e instanceof Enum || typeof e == 'string') {
arr.push(e.toString());
}
}
resultObj[prop] = arr;
}
} else if (val instanceof Enum || val instanceof Name) {
// make string for any Enum or Name
resultObj[prop] = val.toString();
} else if (type != 'object') {
// primitives 'as is'
resultObj[prop] = val;
}
}
return resultObj;
}
}
// top level object with one property for each compilation unit
var scriptObj = {};
for each (var cu in task.parse()) {
scriptObj[cu.sourceFile.name] = cu.accept(visitor, null);
}
return scriptObj;
}
// JavaFX classes used
var StackPane = Java.type("javafx.scene.layout.StackPane");
var Scene = Java.type("javafx.scene.Scene");
var TreeItem = Java.type("javafx.scene.control.TreeItem");
var TreeView = Java.type("javafx.scene.control.TreeView");
// Create a javafx TreeItem to view a script object
function treeItemForObject(obj, name) {
var item = new TreeItem(name);
for (var prop in obj) {
var node = obj[prop];
if (typeof node == 'object') {
if (node == null) {
// skip nulls
continue;
}
var subitem = treeItemForObject(node, prop);
} else {
var subitem = new TreeItem(prop + ": " + node);
}
item.children.add(subitem);
}
item.expanded = true;
return item;
}
var commandArgs = arguments;
// JavaFX start method
function start(stage) {
var obj = javaASTToScriptObject(commandArgs);
stage.title = "Java AST Viewer"
var rootItem = treeItemForObject(obj, "AST");
rootItem.expanded = true;
var tree = new TreeView(rootItem);
var root = new StackPane();
root.children.add(tree);
stage.scene = new Scene(root, 300, 450);
stage.show();
}

View File

@ -0,0 +1,107 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Usage: jjs javacastcounter.js -- <.java files>
// This example demonstrates Nashorn Java.extend API
// to subclass a Java class from script.
// This example uses Javac Compiler and Tree API
// to list type casts used in java source files.
if (arguments.length == 0) {
print("Usage: jjs javacastcounter.js -- <.java files>");
exit(1);
}
// Java types used
var ToolProvider = Java.type("javax.tools.ToolProvider");
var TreeScanner = Java.type("com.sun.source.util.TreeScanner");
var Trees = Java.type("com.sun.source.util.Trees");
var StringArray = Java.type("java.lang.String[]");
// get the system compiler tool
var compiler = ToolProvider.systemJavaCompiler;
// get standard file manager
var fileMgr = compiler.getStandardFileManager(null, null, null);
// make a list of compilation unit from command line argument file names
// Using Java.to convert script array (arguments) to a Java String[]
var compUnits = fileMgr.getJavaFileObjects(Java.to(arguments, StringArray));
// create a new compilation task
var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
// SourcePositions object to get positions of AST nodes
var sourcePositions = Trees.instance(task).sourcePositions;
// Subclass TreeScanner class
var CastCounter = Java.extend(TreeScanner);
var counter = new CastCounter() {
// current CompilationUnitTree
compUnit: null,
// current LineMap (pos -> line, column)
lineMap: null,
// current compilation unit's file name
fileName: null,
// overrides of TreeScanner methods
visitCompilationUnit: function(node, p) {
// capture info about current Compilation unit
this.compUnit = node;
this.lineMap = node.lineMap;
this.fileName = node.sourceFile.name;
// Using Java.super API to call super class method here
return Java.super(counter).visitCompilationUnit(node, p);
},
visitTypeCast: function(node, p) {
// print information on this type cast node
var pos = sourcePositions.getStartPosition(this.compUnit, node);
var line = this.lineMap.getLineNumber(pos);
var col = this.lineMap.getColumnNumber(pos);
print(node + " @ " + this.fileName + ":" + line + ":" + col);
// count one more type cast
return 1;
},
reduce: function(r1, r2) {
return (r1 == null ? 0 : r1) + (r2 == null ? 0 : r2);
}
};
// print total number of type cast nodes seen
print("Total casts:", counter.scan(task.parse(), null));

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// JavaImporter along with 'with' statement helps in
// localized Java class references
function readTextFromURL(url) {
// equivalent to
//
// import java.io.*;
// import java.net.*;
// import java.lang.StringBuffer;
//
// only inside the 'with' statement
with (new JavaImporter(java.io,
java.net,
java.lang.StringBuilder)) {
var buf = new StringBuilder();
var u = new URL(url);
var reader = new BufferedReader(
new InputStreamReader(u.openStream()));
var line = null;
try {
while ((line = reader.readLine()) != null)
buf.append(line).append('\n');
} finally {
reader.close();
}
return buf.toString();
}
}
print(readTextFromURL("https://twitter.com/"));

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Java List elements accessed/modified via
// array element access/update syntax
var ArrayList = Java.type("java.util.ArrayList");
var list = new ArrayList();
// add elements to list by List's add method calls
list.add("js");
list.add("ecmascript");
list.add("nashorn");
// get by List's get(int) method
print(list[0]);
print(list[1]);
print(list[2]);
// access list elements by indexed access as well
print(list[0]);
print(list[1]);
print(list[2]);
// assign to list elements by index as well
list[0] = list[0].toUpperCase();
list[1] = list[1].toUpperCase();
list[2] = list[2].toUpperCase();
print(list.get(0));
print(list.get(1));
print(list.get(2));
print(list[0]);
print(list[1]);
print(list[2]);

View File

@ -0,0 +1,58 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Java Map keys as properties
// Demonstrating Java Map key/value can be accessed
// as property/value from script.
var HashMap = Java.type("java.util.HashMap");
var map = new HashMap();
// map key-value access by java get/put method calls
map.put('js', 'nashorn');
print(map.get('js'));
// access keys of map as properties
print(map['js']);
print(map.js);
// also assign new key-value pair
// as 'property-value'
map['language'] = 'java';
print(map.get("language"));
print(map.language);
print(map['language']);
map.answer = 42;
print(map.get("answer"));
print(map.answer);
print(map['answer']);

View File

@ -0,0 +1,146 @@
#// Usage: jjs -scripting javashell.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple Java "shell" with which you can try out
// your few liner Java code leaving imports, main etc.
// And you can leave even compilation as this script
// takes care boilerplate+compile step for you.
// Java types used
var Arrays = Java.type("java.util.Arrays");
var BufferedReader = Java.type("java.io.BufferedReader");
var FileWriter = Java.type("java.io.FileWriter");
var LocalDateTime = Java.type("java.time.LocalDateTime");
var InputStreamReader = Java.type("java.io.InputStreamReader");
var PrintWriter = Java.type("java.io.PrintWriter");
var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
var System = Java.type("java.lang.System");
// read multiple lines of input from stdin till user
// enters an empty line
function input(endMarker, prompt) {
if (!endMarker) {
endMarker = "";
}
if (!prompt) {
prompt = " >> ";
}
var str = "";
var reader = new BufferedReader(new InputStreamReader(System.in));
var line;
while (true) {
System.out.print(prompt);
line = reader.readLine();
if (line == null || line == endMarker) {
break;
}
str += line + "\n";
}
return str;
}
// write the string to the given file
function writeTo(file, str) {
var w = new PrintWriter(new FileWriter(file));
try {
w.print(str);
} finally {
w.close();
}
}
// generate Java code with user's input
// put inside generated main method
function generate(className) {
var usercode = input();
if (usercode == "") {
return false;
}
var fullcode = <<EOF
// userful imports, add more here if you want
// more imports.
import static java.lang.System.*;
import java.io.*;
import java.net.*;
import java.math.*;
import java.nio.file.*;
import java.time.*;
import java.time.chrono.*;
import java.time.format.*;
import java.time.temporal.*;
import java.time.zone.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
public class ${className} {
public static void main(String[] args) throws Exception {
${usercode}
}
}
EOF
writeTo("${className}.java", fullcode);
return true;
}
// execute code command
function exec(args) {
// build child process and start it!
new ProcessBuilder(Arrays.asList(args.split(' ')))
.inheritIO()
.start()
.waitFor();
}
// generate unique name
function uniqueName() {
var now = LocalDateTime.now().toString();
// replace unsafe chars with '_'
return "JavaShell" + now.replace(/-|:|\./g, '_');
}
// read-compile-run loop
while(true) {
var className = uniqueName();
if (generate(className)) {
exec("javac ${className}.java");
exec("java ${className}");
} else {
break;
}
}

View File

@ -0,0 +1,189 @@
#// Usage: jjs -scripting jsadapter_dom.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple example that demonstrates reading XML Rss feed
// to generate a HTML file from script and show it by browser
// Uses XML DOM parser and DOM element wrapped by script
// "proxy" (JSAdapter constructor)
// Java classes used
var DocBuilderFac = Java.type("javax.xml.parsers.DocumentBuilderFactory");
var Node = Java.type("org.w3c.dom.Node");
var File = Java.type("java.io.File");
var FileWriter = Java.type("java.io.FileWriter");
var PrintWriter = Java.type("java.io.PrintWriter");
// constants from Node class
var ELEMENT_NODE = Node.ELEMENT_NODE;
var TEXT_NODE = Node.TEXT_NODE;
// parse XML from uri and return Document
function parseXML(uri) {
var docBuilder = DocBuilderFac.newInstance().newDocumentBuilder();
return docBuilder["parse(java.lang.String)"](uri);
}
// get child Elements of given name of the parent element given
function getChildElements(elem, name) {
var nodeList = elem.childNodes;
var childElems = [];
var len = nodeList.length;
for (var i = 0; i < len; i++) {
var node = nodeList.item(i);
if (node.nodeType == ELEMENT_NODE &&
node.tagName == name) {
childElems.push(wrapElement(node));
}
}
return childElems;
}
// get concatenated child text content of an Element
function getElemText(elem) {
var nodeList = elem.childNodes;
var len = nodeList.length;
var text = '';
for (var i = 0; i < len; i++) {
var node = nodeList.item(i);
if (node.nodeType == TEXT_NODE) {
text += node.nodeValue;
}
}
return text;
}
// Wrap DOM Element object as a convenient script object
// using JSAdapter. JSAdapter is like java.lang.reflect.Proxy
// in that it allows property access, method calls be trapped
// by 'magic' methods like __get__, __call__.
function wrapElement(elem) {
if (! elem) {
return elem;
}
return new JSAdapter() {
// getter to expose child elements and attributes by name
__get__: function(name) {
if (typeof name == 'string') {
if (name.startsWith('@')) {
var attr = elem.getAttributeNode(name.substring(1));
return !attr? undefined : attr.value;
}
var arr = getChildElements(elem, name);
if (arr.length == 1) {
// single child element, expose as single element
return arr[0];
} else {
// multiple children of given name, expose as array
return arr;
}
}
return undefined;
},
__call__: function(name) {
// toString override to get text content of this Element
if (name == 'toString' || name == 'valueOf') {
return getElemText(elem);
}
return undefined;
}
}
}
// generate HTML using here-doc and string interpolation
function getBooksHtml() {
var doc = parseXML("http://www.gutenberg.org/cache/epub/feeds/today.rss");
// wrap document root Element as script convenient object
var rss = wrapElement(doc.documentElement);
print("rss file version " + rss['@version']);
var str = <<HEAD
<html>
<title>${rss.channel.title}</title>
<body>
<h1>${rss.channel.description}</h1>
<p>
Published on ${rss.channel.pubDate}
</p>
HEAD
var items = rss.channel.item;
for each (var i in items) {
str += <<LIST
<dl>
<dt><a href="${i.link}">${i.title}</a></dt>
<dd>${i.description}</dd>
</dl>
LIST
}
str += <<END
</body>
</html>
END
return str;
}
// write the string to the given file
function writeTo(file, str) {
var w = new PrintWriter(new FileWriter(file));
try {
w.print(str);
} finally {
w.close();
}
}
// generate books HTML
var str = getBooksHtml();
// write to file. __DIR__ is directory where
// this script is stored.
var file = new File(__DIR__ + "books.html");
writeTo(file, str);
// show it by desktop browser
try {
var Desktop = Java.type("java.awt.Desktop");
Desktop.desktop.browse(file.toURI());
} catch (e) {
print(e);
}

View File

@ -0,0 +1,75 @@
#// Usage: jjs -scripting -cp . jsobject.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This sample demonstrats how to expose a
// script friendly object from your java code
// by implementing jdk.nashorn.api.scripting.JSObject
// compile the java program
`javac BufferArray.java`;
// print error, if any and exit
if ($ERR != '') {
print($ERR);
exit($EXIT);
}
// create BufferArray
var BufferArray = Java.type("BufferArray");
var bb = new BufferArray(10);
// 'magic' methods called to retrieve set/get
// properties on BufferArray instance
var len = bb.length;
print("bb.length = " + len)
for (var i = 0; i < len; i++) {
bb[i] = i*i;
}
for (var i = 0; i < len; i++) {
print(bb[i]);
}
// get underlying buffer by calling a method
// on BufferArray magic object
// 'buf' is a function member
print(typeof bb.buf);
var buf = bb.buf();
// use retrieved underlying nio buffer
var cap = buf.capacity();
print("buf.capacity() = " + cap);
for (var i = 0; i < cap; i++) {
print(buf.get(i));
}

View File

@ -0,0 +1,62 @@
#// Usage: jjs -scripting -cp . jsobject_mapreduce.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
// These functions accept ECMAScript array as well as
// many array-like objects including JSObjects.
// See also http://en.wikipedia.org/wiki/MapReduce
`javac BufferArray.java`;
var BufferArray = Java.type("BufferArray");
var buf = new BufferArray(10);
var map = Array.prototype.map;
var filter = Array.prototype.filter;
var reduce = Array.prototype.reduce;
// make random list of numbers
for (var i = 0; i < 10; i++)
buf[i] = Math.random();
var forEach = Array.prototype.forEach;
// print numbers in the list
forEach.call(buf, function(x) print(x));
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
map.call(buf, function(x) x*x),
function(x, y) x + y)
);

View File

@ -0,0 +1,120 @@
#// Usage: jjs -fx jsonviewer.js
// or
// jjs -fx jsonviewer.js -- <url-of-json-doc>
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (! $OPTIONS._fx) {
print("Usage: jjs -fx jsonviewer.js -- <url-of-json-doc>");
exit(1);
}
// This example downloads a JSON file from a URL and
// shows the same as a JavaFX tree view.
// Using JavaFX from Nashorn. See also:
// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
// JavaFX classes used
var StackPane = Java.type("javafx.scene.layout.StackPane");
var Scene = Java.type("javafx.scene.Scene");
var TreeItem = Java.type("javafx.scene.control.TreeItem");
var TreeView = Java.type("javafx.scene.control.TreeView");
// read text content of a URL
function readTextFromURL(url) {
// equivalent to
//
// import java.io.*;
// import java.net.*;
// import java.lang.StringBuffer;
//
// only inside the 'with' statement
with (new JavaImporter(java.io,
java.net,
java.lang.StringBuilder)) {
var buf = new StringBuilder();
var u = new URL(url);
var reader = new BufferedReader(
new InputStreamReader(u.openStream()));
var line = null;
try {
while ((line = reader.readLine()) != null)
buf.append(line).append('\n');
} finally {
reader.close();
}
return buf.toString();
}
}
// Create a javafx TreeItem to view a script object
function treeItemForObject(obj, name) {
var item = new TreeItem(name);
for (var prop in obj) {
var node = obj[prop];
if (typeof node == 'object') {
if (node == null) {
// skip nulls
continue;
}
if (Array.isArray(node) && node.length == 0) {
// skip empty arrays
continue;
}
var subitem = treeItemForObject(node, prop);
} else {
var subitem = new TreeItem(prop + ": " + node);
}
item.children.add(subitem);
}
return item;
}
var DEFAULT_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&amp;mode=json&amp;units=metric&amp;cnt=7`";
var url = arguments.length == 0? DEFAULT_URL : arguments[0];
var obj = JSON.parse(readTextFromURL(url));
// JavaFX start method
function start(stage) {
stage.title = "JSON Viewer";
var rootItem = treeItemForObject(obj, url);
var tree = new TreeView(rootItem);
var root = new StackPane();
root.children.add(tree);
stage.scene = new Scene(root, 300, 450);
stage.show();
}

View File

@ -1,3 +1,5 @@
#// Usage: jjs -scripting letter.js -- <sender> <recipient>
/* /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* *

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Usage: jjs list_mapreduce.js
// Many Array.prototype functions such as map,
// filter, reduce, reduceRight, every, some are generic.
// These functions accept ECMAScript array as well as
// many array-like objects including java.util.ArrayLists.
// So, you can do map/filter/reduce with Java streams or
// you can also use Array.prototype functions as below.
// See also http://en.wikipedia.org/wiki/MapReduce
var ArrayList = Java.type("java.util.ArrayList");
var list = new ArrayList();
list.add("nashorn");
list.add("ecmascript");
list.add("javascript");
list.add("js");
list.add("scheme");
var map = Array.prototype.map;
var filter = Array.prototype.filter;
var reduce = Array.prototype.reduce;
// sum of word lengths
print("Sum word length:",
reduce.call(
map.call(list, function(x) x.length),
function(x, y) x + y)
);
// filter use to filter out "j*" and concatenate rest with ":"
// after uppercasing all strings
print(
reduce.call(
map.call(
filter.call(list, function(x) !x.startsWith("j")),
function(x) x.toUpperCase()),
function(x, y) x + ":" + y)
);
// another list example involving numbers
list.clear();
// make random list of numbers
for (var i = 0; i < 10; i++)
list.add(Math.random());
var forEach = Array.prototype.forEach;
// print numbers in the list
forEach.call(list, function(x) print(x));
// print sum of squares of the random numbers
print("Square sum:",
reduce.call(
map.call(list, function(x) x*x),
function(x, y) x + y)
);

View File

@ -0,0 +1,58 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple program that lists available locals. This is ECMAScript
// port of Java example by @brunoborges
// Java classes used
var Arrays = Java.type("java.util.Arrays");
var Collectors = Java.type("java.util.stream.Collectors");
var JString = Java.type("java.lang.String");
var Locale = Java.type("java.util.Locale");
var formatStr = "Country : %s \t\t\t\t:\t Country Code : %s";
// Nashorn allows script functions to be passed
// whereever Java8 lambdas are expected.
// Nashorn also supports "expression closures" supported by
// Mozilla JavaScript 1.8 version. See also
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
// The following prints locales in (country) display name order
var list = Arrays.asList(Locale.getISOCountries())
.stream()
.map(function(x) new Locale("", x))
.sorted(function(c0, c1) c0.displayCountry.compareTo(c1.displayCountry))
.map(function(l) JString.format(formatStr, l.displayCountry, l.country))
.collect(Collectors.toList());
list.forEach(print);

View File

@ -0,0 +1,82 @@
#// Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Logistic map viewer using Java8 Streams and JavaFX
// See also http://en.wikipedia.org/wiki/Logistic_map
if (!$OPTIONS._fx || arguments.length < 2) {
print("Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>");
exit(1);
}
// parameters for the logistic map
var x = parseFloat(arguments[0]);
var R = parseFloat(arguments[1]);
var NUM_POINTS = arguments.length > 2? parseFloat(arguments[2]) : 20;
// Java classes used
var DoubleStream = Java.type('java.util.stream.DoubleStream');
var LineChart = Java.type("javafx.scene.chart.LineChart");
var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
var Scene = Java.type("javafx.scene.Scene");
var Stage = Java.type("javafx.stage.Stage");
var XYChart = Java.type("javafx.scene.chart.XYChart");
function start(stage) {
stage.title = "Logistic Map: initial x = ${x}, R = ${R}";
// make chart
var xAxis = new NumberAxis();
var yAxis = new NumberAxis();
var lineChart = new LineChart(xAxis, yAxis);
xAxis.setLabel("iteration");
yAxis.setLabel("x");
// make chart data series
var series = new XYChart.Series();
var data = series.data;
// populate data using logistic iteration
var i = 0;
DoubleStream
.generate(function() x = R*x*(1-x))
.limit(NUM_POINTS)
.forEach(
function(value) {
data.add(new XYChart.Data(i, value));
i++;
}
);
// add to stage
var scene = new Scene(lineChart, 800, 600);
lineChart.data.add(series);
stage.scene = scene;
stage.show();
}

View File

@ -0,0 +1,37 @@
#// Usage: jjs -scripting options.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// print all option names and values
for (i in $OPTIONS) {
print(i, '=', $OPTIONS[i]);
}

View File

@ -0,0 +1,38 @@
#// Usage: jjs -scripting greeting.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// readLine prints prompt and reads user response
var name = readLine("Your name please: ");
// user name is interpolated within string
print("Hello ${name}");

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports passing script functions whenever
// a SAM (single abstract method) type object is expected
var System = Java.type("java.lang.System");
var Timer = Java.type("java.util.Timer");
var timer = new Timer();
// schedule method accepts java.util.TimerTask
// which is a single-abstract-method type. you
// can pass a script function and nashorn will
// wrap it as SAM implementor.
timer.schedule(function() {
print("Hello World!");
}, 1000);
// wait for timer thread to print by
// reading from stdin.
print("press any key to exit after message from timer...");
System.in.read();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
@ -29,50 +29,53 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
/** // Usage: jjs shell.js
* This is a simple shell tool in JavaScript.
/* This is a simple shell tool in JavaScript.
* *
* Runs any operating system command using Java "exec". When "eval" command is * Runs any operating system command using Java "exec". When "eval" command is
* used, evaluates argument(s) as JavaScript code. * used, evaluates argument(s) as JavaScript code.
*/ */
var imports = new JavaImporter(java.io, java.lang, java.util); (function() {
// Java classes used
var Arrays = Java.type("java.util.Arrays");
var BufferedReader = Java.type("java.io.BufferedReader");
var InputStreamReader = Java.type("java.io.InputStreamReader");
var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
var System = Java.type("java.lang.System");
function prompt() { // print prompt
java.lang.System.out.print(">"); function prompt() {
} System.out.print("> ");
}
with (imports) { var reader = new BufferedReader(new InputStreamReader(System.in));
var reader = new BufferedReader(new InputStreamReader(System["in"]));
var line = null;
prompt(); prompt();
while ((line = reader.readLine()) != null) { // read and evaluate each line from stdin
if (line != "") { reader.lines().forEach(function(line) {
var args = line.split(" "); if (! line.isEmpty()) {
var args = line.split(' ');
try { try {
if (args[0] == "eval") { // special 'eval' command to evaluate JS code
var code = line.substring("eval".length); if (args[0] == 'eval') {
var code = line.substring('eval'.length);
var res = eval(code); var res = eval(code);
if (res != undefined) { if (res != undefined) {
print(res); print(res);
} }
} else { } else {
var argList = new ArrayList(); // build child process and start it!
for (i in args) { argList.add(args[i]); } new ProcessBuilder(Arrays.asList(args))
var procBuilder = new ProcessBuilder(argList); .inheritIO()
procBuilder.redirectErrorStream(); .start()
var proc = procBuilder.start(); .waitFor();
var out = new BufferedReader(new InputStreamReader(proc.getInputStream()));
var line = null;
while ((line = out.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
} }
} catch (e) { } catch (e) {
// print exception, if any
print(e); print(e);
} }
} }
prompt(); prompt();
} })
} })()

55
nashorn/samples/stack.js Normal file
View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// nashorn supports 'stack' property on ECMAScript
// error objects. This property's value is a string
// that shows script stack trace.
function g() {
throw new Error("wrong");
}
function f() {
g();
}
// Output looks something like:
//
// Error: wrong
// at g (stack.js:37)
// at f (stack.js:41)
// at <program> (stack.js:52)
try {
f();
} catch (e) {
print(e.stack);
}

View File

@ -30,4 +30,3 @@
*/ */
print("Hello World"); print("Hello World");

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// generate/print 100 uniformly distributed random values
// and print summary statistics on it
var DoubleStream = Java.type("java.util.stream.DoubleStream");
// pass script function when a lambda is required
// Math.random passed here for double generator lambda
// print passed to forEach method
DoubleStream
.generate(Math.random)
.limit(100)
.forEach(print);
print(DoubleStream
.generate(Math.random)
.limit(100)
.summaryStatistics());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
@ -29,27 +29,28 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
/** // Usage: jjs uniq.js
* Prints unique lines from a given file. // or: jjs uniq.js -- <file>
*/
if (arguments.length != 1) { // omit repeated lines and print unique lines
print("Usage: jjs uniq.js -- <file>");
java.lang.System.exit(1);
}
var imports = new JavaImporter(java.io); var BufferedReader = Java.type("java.io.BufferedReader");
var FileReader = Java.type("java.io.FileReader");
var InputStreamReader = Java.type("java.io.InputStreamReader");
var System = Java.type("java.lang.System");
// use object as set - but insertion order preserved
var uniqueLines = {}; var uniqueLines = {};
with (imports) { var reader = arguments.length > 0 ?
var reader = new BufferedReader(new FileReader(arguments[0])); new FileReader(arguments[0]) :
while ((line = reader.readLine()) != null) { new InputStreamReader(System.in);
// using a JS object as a map... reader = new BufferedReader(reader);
uniqueLines[line] = true;
}
}
// now print the collected lines // add unique lines
for (i in uniqueLines) { reader.lines().forEach(function(line) {
print(i); uniqueLines[line] = true;
})
for (line in uniqueLines) {
print(line);
} }

48
nashorn/samples/uniqs.js Normal file
View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Usage: jjs uniqs.js -- <file>
// omit repeated lines and print unique lines
// But this version uses Stream API
if (arguments.length < 1) {
print("Usage: jjs uniqs.js -- <file>");
exit(1);
}
var Files = Java.type("java.nio.file.Files");
var FileSystems = Java.type("java.nio.file.FileSystems");
print('Unique lines:',
Files
.lines(FileSystems.default.getPath(arguments[0]))
.distinct()
.peek(print)
.count());

View File

@ -0,0 +1,63 @@
#// usage: jjs -scripting weather.js
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Simple nashorn example showing back-quote exec process,
// JSON and Java8 streams
var Arrays = Java.type("java.util.Arrays");
// use curl to download JSON weather data from the net
// use backquote -scripting mode syntax to exec a process
`curl http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&amp;mode=json&amp;units=metric&amp;cnt=7`;
// parse JSON
var weather = JSON.parse($OUT);
// pull out humidity as array
var humidity = weather.list.map(function(curVal) {
return curVal.humidity;
})
// Stream API to print stat
print("Humidity");
print(Arrays["stream(int[])"](humidity).summaryStatistics());
// pull maximum day time temperature
var temp = weather.list.map(function(curVal) {
return curVal.temp.max;
});
// Stream API to print stat
print("Max Temperature");
print(Arrays["stream(double[])"](temp).summaryStatistics());

View File

@ -525,6 +525,31 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt)); return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
} }
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
final Global oldGlobal = Context.getGlobal();
final boolean globalChanged = (oldGlobal != ctxtGlobal);
try {
if (globalChanged) {
Context.setGlobal(ctxtGlobal);
}
final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
// set ScriptContext variables if ctxt is non-null
if (ctxt != null) {
setContextVariables(ctxtGlobal, ctxt);
}
return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
} catch (final Exception e) {
throwAsScriptException(e, ctxtGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
}
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException { private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
if (script == null) { if (script == null) {
return null; return null;
@ -571,18 +596,38 @@ public final class NashornScriptEngine extends AbstractScriptEngine implements C
} }
private CompiledScript asCompiledScript(final Source source) throws ScriptException { private CompiledScript asCompiledScript(final Source source) throws ScriptException {
final ScriptFunction func = compileImpl(source, context); final Context.MultiGlobalCompiledScript mgcs;
final ScriptFunction func;
final Global oldGlobal = Context.getGlobal();
final Global newGlobal = getNashornGlobalFrom(context);
final boolean globalChanged = (oldGlobal != newGlobal);
try {
if (globalChanged) {
Context.setGlobal(newGlobal);
}
mgcs = nashornContext.compileScript(source);
func = mgcs.getFunction(newGlobal);
} catch (final Exception e) {
throwAsScriptException(e, newGlobal);
throw new AssertionError("should not reach here");
} finally {
if (globalChanged) {
Context.setGlobal(oldGlobal);
}
}
return new CompiledScript() { return new CompiledScript() {
@Override @Override
public Object eval(final ScriptContext ctxt) throws ScriptException { public Object eval(final ScriptContext ctxt) throws ScriptException {
final Global globalObject = getNashornGlobalFrom(ctxt); final Global globalObject = getNashornGlobalFrom(ctxt);
// Are we running the script in the correct global? // Are we running the script in the same global in which it was compiled?
if (func.getScope() == globalObject) { if (func.getScope() == globalObject) {
return evalImpl(func, ctxt, globalObject); return evalImpl(func, ctxt, globalObject);
} }
// ScriptContext with a different global. Compile again!
// Note that we may still hit per-global compilation cache. // different global
return evalImpl(compileImpl(source, ctxt), ctxt, globalObject); return evalImpl(mgcs, ctxt, globalObject);
} }
@Override @Override
public ScriptEngine getEngine() { public ScriptEngine getEngine() {

View File

@ -1451,7 +1451,10 @@ final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContex
if (value == null) { if (value == null) {
hasGettersSetters = true; hasGettersSetters = true;
} else if (key.equals(ScriptObject.PROTO_PROPERTY_NAME)) { } else if (propertyNode.getKey() instanceof IdentNode &&
key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
// ES6 draft compliant __proto__ inside object literal
// Identifier key and name is __proto__
protoNode = value; protoNode = value;
continue; continue;
} }

View File

@ -1906,6 +1906,13 @@ public final class Global extends ScriptObject implements Scope {
// Object.getPrototypeOf(Function.prototype) === Object.prototype // Object.getPrototypeOf(Function.prototype) === Object.prototype
anon.setInitialProto(ObjectPrototype); anon.setInitialProto(ObjectPrototype);
// ES6 draft compliant __proto__ property of Object.prototype
// accessors on Object.prototype for "__proto__"
final ScriptFunction getProto = ScriptFunctionImpl.makeFunction("getProto", ScriptObject.GETPROTO);
final ScriptFunction setProto = ScriptFunctionImpl.makeFunction("setProto", ScriptObject.SETPROTOCHECK);
ObjectPrototype.addOwnProperty("__proto__", Attribute.NOT_ENUMERABLE, getProto, setProto);
// Function valued properties of Function.prototype were not properly // Function valued properties of Function.prototype were not properly
// initialized. Because, these were created before global.function and // initialized. Because, these were created before global.function and
// global.object were not initialized. // global.object were not initialized.

View File

@ -33,6 +33,7 @@ import static jdk.nashorn.internal.parser.TokenType.CASE;
import static jdk.nashorn.internal.parser.TokenType.CATCH; import static jdk.nashorn.internal.parser.TokenType.CATCH;
import static jdk.nashorn.internal.parser.TokenType.COLON; import static jdk.nashorn.internal.parser.TokenType.COLON;
import static jdk.nashorn.internal.parser.TokenType.COMMARIGHT; import static jdk.nashorn.internal.parser.TokenType.COMMARIGHT;
import static jdk.nashorn.internal.parser.TokenType.CONST;
import static jdk.nashorn.internal.parser.TokenType.DECPOSTFIX; import static jdk.nashorn.internal.parser.TokenType.DECPOSTFIX;
import static jdk.nashorn.internal.parser.TokenType.DECPREFIX; import static jdk.nashorn.internal.parser.TokenType.DECPREFIX;
import static jdk.nashorn.internal.parser.TokenType.ELSE; import static jdk.nashorn.internal.parser.TokenType.ELSE;
@ -849,6 +850,11 @@ loop:
expect(SEMICOLON); expect(SEMICOLON);
break; break;
default: default:
if (env._const_as_var && type == CONST) {
variableStatement(true);
break;
}
if (type == IDENT || isNonStrictModeIdent()) { if (type == IDENT || isNonStrictModeIdent()) {
if (T(k + 1) == COLON) { if (T(k + 1) == COLON) {
labelStatement(); labelStatement();
@ -1110,6 +1116,12 @@ loop:
case SEMICOLON: case SEMICOLON:
break; break;
default: default:
if (env._const_as_var && type == CONST) {
// Var statements captured in for outer block.
vars = variableStatement(false);
break;
}
final Expression expression = expression(unaryExpression(), COMMARIGHT.getPrecedence(), true); final Expression expression = expression(unaryExpression(), COMMARIGHT.getPrecedence(), true);
forNode = forNode.setInit(lc, expression); forNode = forNode.setInit(lc, expression);
break; break;

View File

@ -111,7 +111,7 @@ public enum TokenType {
CATCH (KEYWORD, "catch"), CATCH (KEYWORD, "catch"),
// CHAR (FUTURE, "char"), // CHAR (FUTURE, "char"),
CLASS (FUTURE, "class"), CLASS (FUTURE, "class"),
CONST (FUTURE, "const"), CONST (KEYWORD, "const"),
CONTINUE (KEYWORD, "continue"), CONTINUE (KEYWORD, "continue"),
DEBUGGER (KEYWORD, "debugger"), DEBUGGER (KEYWORD, "debugger"),
DEFAULT (KEYWORD, "default"), DEFAULT (KEYWORD, "default"),

View File

@ -489,6 +489,39 @@ public final class Context {
return compileScript(source, scope, this.errors); return compileScript(source, scope, this.errors);
} }
/**
* Interface to represent compiled code that can be re-used across many
* global scope instances
*/
public static interface MultiGlobalCompiledScript {
/**
* Obtain script function object for a specific global scope object.
*
* @param newGlobal global scope for which function object is obtained
* @return script function for script level expressions
*/
public ScriptFunction getFunction(final Global newGlobal);
}
/**
* Compile a top level script.
*
* @param source the script source
* @return reusable compiled script across many global scopes.
*/
public MultiGlobalCompiledScript compileScript(final Source source) {
final Class<?> clazz = compile(source, this.errors, this._strict);
final MethodHandle runMethodHandle = getRunScriptHandle(clazz);
final boolean strict = isStrict(clazz);
return new MultiGlobalCompiledScript() {
@Override
public ScriptFunction getFunction(final Global newGlobal) {
return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, newGlobal, strict);
}
};
}
/** /**
* Entry point for {@code eval} * Entry point for {@code eval}
* *
@ -949,14 +982,8 @@ public final class Context {
return ScriptRuntime.apply(script, thiz); return ScriptRuntime.apply(script, thiz);
} }
private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) { private static MethodHandle getRunScriptHandle(final Class<?> script) {
if (script == null) { return MH.findStatic(
return null;
}
// Get run method - the entry point to the script
final MethodHandle runMethodHandle =
MH.findStatic(
MethodHandles.lookup(), MethodHandles.lookup(),
script, script,
RUN_SCRIPT.symbolName(), RUN_SCRIPT.symbolName(),
@ -964,14 +991,24 @@ public final class Context {
Object.class, Object.class,
ScriptFunction.class, ScriptFunction.class,
Object.class)); Object.class));
}
boolean strict; private static boolean isStrict(final Class<?> script) {
try { try {
strict = script.getField(STRICT_MODE.symbolName()).getBoolean(null); return script.getField(STRICT_MODE.symbolName()).getBoolean(null);
} catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
strict = false; return false;
} }
}
private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
if (script == null) {
return null;
}
// Get run method - the entry point to the script
final MethodHandle runMethodHandle = getRunScriptHandle(script);
boolean strict = isStrict(script);
// Package as a JavaScript function and pass function back to shell. // Package as a JavaScript function and pass function back to shell.
return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict); return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);

View File

@ -62,6 +62,9 @@ public final class ScriptEnvironment {
/** Only compile script, do not run it or generate other ScriptObjects */ /** Only compile script, do not run it or generate other ScriptObjects */
public final boolean _compile_only; public final boolean _compile_only;
/** Accept "const" keyword and treat it as variable. Interim feature */
public final boolean _const_as_var;
/** Accumulated callsite flags that will be used when bootstrapping script callsites */ /** Accumulated callsite flags that will be used when bootstrapping script callsites */
public final int _callsite_flags; public final int _callsite_flags;
@ -200,6 +203,7 @@ public final class ScriptEnvironment {
_class_cache_size = options.getInteger("class.cache.size"); _class_cache_size = options.getInteger("class.cache.size");
_compile_only = options.getBoolean("compile.only"); _compile_only = options.getBoolean("compile.only");
_const_as_var = options.getBoolean("const.as.var");
_debug_lines = options.getBoolean("debug.lines"); _debug_lines = options.getBoolean("debug.lines");
_dest_dir = options.getString("d"); _dest_dir = options.getString("d");
_dump_on_error = options.getBoolean("doe"); _dump_on_error = options.getBoolean("doe");

View File

@ -91,7 +91,7 @@ import jdk.nashorn.internal.runtime.linker.NashornGuards;
*/ */
public abstract class ScriptObject implements PropertyAccess { public abstract class ScriptObject implements PropertyAccess {
/** __proto__ special property name */ /** __proto__ special property name inside object literals. ES6 draft. */
public static final String PROTO_PROPERTY_NAME = "__proto__"; public static final String PROTO_PROPERTY_NAME = "__proto__";
/** Search fall back routine name for "no such method" */ /** Search fall back routine name for "no such method" */
@ -130,8 +130,10 @@ public abstract class ScriptObject implements PropertyAccess {
/** Indexed array data. */ /** Indexed array data. */
private ArrayData arrayData; private ArrayData arrayData;
static final MethodHandle GETPROTO = findOwnMH("getProto", ScriptObject.class); /** Method handle to retrive prototype of this object */
static final MethodHandle SETPROTOCHECK = findOwnMH("setProtoCheck", void.class, Object.class); public static final MethodHandle GETPROTO = findOwnMH("getProto", ScriptObject.class);
/** Method handle to set prototype of this object */
public static final MethodHandle SETPROTOCHECK = findOwnMH("setProtoCheck", void.class, Object.class);
static final MethodHandle MEGAMORPHIC_GET = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class, boolean.class); static final MethodHandle MEGAMORPHIC_GET = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class, boolean.class);
static final MethodHandle GLOBALFILTER = findOwnMH("globalFilter", Object.class, Object.class); static final MethodHandle GLOBALFILTER = findOwnMH("globalFilter", Object.class, Object.class);
@ -1732,10 +1734,6 @@ public abstract class ScriptObject implements PropertyAccess {
MethodHandle methodHandle; MethodHandle methodHandle;
if (find == null) { if (find == null) {
if (PROTO_PROPERTY_NAME.equals(name)) {
return new GuardedInvocation(GETPROTO, NashornGuards.getScriptObjectGuard());
}
if ("getProp".equals(operator)) { if ("getProp".equals(operator)) {
return noSuchProperty(desc, request); return noSuchProperty(desc, request);
} else if ("getMethod".equals(operator)) { } else if ("getMethod".equals(operator)) {
@ -1890,9 +1888,7 @@ public abstract class ScriptObject implements PropertyAccess {
return createEmptySetMethod(desc, "property.not.writable", true); return createEmptySetMethod(desc, "property.not.writable", true);
} }
} else { } else {
if (PROTO_PROPERTY_NAME.equals(name)) { if (! isExtensible()) {
return new GuardedInvocation(SETPROTOCHECK, NashornGuards.getScriptObjectGuard());
} else if (! isExtensible()) {
return createEmptySetMethod(desc, "object.non.extensible", false); return createEmptySetMethod(desc, "object.non.extensible", false);
} }
} }

View File

@ -46,9 +46,6 @@ public class JdkRegExp extends RegExp {
/** Java regexp pattern to use for match. We compile to one of these */ /** Java regexp pattern to use for match. We compile to one of these */
private Pattern pattern; private Pattern pattern;
/** The matcher */
private RegExpMatcher matcher;
/** /**
* Construct a Regular expression from the given {@code source} and {@code flags} strings. * Construct a Regular expression from the given {@code source} and {@code flags} strings.
* *
@ -95,14 +92,7 @@ public class JdkRegExp extends RegExp {
return null; // never matches or similar, e.g. a[] return null; // never matches or similar, e.g. a[]
} }
RegExpMatcher currentMatcher = this.matcher; return new DefaultMatcher(str);
if (currentMatcher == null || matcher.getInput() != str) {
currentMatcher = new DefaultMatcher(str);
this.matcher = currentMatcher;
}
return currentMatcher;
} }
class DefaultMatcher implements RegExpMatcher { class DefaultMatcher implements RegExpMatcher {

View File

@ -44,9 +44,6 @@ public class JoniRegExp extends RegExp {
/** Compiled Joni Regex */ /** Compiled Joni Regex */
private Regex regex; private Regex regex;
/** Matcher */
private RegExpMatcher matcher;
/** /**
* Construct a Regular expression from the given {@code pattern} and {@code flags} strings. * Construct a Regular expression from the given {@code pattern} and {@code flags} strings.
* *
@ -95,14 +92,7 @@ public class JoniRegExp extends RegExp {
return null; return null;
} }
RegExpMatcher currentMatcher = this.matcher; return new JoniMatcher(input);
if (currentMatcher == null || input != currentMatcher.getInput()) {
currentMatcher = new JoniMatcher(input);
this.matcher = currentMatcher;
}
return currentMatcher;
} }
/** /**

View File

@ -131,12 +131,13 @@ public final class Regex implements RegexState {
this.warnings = null; this.warnings = null;
} }
public void compile() { public synchronized MatcherFactory compile() {
if (factory == null && analyser != null) { if (factory == null && analyser != null) {
Compiler compiler = new ArrayCompiler(analyser); new ArrayCompiler(analyser).compile();
analyser = null; // only do this once analyser = null; // only do this once
compiler.compile();
} }
assert factory != null;
return factory;
} }
public Matcher matcher(char[] chars) { public Matcher matcher(char[] chars) {
@ -144,8 +145,11 @@ public final class Regex implements RegexState {
} }
public Matcher matcher(char[] chars, int p, int end) { public Matcher matcher(char[] chars, int p, int end) {
compile(); MatcherFactory matcherFactory = factory;
return factory.create(this, chars, p, end); if (matcherFactory == null) {
matcherFactory = compile();
}
return matcherFactory.create(this, chars, p, end);
} }
public WarnCallback getWarnings() { public WarnCallback getWarnings() {

View File

@ -102,6 +102,13 @@ nashorn.option.compile.only = { \
type=Boolean \ type=Boolean \
} }
nashorn.option.const.as.var = { \
name="--const-as-var", \
is_undocumented=true, \
desc="Replace 'const' with 'var'.", \
type=Boolean \
}
nashorn.option.d = { \ nashorn.option.d = { \
name="--dump-debug-dir", \ name="--dump-debug-dir", \
short_name="-d", \ short_name="-d", \

View File

@ -453,7 +453,7 @@ public class Shell {
} }
} finally { } finally {
if (globalChanged) { if (globalChanged) {
Context.setGlobal(global); Context.setGlobal(oldGlobal);
} }
} }

View File

@ -26,6 +26,7 @@
* Ensure that all parseable files can be parsed using parser API. * Ensure that all parseable files can be parsed using parser API.
* *
* @test * @test
* @option --const-as-var
* @option -scripting * @option -scripting
* @run * @run
*/ */

View File

@ -32,10 +32,6 @@ var obj = {};
obj.__proto__ = null; obj.__proto__ = null;
if (obj.__proto__ !== null || typeof(obj.__proto__) != 'object') {
fail("obj.__proto__ is expected to be null");
}
var p = Object.getPrototypeOf(obj); var p = Object.getPrototypeOf(obj);
if (p !== null || typeof(p) != 'object') { if (p !== null || typeof(p) != 'object') {
fail("Object.getPrototypeOf(obj) is expected to be null"); fail("Object.getPrototypeOf(obj) is expected to be null");

View File

@ -46,6 +46,6 @@ var obj2 = {
__proto__: null __proto__: null
}; };
if (obj2.__proto__ !== null || Object.getPrototypeOf(obj2) !== null) { if (Object.getPrototypeOf(obj2) !== null) {
fail("obj2.__proto__ was not set to null inside literal"); fail("obj2.__proto__ was not set to null inside literal");
} }

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2014, 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.
*/
/**
* JDK-8027933: Add const.as.var option
*
* @test
* @option --const-as-var
* @run
*/
const THE_ANSWER = 42;
print("Answer to all questions: " + THE_ANSWER);
print((function () {
const FORTY_TWO = 42;
return FORTY_TWO
})())

View File

@ -0,0 +1,2 @@
Answer to all questions: 42
42

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2010, 2014, 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.
*/
/**
* JDK-8041998: RegExp implementation is not thread-safe
*
* @test
* @run
*/
var Thread = java.lang.Thread;
function run() {
var line = 'content-type: text/html';
for (var i = 0; i < 300; i++) {
Thread.sleep(1);
line.split(/: /);
}
print("done");
}
var threads = [];
for (var i = 0; i < 4; i++) {
var thread = new Thread(run);
thread.start();
threads.push(thread);
}
for (var i = 0; i < 4; i++) {
threads[i].join();
}

View File

@ -0,0 +1,4 @@
done
done
done
done

View File

@ -0,0 +1,65 @@
/*
* Copyright (c) 2014, 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.
*/
/**
* JDK-8042364: Make __proto__ ES6 draft compliant
*
* @test
* @run
*/
// check for Object.prototype.__proto__ accessor property
print("Object.prototype has __proto__?",
Object.prototype.hasOwnProperty("__proto__"))
var desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__")
print("descriptor");
print(JSON.stringify(desc))
print("getter", desc.get)
print("setter", desc.set)
// no computed "__proto__" name, only identifier!
var p = {}
var obj = {
"__proto__" : p
}
if (Object.getPrototypeOf(obj) === p) {
fail("obj has wrong __proto__, allows computed __proto__!")
}
if (obj.__proto__ !== p) {
fail("__proto__ not created as normal property!")
}
if (Object.getPrototypeOf(obj) !== Object.prototype) {
fail("obj has wrong __proto__")
}
var obj2 = {
__proto__: p
}
if (Object.getPrototypeOf(obj2) !== p) {
fail("can't set __proto__ in object literal")
}

View File

@ -0,0 +1,5 @@
Object.prototype has __proto__? true
descriptor
{"configurable":true,"enumerable":false}
getter function getProto() { [native code] }
setter function setProto() { [native code] }

View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2014, 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.
*/
/**
* JDK-8027933: Add const.as.var option
*
* @test/compile-error
*/
// without --const-as-var the following should fail to compile
const THE_ANSWER = 42;

View File

@ -0,0 +1,3 @@
test/script/error/JDK-8027933.js:31:0 Expected an operand but found const
const THE_ANSWER = 42;
^

View File

@ -71,6 +71,7 @@ public class CompilerTest {
options.set("print.ast", true); options.set("print.ast", true);
options.set("print.parse", true); options.set("print.parse", true);
options.set("scripting", true); options.set("scripting", true);
options.set("const.as.var", true);
final ErrorManager errors = new ErrorManager() { final ErrorManager errors = new ErrorManager() {
@Override @Override

View File

@ -65,6 +65,7 @@ public class ParserTest {
options.set("anon.functions", true); options.set("anon.functions", true);
options.set("parse.only", true); options.set("parse.only", true);
options.set("scripting", true); options.set("scripting", true);
options.set("const.as.var", true);
ErrorManager errors = new ErrorManager(); ErrorManager errors = new ErrorManager();
this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader()); this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader());

View File

@ -220,4 +220,19 @@ public class TrustedScriptEngineTest {
// bar should be visible in default context // bar should be visible in default context
assertTrue(e.eval("typeof bar").equals("function")); assertTrue(e.eval("typeof bar").equals("function"));
} }
@Test public void nashornSwallowsConstKeyword() throws Exception {
final NashornScriptEngineFactory f = new NashornScriptEngineFactory();
final String[] args = new String[] { "--const-as-var" };
final ScriptEngine engine = f.getScriptEngine(args);
final Object ret = engine.eval(""
+ "(function() {\n"
+ " const x = 10;\n"
+ " return x;\n"
+ "})();"
);
assertEquals(ret, 10, "Parsed and executed OK");
}
} }