Merge jdk8u20-b15

Wed, 14 May 2014 11:02:04 -0700

author
lana
date
Wed, 14 May 2014 11:02:04 -0700
changeset 852
bb2d11667547
parent 843
fc45fab1b91c
parent 851
41be00d23622
child 853
c89a4945404c
child 855
ffdb43036807
child 886
90c4833e0f87

Merge

     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/BufferArray.java	Wed May 14 11:02:04 2014 -0700
     1.3 @@ -0,0 +1,110 @@
     1.4 +/*
     1.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     1.6 + *
     1.7 + * Redistribution and use in source and binary forms, with or without
     1.8 + * modification, are permitted provided that the following conditions
     1.9 + * are met:
    1.10 + *
    1.11 + *   - Redistributions of source code must retain the above copyright
    1.12 + *     notice, this list of conditions and the following disclaimer.
    1.13 + *
    1.14 + *   - Redistributions in binary form must reproduce the above copyright
    1.15 + *     notice, this list of conditions and the following disclaimer in the
    1.16 + *     documentation and/or other materials provided with the distribution.
    1.17 + *
    1.18 + *   - Neither the name of Oracle nor the names of its
    1.19 + *     contributors may be used to endorse or promote products derived
    1.20 + *     from this software without specific prior written permission.
    1.21 + *
    1.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    1.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    1.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    1.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    1.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    1.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    1.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    1.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    1.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    1.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    1.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.33 + */
    1.34 +
    1.35 +import jdk.nashorn.api.scripting.AbstractJSObject;
    1.36 +import java.nio.DoubleBuffer;
    1.37 +
    1.38 +/**
    1.39 + * Simple class demonstrating pluggable script object
    1.40 + * implementation. By implementing jdk.nashorn.api.scripting.JSObject
    1.41 + * (or extending AbstractJSObject which implements it), you
    1.42 + * can supply a friendly script object. Nashorn will call
    1.43 + * 'magic' methods on such a class on 'obj.foo, obj.foo = 33,
    1.44 + * obj.bar()' etc. from script.
    1.45 + *
    1.46 + * In this example, Java nio DoubleBuffer object is wrapped
    1.47 + * as a friendly script object that provides indexed acces
    1.48 + * to buffer content and also support array-like "length"
    1.49 + * readonly property to retrieve buffer's capacity. This class
    1.50 + * also demonstrates a function valued property called "buf".
    1.51 + * On 'buf' method, we return the underlying nio buffer object
    1.52 + * that is being wrapped.
    1.53 + */
    1.54 +public class BufferArray extends AbstractJSObject {
    1.55 +    // underlying nio buffer
    1.56 +    private final DoubleBuffer buf;
    1.57 +
    1.58 +    public BufferArray(int size) {
    1.59 +        buf = DoubleBuffer.allocate(size);
    1.60 +    }
    1.61 +
    1.62 +    public BufferArray(DoubleBuffer buf) {
    1.63 +        this.buf = buf;
    1.64 +    }
    1.65 +
    1.66 +    // called to check if indexed property exists
    1.67 +    @Override
    1.68 +    public boolean hasSlot(int index) {
    1.69 +        return index > 0 && index < buf.capacity();
    1.70 +    }
    1.71 +
    1.72 +    // get the value from that index
    1.73 +    @Override
    1.74 +    public Object getSlot(int index) {
    1.75 +       return buf.get(index);
    1.76 +    }
    1.77 +
    1.78 +    // set the value at that index
    1.79 +    @Override
    1.80 +    public void setSlot(int index, Object value) {
    1.81 +       buf.put(index, ((Number)value).doubleValue());
    1.82 +    }
    1.83 +
    1.84 +    // do you have a property of that given name?
    1.85 +    @Override
    1.86 +    public boolean hasMember(String name) {
    1.87 +       return "length".equals(name) || "buf".equals(name);
    1.88 +    }
    1.89 +
    1.90 +    // get the value of that named property
    1.91 +    @Override
    1.92 +    public Object getMember(String name) {
    1.93 +       switch (name) {
    1.94 +          case "length":
    1.95 +              return buf.capacity();
    1.96 +          case "buf":
    1.97 +              // return a 'function' value for this property
    1.98 +              return new AbstractJSObject() {
    1.99 +                  @Override
   1.100 +                  public Object call(Object thiz, Object... args) {
   1.101 +                      return BufferArray.this.buf;
   1.102 +                  }
   1.103 +
   1.104 +                  // yes, I'm a function !
   1.105 +                  @Override
   1.106 +                  public boolean isFunction() {
   1.107 +                      return true;
   1.108 +                  }
   1.109 +              };
   1.110 +       }
   1.111 +       return null;
   1.112 +    }
   1.113 +}
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/samples/CastExample.java	Wed May 14 11:02:04 2014 -0700
     2.3 @@ -0,0 +1,38 @@
     2.4 +/*
     2.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     2.6 + *
     2.7 + * Redistribution and use in source and binary forms, with or without
     2.8 + * modification, are permitted provided that the following conditions
     2.9 + * are met:
    2.10 + *
    2.11 + *   - Redistributions of source code must retain the above copyright
    2.12 + *     notice, this list of conditions and the following disclaimer.
    2.13 + *
    2.14 + *   - Redistributions in binary form must reproduce the above copyright
    2.15 + *     notice, this list of conditions and the following disclaimer in the
    2.16 + *     documentation and/or other materials provided with the distribution.
    2.17 + *
    2.18 + *   - Neither the name of Oracle nor the names of its
    2.19 + *     contributors may be used to endorse or promote products derived
    2.20 + *     from this software without specific prior written permission.
    2.21 + *
    2.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    2.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    2.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    2.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    2.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    2.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    2.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    2.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    2.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    2.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    2.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    2.33 + */
    2.34 +
    2.35 +// Simple java example with type casts.
    2.36 +// see javacastcounter.js.
    2.37 +
    2.38 +class CastExample {
    2.39 +   public final static int I = (int)23.33;
    2.40 +   public final String str = (String)"hello";
    2.41 +}
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/samples/README	Wed May 14 11:02:04 2014 -0700
     3.3 @@ -0,0 +1,1 @@
     3.4 +Simple Nashorn examples that can be run with "jjs" tool.
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/samples/array_mapreduce.js	Wed May 14 11:02:04 2014 -0700
     4.3 @@ -0,0 +1,78 @@
     4.4 +/*
     4.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     4.6 + * 
     4.7 + * Redistribution and use in source and binary forms, with or without
     4.8 + * modification, are permitted provided that the following conditions
     4.9 + * are met:
    4.10 + * 
    4.11 + *   - Redistributions of source code must retain the above copyright
    4.12 + *     notice, this list of conditions and the following disclaimer.
    4.13 + * 
    4.14 + *   - Redistributions in binary form must reproduce the above copyright
    4.15 + *     notice, this list of conditions and the following disclaimer in the
    4.16 + *     documentation and/or other materials provided with the distribution.
    4.17 + * 
    4.18 + *   - Neither the name of Oracle nor the names of its
    4.19 + *     contributors may be used to endorse or promote products derived
    4.20 + *     from this software without specific prior written permission.
    4.21 + * 
    4.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    4.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    4.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    4.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    4.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    4.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    4.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    4.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    4.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    4.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    4.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    4.33 + */
    4.34 +
    4.35 +// Usage: jjs array_mapreduce.js
    4.36 +
    4.37 +// Many Array.prototype functions such as map, 
    4.38 +// filter, reduce, reduceRight, every, some are generic.
    4.39 +// These functions accept ECMAScript array as well as 
    4.40 +// many array-like objects including java arrays.
    4.41 +// So, you can do map/filter/reduce with Java streams or
    4.42 +// you can also use Array.prototype functions as below.
    4.43 +// See also http://en.wikipedia.org/wiki/MapReduce
    4.44 +
    4.45 +var DoubleArray = Java.type("double[]");
    4.46 +var StringArray = Java.type("java.lang.String[]");
    4.47 +
    4.48 +var map = Array.prototype.map;
    4.49 +var filter = Array.prototype.filter;
    4.50 +var reduce = Array.prototype.reduce;
    4.51 +
    4.52 +var jarr = new StringArray(5);
    4.53 +jarr[0] = "nashorn";
    4.54 +jarr[1] = "ecmascript";
    4.55 +jarr[2] = "javascript";
    4.56 +jarr[3] = "js";
    4.57 +jarr[4] = "scheme";
    4.58 +
    4.59 +// sum of word lengths
    4.60 +print("Sum word length:",
    4.61 +    reduce.call(
    4.62 +        map.call(jarr, function(x) x.length),
    4.63 +        function(x, y) x + y)
    4.64 +);
    4.65 +
    4.66 +// another array example involving numbers
    4.67 +jarr = new DoubleArray(10);
    4.68 +// make random array of numbers
    4.69 +for (var i = 0; i < jarr.length; i++)
    4.70 +    jarr[i] = Math.random();
    4.71 +
    4.72 +var forEach = Array.prototype.forEach;
    4.73 +// print numbers in the array
    4.74 +forEach.call(jarr, function(x) print(x));
    4.75 +
    4.76 +// print sum of squares of the random numbers
    4.77 +print("Square sum:",
    4.78 +    reduce.call(
    4.79 +        map.call(jarr, function(x) x*x), 
    4.80 +        function(x, y) x + y)
    4.81 +);
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/samples/astviewer.js	Wed May 14 11:02:04 2014 -0700
     5.3 @@ -0,0 +1,98 @@
     5.4 +#// Usage: jjs -scripting -fx astviewer.js -- <scriptfile>
     5.5 +
     5.6 +/*
     5.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     5.8 + * 
     5.9 + * Redistribution and use in source and binary forms, with or without
    5.10 + * modification, are permitted provided that the following conditions
    5.11 + * are met:
    5.12 + * 
    5.13 + *   - Redistributions of source code must retain the above copyright
    5.14 + *     notice, this list of conditions and the following disclaimer.
    5.15 + * 
    5.16 + *   - Redistributions in binary form must reproduce the above copyright
    5.17 + *     notice, this list of conditions and the following disclaimer in the
    5.18 + *     documentation and/or other materials provided with the distribution.
    5.19 + * 
    5.20 + *   - Neither the name of Oracle nor the names of its
    5.21 + *     contributors may be used to endorse or promote products derived
    5.22 + *     from this software without specific prior written permission.
    5.23 + * 
    5.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    5.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    5.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    5.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    5.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    5.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    5.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    5.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    5.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    5.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    5.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    5.35 + */
    5.36 +
    5.37 +if (!$OPTIONS._fx) {
    5.38 +    print("Usage: jjs -scripting -fx astviewer.js -- <.js file>");
    5.39 +    exit(1);
    5.40 +}
    5.41 +
    5.42 +// Using JavaFX from Nashorn. See also:
    5.43 +// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
    5.44 +
    5.45 +// This example shows AST of a script file as a JavaFX
    5.46 +// tree view in a window. If no file is specified, AST of
    5.47 +// this script file is shown. This script demonstrates
    5.48 +// 'load' function, JavaFX support by -fx, readFully function
    5.49 +// in scripting mode.
    5.50 +
    5.51 +// JavaFX classes used
    5.52 +var StackPane = Java.type("javafx.scene.layout.StackPane");
    5.53 +var Scene     = Java.type("javafx.scene.Scene");
    5.54 +var TreeItem  = Java.type("javafx.scene.control.TreeItem");
    5.55 +var TreeView  = Java.type("javafx.scene.control.TreeView");
    5.56 +
    5.57 +// Create a javafx TreeItem to view a AST node
    5.58 +function treeItemForASTNode(ast, name) {
    5.59 +    var item = new TreeItem(name);
    5.60 +    for (var prop in ast) {
    5.61 +       var node = ast[prop];
    5.62 +       if (typeof node == 'object') {
    5.63 +           if (node == null) {
    5.64 +               // skip nulls
    5.65 +               continue;
    5.66 +           }
    5.67 +
    5.68 +           if (Array.isArray(node) && node.length == 0) {
    5.69 +               // skip empty arrays
    5.70 +               continue;
    5.71 +           }
    5.72 +
    5.73 +           var subitem = treeItemForASTNode(node, prop);
    5.74 +       } else {
    5.75 +           var subitem = new TreeItem(prop + ": " + node);
    5.76 +       }
    5.77 +       item.children.add(subitem);
    5.78 +    }
    5.79 +    return item;
    5.80 +}
    5.81 +
    5.82 +// do we have a script file passed? if not, use current script
    5.83 +var sourceName = arguments.length == 0? __FILE__ : arguments[0];
    5.84 +
    5.85 +// load parser.js from nashorn resources
    5.86 +load("nashorn:parser.js");
    5.87 +
    5.88 +// read the full content of the file and parse it 
    5.89 +// to get AST of the script specified
    5.90 +var ast = parse(readFully(sourceName));
    5.91 +
    5.92 +// JavaFX start method
    5.93 +function start(stage) {
    5.94 +    stage.title = "AST Viewer";
    5.95 +    var rootItem = treeItemForASTNode(ast, sourceName);
    5.96 +    var tree = new TreeView(rootItem);
    5.97 +    var root = new StackPane();
    5.98 +    root.children.add(tree);
    5.99 +    stage.scene = new Scene(root, 300, 450);
   5.100 +    stage.show();
   5.101 +}
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/samples/barchart_weather.js	Wed May 14 11:02:04 2014 -0700
     6.3 @@ -0,0 +1,116 @@
     6.4 +#// Usage: jjs -fx barchart_weather.js
     6.5 +
     6.6 +/*
     6.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     6.8 + * 
     6.9 + * Redistribution and use in source and binary forms, with or without
    6.10 + * modification, are permitted provided that the following conditions
    6.11 + * are met:
    6.12 + * 
    6.13 + *   - Redistributions of source code must retain the above copyright
    6.14 + *     notice, this list of conditions and the following disclaimer.
    6.15 + * 
    6.16 + *   - Redistributions in binary form must reproduce the above copyright
    6.17 + *     notice, this list of conditions and the following disclaimer in the
    6.18 + *     documentation and/or other materials provided with the distribution.
    6.19 + * 
    6.20 + *   - Neither the name of Oracle nor the names of its
    6.21 + *     contributors may be used to endorse or promote products derived
    6.22 + *     from this software without specific prior written permission.
    6.23 + * 
    6.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    6.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    6.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    6.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    6.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    6.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    6.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    6.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    6.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    6.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    6.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    6.35 + */
    6.36 +
    6.37 +// Example that retrieves weather data from a URL in JSON
    6.38 +// format and draws bar chart using JavaFX
    6.39 +
    6.40 +// -fx check
    6.41 +if (! $OPTIONS._fx) {
    6.42 +    print("Usage: jjs -fx barchart_weather.js");
    6.43 +    exit(1);
    6.44 +}
    6.45 +
    6.46 +// Java classes used
    6.47 +var URL = Java.type("java.net.URL");
    6.48 +var BufferedReader = Java.type("java.io.BufferedReader");
    6.49 +var InputStreamReader = Java.type("java.io.InputStreamReader");
    6.50 +
    6.51 +// function to retrieve text content of the given URL
    6.52 +function readTextFromURL(url) {
    6.53 +    var str = '';
    6.54 +    var u = new URL(url);
    6.55 +    var reader = new BufferedReader(
    6.56 +        new InputStreamReader(u.openStream()));
    6.57 +    try {
    6.58 +        reader.lines().forEach(function(x) str += x);
    6.59 +        return str;
    6.60 +    } finally {
    6.61 +        reader.close();
    6.62 +    }
    6.63 +}
    6.64 +
    6.65 +// change URL for your city here!
    6.66 +var url = "http://api.openweathermap.org/data/2.5/forecast?q=chennai,india&units=metric&mode=json";
    6.67 +
    6.68 +// download JSON document and parse
    6.69 +var json = readTextFromURL(url);
    6.70 +var weather = JSON.parse(json);
    6.71 +
    6.72 +// View JSON of this using site such as http://www.jsoneditoronline.org/ to know
    6.73 +// about the JSON data format used by this site
    6.74 +
    6.75 +// Extracted data from the json object
    6.76 +var temp = weather.list.map(function(x) x.main.temp);
    6.77 +var temp_min = weather.list.map(function(x) x.main.temp_min);
    6.78 +var temp_max = weather.list.map(function(x) x.main.temp_max);
    6.79 +var date = weather.list.map(function(x) x.dt_txt);
    6.80 +
    6.81 +// JavaFX classes used
    6.82 +var Scene = Java.type("javafx.scene.Scene");
    6.83 +var BarChart = Java.type("javafx.scene.chart.BarChart");
    6.84 +var CategoryAxis = Java.type("javafx.scene.chart.CategoryAxis");
    6.85 +var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
    6.86 +var XYChart = Java.type("javafx.scene.chart.XYChart");
    6.87 +
    6.88 +function start(stage) {
    6.89 +    stage.title="Chennai Weather Bar Chart";
    6.90 +    var xAxis = new CategoryAxis();
    6.91 +    xAxis.label = "date/time";
    6.92 +    var yAxis = new NumberAxis();
    6.93 +    yAxis.label = "temp in C";
    6.94 +    var bc = new BarChart(xAxis, yAxis);
    6.95 +
    6.96 +    // 3 bars per datetime item - temp, min temp and max temp
    6.97 +    var s1 = new XYChart.Series();
    6.98 +    s1.name = "temp";
    6.99 +    for (d in date) {
   6.100 +        s1.data.add(new XYChart.Data(date[d], temp[d]));
   6.101 +    }
   6.102 +
   6.103 +    var s2 = new XYChart.Series();
   6.104 +    s2.name = "min temp";
   6.105 +    for (d in date) {
   6.106 +        s2.data.add(new XYChart.Data(date[d], temp_min[d]));
   6.107 +    }
   6.108 +
   6.109 +    var s3 = new XYChart.Series();
   6.110 +    s3.name = "max temp";
   6.111 +    for (d in date) {
   6.112 +        s3.data.add(new XYChart.Data(date[d], temp_max[d]));
   6.113 +    }
   6.114 +
   6.115 +    bc.data.addAll(s1, s2, s3);
   6.116 +
   6.117 +    stage.scene = new Scene(bc, 800, 600);
   6.118 +    stage.show();
   6.119 +}
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/samples/call_lambda.js	Wed May 14 11:02:04 2014 -0700
     7.3 @@ -0,0 +1,45 @@
     7.4 +/*
     7.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     7.6 + * 
     7.7 + * Redistribution and use in source and binary forms, with or without
     7.8 + * modification, are permitted provided that the following conditions
     7.9 + * are met:
    7.10 + * 
    7.11 + *   - Redistributions of source code must retain the above copyright
    7.12 + *     notice, this list of conditions and the following disclaimer.
    7.13 + * 
    7.14 + *   - Redistributions in binary form must reproduce the above copyright
    7.15 + *     notice, this list of conditions and the following disclaimer in the
    7.16 + *     documentation and/or other materials provided with the distribution.
    7.17 + * 
    7.18 + *   - Neither the name of Oracle nor the names of its
    7.19 + *     contributors may be used to endorse or promote products derived
    7.20 + *     from this software without specific prior written permission.
    7.21 + * 
    7.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    7.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    7.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    7.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    7.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    7.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    7.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    7.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    7.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    7.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    7.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    7.33 + */
    7.34 +
    7.35 +// nashorn allows you treat every Java8 lambda as a function
    7.36 +
    7.37 +var JFunction = Java.type("java.util.function.Function");
    7.38 +var obj = new JFunction() {
    7.39 +    apply: function(x) {
    7.40 +        print(x + ", lambda");
    7.41 +    }
    7.42 +};
    7.43 +
    7.44 +// prints 'function'
    7.45 +print(typeof obj);
    7.46 +
    7.47 +// call it!
    7.48 +obj("hello");
     8.1 --- a/samples/counters.js	Tue May 13 23:18:50 2014 -0700
     8.2 +++ b/samples/counters.js	Wed May 14 11:02:04 2014 -0700
     8.3 @@ -1,5 +1,5 @@
     8.4  /*
     8.5 - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
     8.6 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     8.7   * 
     8.8   * Redistribution and use in source and binary forms, with or without
     8.9   * modification, are permitted provided that the following conditions
    8.10 @@ -33,7 +33,11 @@
    8.11   * This file can be run along with any script you want to run
    8.12   * to print aggregate stat counters from nashorn.
    8.13   *
    8.14 - * Usage:  jjs <your-file.js> counters.js
    8.15 + * Usage:  jjs -J-Dnashorn.debug <your-file.js> counters.js
    8.16   */
    8.17  
    8.18 -Debug.dumpCounters();
    8.19 +if (java.lang.System.getProperty("nashorn.debug") == null) {
    8.20 +    print("Usage: jjs -J-Dnashorn.debug <your-file.js> counters.js");
    8.21 +} else {
    8.22 +    Debug.dumpCounters();
    8.23 +}
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/samples/dirname.js	Wed May 14 11:02:04 2014 -0700
     9.3 @@ -0,0 +1,36 @@
     9.4 +/*
     9.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
     9.6 + * 
     9.7 + * Redistribution and use in source and binary forms, with or without
     9.8 + * modification, are permitted provided that the following conditions
     9.9 + * are met:
    9.10 + * 
    9.11 + *   - Redistributions of source code must retain the above copyright
    9.12 + *     notice, this list of conditions and the following disclaimer.
    9.13 + * 
    9.14 + *   - Redistributions in binary form must reproduce the above copyright
    9.15 + *     notice, this list of conditions and the following disclaimer in the
    9.16 + *     documentation and/or other materials provided with the distribution.
    9.17 + * 
    9.18 + *   - Neither the name of Oracle nor the names of its
    9.19 + *     contributors may be used to endorse or promote products derived
    9.20 + *     from this software without specific prior written permission.
    9.21 + * 
    9.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    9.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    9.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    9.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    9.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    9.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    9.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    9.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    9.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    9.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    9.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    9.33 + */
    9.34 +
    9.35 +// __DIR__ variable is equivalent of `dirname $0` in
    9.36 +// shell scripts - expands to the directory where
    9.37 +// the current script is located.
    9.38 +
    9.39 +print("This script is in the directory: " + __DIR__);
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/samples/disassemble.js	Wed May 14 11:02:04 2014 -0700
    10.3 @@ -0,0 +1,75 @@
    10.4 +/*
    10.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    10.6 + * 
    10.7 + * Redistribution and use in source and binary forms, with or without
    10.8 + * modification, are permitted provided that the following conditions
    10.9 + * are met:
   10.10 + * 
   10.11 + *   - Redistributions of source code must retain the above copyright
   10.12 + *     notice, this list of conditions and the following disclaimer.
   10.13 + * 
   10.14 + *   - Redistributions in binary form must reproduce the above copyright
   10.15 + *     notice, this list of conditions and the following disclaimer in the
   10.16 + *     documentation and/or other materials provided with the distribution.
   10.17 + * 
   10.18 + *   - Neither the name of Oracle nor the names of its
   10.19 + *     contributors may be used to endorse or promote products derived
   10.20 + *     from this software without specific prior written permission.
   10.21 + * 
   10.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   10.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   10.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   10.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   10.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   10.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   10.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   10.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   10.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   10.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   10.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   10.33 + */
   10.34 +
   10.35 +// Usage: jjs disassemble.js -- <.class-file-path>
   10.36 +
   10.37 +// Simple .class disassembler that uses bundled ObjectWeb ASM
   10.38 +// classes in jdk8. WARNING: Bundled ObjectWeb ASM classes are
   10.39 +// not part of official jdk8 API. It can be changed/removed 
   10.40 +// without notice. So, this script is brittle by design!
   10.41 +
   10.42 +// This example demonstrates passing arguments to script
   10.43 +// from jjs command line, nio and ASM usage.
   10.44 +
   10.45 +// classes used
   10.46 +var FileSystems = Java.type("java.nio.file.FileSystems");
   10.47 +var Files = Java.type("java.nio.file.Files");
   10.48 +var System = Java.type("java.lang.System");
   10.49 +var PrintWriter = Java.type("java.io.PrintWriter");
   10.50 +
   10.51 +// WARNING: uses non-API classes of jdk8!
   10.52 +var ClassReader = Java.type("jdk.internal.org.objectweb.asm.ClassReader");
   10.53 +var TraceClassVisitor = Java.type("jdk.internal.org.objectweb.asm.util.TraceClassVisitor");
   10.54 +
   10.55 +// convert file name to Path instance
   10.56 +function path(file) {
   10.57 +    return FileSystems.default.getPath(file);
   10.58 +}
   10.59 +
   10.60 +// read all file content as a byte[]
   10.61 +function readAllBytes(file) {
   10.62 +    return Files.readAllBytes(path(file));
   10.63 +}
   10.64 +
   10.65 +// disassemble .class byte[] and prints output to stdout
   10.66 +function disassemble(bytecode) {
   10.67 +    var pw = new PrintWriter(System.out);
   10.68 +    new ClassReader(bytecode).accept(new TraceClassVisitor(pw), 0);
   10.69 +}
   10.70 +
   10.71 +// check for command line arg (for .class file name)
   10.72 +if (arguments.length == 0 || !arguments[0].endsWith('.class')) {
   10.73 +    print("Usage: jjs disassemble -- <.class file>");
   10.74 +    exit(1);
   10.75 +}
   10.76 +
   10.77 +// disassemble the given .class file
   10.78 +disassemble(readAllBytes(arguments[0]));
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/samples/engine/README	Wed May 14 11:02:04 2014 -0700
    11.3 @@ -0,0 +1,1 @@
    11.4 +Using javax.script engine API of nashorn from script!
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/samples/engine/accessvar.js	Wed May 14 11:02:04 2014 -0700
    12.3 @@ -0,0 +1,44 @@
    12.4 +/*
    12.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    12.6 + * 
    12.7 + * Redistribution and use in source and binary forms, with or without
    12.8 + * modification, are permitted provided that the following conditions
    12.9 + * are met:
   12.10 + * 
   12.11 + *   - Redistributions of source code must retain the above copyright
   12.12 + *     notice, this list of conditions and the following disclaimer.
   12.13 + * 
   12.14 + *   - Redistributions in binary form must reproduce the above copyright
   12.15 + *     notice, this list of conditions and the following disclaimer in the
   12.16 + *     documentation and/or other materials provided with the distribution.
   12.17 + * 
   12.18 + *   - Neither the name of Oracle nor the names of its
   12.19 + *     contributors may be used to endorse or promote products derived
   12.20 + *     from this software without specific prior written permission.
   12.21 + * 
   12.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   12.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   12.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   12.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   12.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   12.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   12.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   12.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   12.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   12.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   12.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   12.33 + */
   12.34 +
   12.35 +// Simple example showing global variable access from caller
   12.36 +
   12.37 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   12.38 +// create manager
   12.39 +var manager = new ScriptEngineManager();
   12.40 +// create engine
   12.41 +var engine = manager.getEngineByName("js");
   12.42 +
   12.43 +// eval code!
   12.44 +engine.eval("x = 'hello'");
   12.45 +
   12.46 +// access global var from engine
   12.47 +print(engine.get('x'));
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/samples/engine/callfunc.js	Wed May 14 11:02:04 2014 -0700
    13.3 @@ -0,0 +1,48 @@
    13.4 +/*
    13.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    13.6 + * 
    13.7 + * Redistribution and use in source and binary forms, with or without
    13.8 + * modification, are permitted provided that the following conditions
    13.9 + * are met:
   13.10 + * 
   13.11 + *   - Redistributions of source code must retain the above copyright
   13.12 + *     notice, this list of conditions and the following disclaimer.
   13.13 + * 
   13.14 + *   - Redistributions in binary form must reproduce the above copyright
   13.15 + *     notice, this list of conditions and the following disclaimer in the
   13.16 + *     documentation and/or other materials provided with the distribution.
   13.17 + * 
   13.18 + *   - Neither the name of Oracle nor the names of its
   13.19 + *     contributors may be used to endorse or promote products derived
   13.20 + *     from this software without specific prior written permission.
   13.21 + * 
   13.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   13.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   13.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   13.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   13.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   13.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   13.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   13.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   13.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   13.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   13.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   13.33 + */
   13.34 +
   13.35 +// simple example showing how to call a global script 
   13.36 +// function from caller
   13.37 +
   13.38 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   13.39 +// create manager
   13.40 +var manager = new ScriptEngineManager();
   13.41 +// create engine
   13.42 +var engine = manager.getEngineByName("js");
   13.43 +
   13.44 +// eval code!
   13.45 +engine.eval("function func(name) { print('I am func, hello ' + name) }");
   13.46 +
   13.47 +// invoke functions, methods of code evaluated by engine
   13.48 +// from javax.script.Invocable interface. But, hey, 
   13.49 +// calling code is JavaScript and don't worry about types :)
   13.50 +
   13.51 +engine.invokeFunction("func", "Nashorn");
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/samples/engine/callmethod.js	Wed May 14 11:02:04 2014 -0700
    14.3 @@ -0,0 +1,64 @@
    14.4 +#// Usage: jjs -scripting callmethod.js
    14.5 +
    14.6 +/*
    14.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    14.8 + * 
    14.9 + * Redistribution and use in source and binary forms, with or without
   14.10 + * modification, are permitted provided that the following conditions
   14.11 + * are met:
   14.12 + * 
   14.13 + *   - Redistributions of source code must retain the above copyright
   14.14 + *     notice, this list of conditions and the following disclaimer.
   14.15 + * 
   14.16 + *   - Redistributions in binary form must reproduce the above copyright
   14.17 + *     notice, this list of conditions and the following disclaimer in the
   14.18 + *     documentation and/or other materials provided with the distribution.
   14.19 + * 
   14.20 + *   - Neither the name of Oracle nor the names of its
   14.21 + *     contributors may be used to endorse or promote products derived
   14.22 + *     from this software without specific prior written permission.
   14.23 + * 
   14.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   14.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   14.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   14.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   14.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   14.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   14.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   14.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   14.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   14.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   14.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   14.35 + */
   14.36 +
   14.37 +// simple example demonstrating calling a script object
   14.38 +// method from script engine user code
   14.39 +
   14.40 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   14.41 +// create manager
   14.42 +var manager = new ScriptEngineManager();
   14.43 +// create engine
   14.44 +var engine = manager.getEngineByName("js");
   14.45 +
   14.46 +// eval code - too many script escapes?
   14.47 +// use heredoc !
   14.48 +engine.eval(<<CODE
   14.49 +    var obj = {
   14.50 +        func: function() {
   14.51 +            print("I am func of " + this);
   14.52 +        },
   14.53 +
   14.54 +        toString: function() {
   14.55 +            return "Object 'obj'";
   14.56 +        }
   14.57 +   };
   14.58 +CODE);
   14.59 +
   14.60 +// invoke methods of an object in script world
   14.61 +// from javax.script.Invocable interface. But, hey, 
   14.62 +// calling code is JavaScript and don't worry about types :)
   14.63 +
   14.64 +// get that script object on which to call a method
   14.65 +var scriptObj = engine.get("obj");
   14.66 +// call 'func' method on object 'obj'
   14.67 +engine.invokeMethod(scriptObj, "func");
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/samples/engine/exposevar.js	Wed May 14 11:02:04 2014 -0700
    15.3 @@ -0,0 +1,44 @@
    15.4 +/*
    15.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    15.6 + * 
    15.7 + * Redistribution and use in source and binary forms, with or without
    15.8 + * modification, are permitted provided that the following conditions
    15.9 + * are met:
   15.10 + * 
   15.11 + *   - Redistributions of source code must retain the above copyright
   15.12 + *     notice, this list of conditions and the following disclaimer.
   15.13 + * 
   15.14 + *   - Redistributions in binary form must reproduce the above copyright
   15.15 + *     notice, this list of conditions and the following disclaimer in the
   15.16 + *     documentation and/or other materials provided with the distribution.
   15.17 + * 
   15.18 + *   - Neither the name of Oracle nor the names of its
   15.19 + *     contributors may be used to endorse or promote products derived
   15.20 + *     from this software without specific prior written permission.
   15.21 + * 
   15.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   15.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   15.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   15.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   15.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   15.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   15.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   15.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   15.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   15.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   15.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   15.33 + */
   15.34 +
   15.35 +// Example showing how to expose a script global var from caller
   15.36 +
   15.37 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   15.38 +// create manager
   15.39 +var manager = new ScriptEngineManager();
   15.40 +// create engine
   15.41 +var engine = manager.getEngineByName("js");
   15.42 +
   15.43 +// expose variable to engine
   15.44 +engine.put("name", "Nashorn");
   15.45 +
   15.46 +// access it from script
   15.47 +engine.eval("print('Hello, ' + name)");
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/samples/engine/foreignobject.js	Wed May 14 11:02:04 2014 -0700
    16.3 @@ -0,0 +1,71 @@
    16.4 +#// Usage: jjs -scripting foreignobject.js
    16.5 +
    16.6 +/*
    16.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    16.8 + * 
    16.9 + * Redistribution and use in source and binary forms, with or without
   16.10 + * modification, are permitted provided that the following conditions
   16.11 + * are met:
   16.12 + * 
   16.13 + *   - Redistributions of source code must retain the above copyright
   16.14 + *     notice, this list of conditions and the following disclaimer.
   16.15 + * 
   16.16 + *   - Redistributions in binary form must reproduce the above copyright
   16.17 + *     notice, this list of conditions and the following disclaimer in the
   16.18 + *     documentation and/or other materials provided with the distribution.
   16.19 + * 
   16.20 + *   - Neither the name of Oracle nor the names of its
   16.21 + *     contributors may be used to endorse or promote products derived
   16.22 + *     from this software without specific prior written permission.
   16.23 + * 
   16.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   16.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   16.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   16.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   16.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   16.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   16.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   16.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   16.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   16.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   16.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   16.35 + */
   16.36 +
   16.37 +// cross nashorn engine scripting
   16.38 +// access script objects from other engines in natural syntax
   16.39 +
   16.40 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   16.41 +// create manager
   16.42 +var manager = new ScriptEngineManager();
   16.43 +// create engine
   16.44 +var engine = manager.getEngineByName("js");
   16.45 +
   16.46 +// eval code!
   16.47 +engine.eval(<<CODE
   16.48 +    var obj = {
   16.49 +        foo: 42,
   16.50 +        func: function() {
   16.51 +            print("func: " + this.foo);
   16.52 +        }
   16.53 +    };
   16.54 +CODE);
   16.55 +
   16.56 +// Nashorn engine returns script objects as instance of
   16.57 +// the class jdk.nashorn.api.scripting.ScriptObjectMirror
   16.58 +// But nashorn's dynalink linker can treat these objects
   16.59 +// specially to support natural script syntax to access..
   16.60 +// In Java code, you need to use ScriptObjectMirror's 
   16.61 +// methods though. Once again, script world is simpler :-)
   16.62 +
   16.63 +var foreignObj = engine.get("obj");
   16.64 +// access properties, functions of it
   16.65 +// with natural syntax
   16.66 +print(foreignObj.foo);
   16.67 +foreignObj.func();
   16.68 +print(typeof foreignObj.func);
   16.69 +
   16.70 +// access engine's global
   16.71 +var foreignGlobal = engine.eval("this");
   16.72 +// create objects in engine's world from here!
   16.73 +print(new foreignGlobal.Object());
   16.74 +print(new foreignGlobal.Date());
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/samples/engine/hello.js	Wed May 14 11:02:04 2014 -0700
    17.3 @@ -0,0 +1,41 @@
    17.4 +/*
    17.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    17.6 + * 
    17.7 + * Redistribution and use in source and binary forms, with or without
    17.8 + * modification, are permitted provided that the following conditions
    17.9 + * are met:
   17.10 + * 
   17.11 + *   - Redistributions of source code must retain the above copyright
   17.12 + *     notice, this list of conditions and the following disclaimer.
   17.13 + * 
   17.14 + *   - Redistributions in binary form must reproduce the above copyright
   17.15 + *     notice, this list of conditions and the following disclaimer in the
   17.16 + *     documentation and/or other materials provided with the distribution.
   17.17 + * 
   17.18 + *   - Neither the name of Oracle nor the names of its
   17.19 + *     contributors may be used to endorse or promote products derived
   17.20 + *     from this software without specific prior written permission.
   17.21 + * 
   17.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   17.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   17.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   17.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   17.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   17.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   17.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   17.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   17.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   17.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   17.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   17.33 + */
   17.34 +
   17.35 +// Simple hello world example showing create engine
   17.36 +// and eval simple script
   17.37 +
   17.38 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   17.39 +// create manager
   17.40 +var manager = new ScriptEngineManager();
   17.41 +// create engine
   17.42 +var engine = manager.getEngineByName("js");
   17.43 +// eval code!
   17.44 +engine.eval("print('hello world')");
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/samples/engine/interface.js	Wed May 14 11:02:04 2014 -0700
    18.3 @@ -0,0 +1,60 @@
    18.4 +#// Usage: jjs -scripting interface.js
    18.5 +
    18.6 +/*
    18.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    18.8 + * 
    18.9 + * Redistribution and use in source and binary forms, with or without
   18.10 + * modification, are permitted provided that the following conditions
   18.11 + * are met:
   18.12 + * 
   18.13 + *   - Redistributions of source code must retain the above copyright
   18.14 + *     notice, this list of conditions and the following disclaimer.
   18.15 + * 
   18.16 + *   - Redistributions in binary form must reproduce the above copyright
   18.17 + *     notice, this list of conditions and the following disclaimer in the
   18.18 + *     documentation and/or other materials provided with the distribution.
   18.19 + * 
   18.20 + *   - Neither the name of Oracle nor the names of its
   18.21 + *     contributors may be used to endorse or promote products derived
   18.22 + *     from this software without specific prior written permission.
   18.23 + * 
   18.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   18.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   18.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   18.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   18.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   18.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   18.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   18.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   18.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   18.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   18.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   18.35 + */
   18.36 +
   18.37 +// Example demonstrating how to implement a Java interface
   18.38 +// whose methods are backed by global script functions
   18.39 +
   18.40 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   18.41 +// create manager
   18.42 +var manager = new ScriptEngineManager();
   18.43 +// create engine
   18.44 +var engine = manager.getEngineByName("js");
   18.45 +
   18.46 +// eval code - too many script escapes?
   18.47 +// use heredoc !
   18.48 +engine.eval(<<CODE
   18.49 +function run() {
   18.50 +    print("run global function called");
   18.51 +}
   18.52 +CODE);
   18.53 +
   18.54 +// create Java interface object whose methods are
   18.55 +// implemented by script functions. This is from
   18.56 +// javax.script.Invocable. But we are in JS world, 
   18.57 +// don't worry about types :)
   18.58 +
   18.59 +var Runnable = Java.type("java.lang.Runnable");
   18.60 +var r = engine.getInterface(Runnable.class);
   18.61 +print(r.class);
   18.62 +
   18.63 +r.run();
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/samples/engine/interface2.js	Wed May 14 11:02:04 2014 -0700
    19.3 @@ -0,0 +1,63 @@
    19.4 +#// Usage: jjs -scripting interface2.js
    19.5 +
    19.6 +/*
    19.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    19.8 + * 
    19.9 + * Redistribution and use in source and binary forms, with or without
   19.10 + * modification, are permitted provided that the following conditions
   19.11 + * are met:
   19.12 + * 
   19.13 + *   - Redistributions of source code must retain the above copyright
   19.14 + *     notice, this list of conditions and the following disclaimer.
   19.15 + * 
   19.16 + *   - Redistributions in binary form must reproduce the above copyright
   19.17 + *     notice, this list of conditions and the following disclaimer in the
   19.18 + *     documentation and/or other materials provided with the distribution.
   19.19 + * 
   19.20 + *   - Neither the name of Oracle nor the names of its
   19.21 + *     contributors may be used to endorse or promote products derived
   19.22 + *     from this software without specific prior written permission.
   19.23 + * 
   19.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   19.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   19.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   19.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   19.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   19.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   19.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   19.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   19.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   19.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   19.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   19.35 + */
   19.36 +
   19.37 +// Simple example demonstrating how to implement java interface
   19.38 +// whose methods are backed by script methods of a script object
   19.39 +
   19.40 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   19.41 +// create manager
   19.42 +var manager = new ScriptEngineManager();
   19.43 +// create engine
   19.44 +var engine = manager.getEngineByName("js");
   19.45 +
   19.46 +// eval code - too many script escapes?
   19.47 +// use heredoc !
   19.48 +engine.eval(<<CODE
   19.49 +  var obj = {
   19.50 +    run: function() {
   19.51 +        print("I am run method of 'obj'");
   19.52 +    }
   19.53 +  };
   19.54 +CODE);
   19.55 +
   19.56 +// create Java interface object whose methods are
   19.57 +// implemented by script methods of a script object
   19.58 +// This is from javax.script.Invocable. But we are
   19.59 +// in JS world, don't worry about types :)
   19.60 +
   19.61 +var Runnable = Java.type("java.lang.Runnable");
   19.62 +
   19.63 +var scriptObj = engine.get("obj");
   19.64 +var r = engine.getInterface(scriptObj, Runnable.class);
   19.65 +print(r.class);
   19.66 +r.run();
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/samples/engine/lambda_as_func.js	Wed May 14 11:02:04 2014 -0700
    20.3 @@ -0,0 +1,49 @@
    20.4 +/*
    20.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    20.6 + * 
    20.7 + * Redistribution and use in source and binary forms, with or without
    20.8 + * modification, are permitted provided that the following conditions
    20.9 + * are met:
   20.10 + * 
   20.11 + *   - Redistributions of source code must retain the above copyright
   20.12 + *     notice, this list of conditions and the following disclaimer.
   20.13 + * 
   20.14 + *   - Redistributions in binary form must reproduce the above copyright
   20.15 + *     notice, this list of conditions and the following disclaimer in the
   20.16 + *     documentation and/or other materials provided with the distribution.
   20.17 + * 
   20.18 + *   - Neither the name of Oracle nor the names of its
   20.19 + *     contributors may be used to endorse or promote products derived
   20.20 + *     from this software without specific prior written permission.
   20.21 + * 
   20.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   20.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   20.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   20.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   20.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   20.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   20.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   20.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   20.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   20.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   20.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   20.33 + */
   20.34 +
   20.35 +// Simple example demonstrating how to expose 'function's
   20.36 +// from embedding code. Any lambda object exposed to engine
   20.37 +// can be called as 'function' in script.
   20.38 +
   20.39 +var ScriptEngineManager = Java.type("javax.script.ScriptEngineManager");
   20.40 +// create manager
   20.41 +var manager = new ScriptEngineManager();
   20.42 +// create engine
   20.43 +var engine = manager.getEngineByName("js");
   20.44 +
   20.45 +// Any lambda (@FunctionalInterface annotated type) object can be
   20.46 +// be exposed from script embedding code. Script can call
   20.47 +// it as a function
   20.48 +engine.put("upper", new java.util.function.Function() {
   20.49 +     apply: function(x) x.toUpperCase()
   20.50 +});
   20.51 +
   20.52 +print(engine.eval("upper('hello')"));
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/samples/env.js	Wed May 14 11:02:04 2014 -0700
    21.3 @@ -0,0 +1,43 @@
    21.4 +#// Usage: jjs -scripting env.js
    21.5 +
    21.6 +/*
    21.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    21.8 + * 
    21.9 + * Redistribution and use in source and binary forms, with or without
   21.10 + * modification, are permitted provided that the following conditions
   21.11 + * are met:
   21.12 + * 
   21.13 + *   - Redistributions of source code must retain the above copyright
   21.14 + *     notice, this list of conditions and the following disclaimer.
   21.15 + * 
   21.16 + *   - Redistributions in binary form must reproduce the above copyright
   21.17 + *     notice, this list of conditions and the following disclaimer in the
   21.18 + *     documentation and/or other materials provided with the distribution.
   21.19 + * 
   21.20 + *   - Neither the name of Oracle nor the names of its
   21.21 + *     contributors may be used to endorse or promote products derived
   21.22 + *     from this software without specific prior written permission.
   21.23 + * 
   21.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   21.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   21.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   21.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   21.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   21.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   21.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   21.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   21.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   21.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   21.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   21.35 + */
   21.36 +
   21.37 +// In nashorn -scripting mode, 
   21.38 +// "$ENV" object exposes process 
   21.39 +// environment variables
   21.40 +
   21.41 +print($ENV.PATH);
   21.42 +print($ENV.JAVA_HOME);
   21.43 +
   21.44 +for (i in $ENV) {
   21.45 +   print(i, "->", $ENV[i]);
   21.46 +}
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/samples/expression_closure.js	Wed May 14 11:02:04 2014 -0700
    22.3 @@ -0,0 +1,41 @@
    22.4 +/*
    22.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    22.6 + * 
    22.7 + * Redistribution and use in source and binary forms, with or without
    22.8 + * modification, are permitted provided that the following conditions
    22.9 + * are met:
   22.10 + * 
   22.11 + *   - Redistributions of source code must retain the above copyright
   22.12 + *     notice, this list of conditions and the following disclaimer.
   22.13 + * 
   22.14 + *   - Redistributions in binary form must reproduce the above copyright
   22.15 + *     notice, this list of conditions and the following disclaimer in the
   22.16 + *     documentation and/or other materials provided with the distribution.
   22.17 + * 
   22.18 + *   - Neither the name of Oracle nor the names of its
   22.19 + *     contributors may be used to endorse or promote products derived
   22.20 + *     from this software without specific prior written permission.
   22.21 + * 
   22.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   22.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   22.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   22.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   22.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   22.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   22.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   22.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   22.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   22.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   22.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   22.33 + */
   22.34 +
   22.35 +// nashorn supports expression closures extension of
   22.36 +// Mozilla JavaScript 1.8. See also
   22.37 +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
   22.38 +
   22.39 +// leave {, } and 'return' keyword
   22.40 +
   22.41 +function sqr(x) x*x;
   22.42 +
   22.43 +// prints 289 (= 17*17)
   22.44 +print(sqr(17));
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/samples/fileline.js	Wed May 14 11:02:04 2014 -0700
    23.3 @@ -0,0 +1,37 @@
    23.4 +/*
    23.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    23.6 + * 
    23.7 + * Redistribution and use in source and binary forms, with or without
    23.8 + * modification, are permitted provided that the following conditions
    23.9 + * are met:
   23.10 + * 
   23.11 + *   - Redistributions of source code must retain the above copyright
   23.12 + *     notice, this list of conditions and the following disclaimer.
   23.13 + * 
   23.14 + *   - Redistributions in binary form must reproduce the above copyright
   23.15 + *     notice, this list of conditions and the following disclaimer in the
   23.16 + *     documentation and/or other materials provided with the distribution.
   23.17 + * 
   23.18 + *   - Neither the name of Oracle nor the names of its
   23.19 + *     contributors may be used to endorse or promote products derived
   23.20 + *     from this software without specific prior written permission.
   23.21 + * 
   23.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   23.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   23.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   23.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   23.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   23.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   23.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   23.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   23.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   23.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   23.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   23.33 + */
   23.34 +
   23.35 +// nashorn supports pseudo global variables __FILE__
   23.36 +// and __LINE__ that expands to currently executed
   23.37 +// script file name and current script line number
   23.38 +
   23.39 +// prints current file and line number
   23.40 +print("executing " + __FILE__ + " @ " + __LINE__);
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/samples/fizzbuzz.js	Wed May 14 11:02:04 2014 -0700
    24.3 @@ -0,0 +1,48 @@
    24.4 +/*
    24.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    24.6 + * 
    24.7 + * Redistribution and use in source and binary forms, with or without
    24.8 + * modification, are permitted provided that the following conditions
    24.9 + * are met:
   24.10 + * 
   24.11 + *   - Redistributions of source code must retain the above copyright
   24.12 + *     notice, this list of conditions and the following disclaimer.
   24.13 + * 
   24.14 + *   - Redistributions in binary form must reproduce the above copyright
   24.15 + *     notice, this list of conditions and the following disclaimer in the
   24.16 + *     documentation and/or other materials provided with the distribution.
   24.17 + * 
   24.18 + *   - Neither the name of Oracle nor the names of its
   24.19 + *     contributors may be used to endorse or promote products derived
   24.20 + *     from this software without specific prior written permission.
   24.21 + * 
   24.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   24.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   24.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   24.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   24.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   24.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   24.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   24.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   24.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   24.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   24.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   24.33 + */
   24.34 +
   24.35 +// What is FizzBuzz? http://c2.com/cgi/wiki?FizzBuzzTest
   24.36 +
   24.37 +// Yet another FizzBuzz impl. using Java 8 lambda and stream
   24.38 +// but using Nashorn. This is ECMAScript port of @stuartmarks'
   24.39 +// Java implementation
   24.40 +
   24.41 +var IntStream = Java.type("java.util.stream.IntStream");
   24.42 +
   24.43 +function ifmod(m, r, f) {
   24.44 +    return function(i) { return i % m == 0? r : f(i); }
   24.45 +}
   24.46 +
   24.47 +// pass script function for lambda
   24.48 +IntStream.rangeClosed(1, 100).
   24.49 +   mapToObj(
   24.50 +      ifmod(15, "FizzBuzz", ifmod(5, "Buzz", ifmod(3, "Fizz", String))))
   24.51 +      .forEach(print);
    25.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.2 +++ b/samples/for_each.js	Wed May 14 11:02:04 2014 -0700
    25.3 @@ -0,0 +1,66 @@
    25.4 +/*
    25.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    25.6 + * 
    25.7 + * Redistribution and use in source and binary forms, with or without
    25.8 + * modification, are permitted provided that the following conditions
    25.9 + * are met:
   25.10 + * 
   25.11 + *   - Redistributions of source code must retain the above copyright
   25.12 + *     notice, this list of conditions and the following disclaimer.
   25.13 + * 
   25.14 + *   - Redistributions in binary form must reproduce the above copyright
   25.15 + *     notice, this list of conditions and the following disclaimer in the
   25.16 + *     documentation and/or other materials provided with the distribution.
   25.17 + * 
   25.18 + *   - Neither the name of Oracle nor the names of its
   25.19 + *     contributors may be used to endorse or promote products derived
   25.20 + *     from this software without specific prior written permission.
   25.21 + * 
   25.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   25.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   25.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   25.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   25.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   25.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   25.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   25.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   25.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   25.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   25.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   25.33 + */
   25.34 +
   25.35 +// nashorn supports for..each extension supported
   25.36 +// by Mozilla. See also
   25.37 +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in
   25.38 +
   25.39 +var strs = [ "hello", "world" ];
   25.40 +for each (str in strs)
   25.41 +    print(str);
   25.42 +
   25.43 +// create a java int[] object
   25.44 +var JArray = Java.type("int[]");
   25.45 +var arr = new JArray(10);
   25.46 +
   25.47 +// store squares as values
   25.48 +for (i in arr) 
   25.49 +    arr[i] = i*i;
   25.50 +
   25.51 +// for .. each on java arrays
   25.52 +print("squares");
   25.53 +for each (i in arr)
   25.54 +    print(i);
   25.55 +
   25.56 +var System = Java.type("java.lang.System");
   25.57 +
   25.58 +// for..each on java Iterables
   25.59 +// print System properties as name = value pairs
   25.60 +print("System properties");
   25.61 +for each (p in System.properties.entrySet()) {
   25.62 +    print(p.key, "=", p.value);
   25.63 +} 
   25.64 +
   25.65 +// print process environment vars as name = value pairs
   25.66 +print("Process environment");
   25.67 +for each (e in System.env.entrySet()) {
   25.68 +    print(e.key, "=", e.value);
   25.69 +}
    26.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.2 +++ b/samples/gaussian_random.js	Wed May 14 11:02:04 2014 -0700
    26.3 @@ -0,0 +1,46 @@
    26.4 +/*
    26.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    26.6 + * 
    26.7 + * Redistribution and use in source and binary forms, with or without
    26.8 + * modification, are permitted provided that the following conditions
    26.9 + * are met:
   26.10 + * 
   26.11 + *   - Redistributions of source code must retain the above copyright
   26.12 + *     notice, this list of conditions and the following disclaimer.
   26.13 + * 
   26.14 + *   - Redistributions in binary form must reproduce the above copyright
   26.15 + *     notice, this list of conditions and the following disclaimer in the
   26.16 + *     documentation and/or other materials provided with the distribution.
   26.17 + * 
   26.18 + *   - Neither the name of Oracle nor the names of its
   26.19 + *     contributors may be used to endorse or promote products derived
   26.20 + *     from this software without specific prior written permission.
   26.21 + * 
   26.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   26.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   26.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   26.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   26.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   26.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   26.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   26.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   26.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   26.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   26.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   26.33 + */
   26.34 +
   26.35 +// print 100 Guassian distributed numbers
   26.36 +
   26.37 +var Random = Java.type("java.util.Random");
   26.38 +var DoubleStream = Java.type("java.util.stream.DoubleStream");
   26.39 +
   26.40 +var r = new Random();
   26.41 +
   26.42 +// expression closure (see expression_closure.js as well)
   26.43 +// passed as lambda double generator. "print" passed as 
   26.44 +// double consumer lambda to 'forEach' method.
   26.45 +
   26.46 +DoubleStream
   26.47 +    .generate(function() r.nextGaussian())
   26.48 +    .limit(100)
   26.49 +    .forEach(print);
    27.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.2 +++ b/samples/gaussian_random_bind.js	Wed May 14 11:02:04 2014 -0700
    27.3 @@ -0,0 +1,48 @@
    27.4 +/*
    27.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    27.6 + * 
    27.7 + * Redistribution and use in source and binary forms, with or without
    27.8 + * modification, are permitted provided that the following conditions
    27.9 + * are met:
   27.10 + * 
   27.11 + *   - Redistributions of source code must retain the above copyright
   27.12 + *     notice, this list of conditions and the following disclaimer.
   27.13 + * 
   27.14 + *   - Redistributions in binary form must reproduce the above copyright
   27.15 + *     notice, this list of conditions and the following disclaimer in the
   27.16 + *     documentation and/or other materials provided with the distribution.
   27.17 + * 
   27.18 + *   - Neither the name of Oracle nor the names of its
   27.19 + *     contributors may be used to endorse or promote products derived
   27.20 + *     from this software without specific prior written permission.
   27.21 + * 
   27.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   27.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   27.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   27.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   27.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   27.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   27.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   27.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   27.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   27.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   27.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   27.33 + */
   27.34 +
   27.35 +// print 100 Guassian distributed numbers
   27.36 +
   27.37 +var Random = Java.type("java.util.Random");
   27.38 +var DoubleStream = Java.type("java.util.stream.DoubleStream");
   27.39 +
   27.40 +// function as lambda double generator. "print" passed as 
   27.41 +// double consumer lambda to 'forEach' method.
   27.42 +// Function.prototype.bind used to attach 'state' for the
   27.43 +// generator function.
   27.44 +
   27.45 +DoubleStream
   27.46 +    .generate(
   27.47 +         function(r) {
   27.48 +             return r.nextGaussian()
   27.49 +         }.bind(this, new Random()))
   27.50 +    .limit(100)
   27.51 +    .forEach(print);
    28.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.2 +++ b/samples/gutenberg.js	Wed May 14 11:02:04 2014 -0700
    28.3 @@ -0,0 +1,142 @@
    28.4 +#// Usage: jjs -scripting gutenberg.js
    28.5 +
    28.6 +/*
    28.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    28.8 + * 
    28.9 + * Redistribution and use in source and binary forms, with or without
   28.10 + * modification, are permitted provided that the following conditions
   28.11 + * are met:
   28.12 + * 
   28.13 + *   - Redistributions of source code must retain the above copyright
   28.14 + *     notice, this list of conditions and the following disclaimer.
   28.15 + * 
   28.16 + *   - Redistributions in binary form must reproduce the above copyright
   28.17 + *     notice, this list of conditions and the following disclaimer in the
   28.18 + *     documentation and/or other materials provided with the distribution.
   28.19 + * 
   28.20 + *   - Neither the name of Oracle nor the names of its
   28.21 + *     contributors may be used to endorse or promote products derived
   28.22 + *     from this software without specific prior written permission.
   28.23 + * 
   28.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   28.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   28.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   28.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   28.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   28.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   28.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   28.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   28.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   28.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   28.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   28.35 + */
   28.36 +
   28.37 +// Simple example that demonstrates reading XML Rss feed
   28.38 +// to generate a HTML file from script and show it by browser
   28.39 +
   28.40 +// Java classes used
   28.41 +var Characters = Java.type("javax.xml.stream.events.Characters");
   28.42 +var Factory = Java.type("javax.xml.stream.XMLInputFactory");
   28.43 +var File = Java.type("java.io.File");
   28.44 +var FileWriter = Java.type("java.io.FileWriter");
   28.45 +var PrintWriter = Java.type("java.io.PrintWriter");
   28.46 +var URL = Java.type("java.net.URL");
   28.47 +
   28.48 +// read Rss feed from a URL. Returns an array
   28.49 +// of objects having only title and link properties
   28.50 +function readRssFeed(url) {
   28.51 +    var fac = Factory.newInstance();
   28.52 +    var reader = fac.createXMLEventReader(url.openStream());
   28.53 +
   28.54 +    // get text content from next event
   28.55 +    function getChars() {
   28.56 +        var result = "";
   28.57 +        var e = reader.nextEvent();
   28.58 +        if (e instanceof Characters) {
   28.59 +            result = e.getData();
   28.60 +        }
   28.61 +        return result;
   28.62 +    }
   28.63 +
   28.64 +    var items = [];
   28.65 +    var title, link;
   28.66 +    var inItem = false;
   28.67 +    while (reader.hasNext()) {
   28.68 +        var evt = reader.nextEvent();
   28.69 +        if (evt.isStartElement()) {
   28.70 +            var local = evt.name.localPart;
   28.71 +            if (local == "item") {
   28.72 +               // capture title, description now
   28.73 +               inItem = true;
   28.74 +            }
   28.75 +        
   28.76 +            if (inItem) {
   28.77 +                switch (local) {
   28.78 +                    case 'title':
   28.79 +                        title = getChars();
   28.80 +                        break;
   28.81 +                    case 'link':
   28.82 +                        link = getChars();
   28.83 +                        break;
   28.84 +                }
   28.85 +            }
   28.86 +        } else if (evt.isEndElement()) {
   28.87 +            var local = evt.name.localPart;
   28.88 +            if (local == "item") {
   28.89 +                // one item done, save it in result array
   28.90 +                items.push({ title: title, link: link });
   28.91 +                inItem = false;
   28.92 +            }
   28.93 +        }
   28.94 +    }
   28.95 +
   28.96 +    return items;
   28.97 +}
   28.98 +
   28.99 +// generate simple HTML for an RSS feed
  28.100 +function getBooksHtml() {
  28.101 +    var url = new URL("http://www.gutenberg.org/cache/epub/feeds/today.rss");
  28.102 +    var items = readRssFeed(url);
  28.103 +
  28.104 +    var str = "<ul>";
  28.105 +
  28.106 +    // Nashorn's string interpolation and heredoc
  28.107 +    // support is very handy in generating text content
  28.108 +    // that is filled with elements from runtime objects.
  28.109 +    // We insert title and link in <li> elements here.
  28.110 +    for each (i in items) {
  28.111 +        str += <<EOF
  28.112 +<li>
  28.113 +    <a href="${i.link}">${i.title}</a>
  28.114 +</li>
  28.115 +EOF
  28.116 +    }
  28.117 +    str += "</ul>";
  28.118 +    return str;
  28.119 +}
  28.120 +
  28.121 +// write the string to the given file
  28.122 +function writeTo(file, str) {
  28.123 +    var w = new PrintWriter(new FileWriter(file));
  28.124 +    try {
  28.125 +        w.print(str);
  28.126 +    } finally {
  28.127 +        w.close();
  28.128 +    }
  28.129 +}
  28.130 +
  28.131 +// generate books HTML
  28.132 +var str = getBooksHtml();
  28.133 +
  28.134 +// write to file. __DIR__ is directory where
  28.135 +// this script is stored.
  28.136 +var file = new File(__DIR__ + "books.html");
  28.137 +writeTo(file, str);
  28.138 +
  28.139 +// show it by desktop browser
  28.140 +try {
  28.141 +    var Desktop = Java.type("java.awt.Desktop");
  28.142 +    Desktop.desktop.browse(file.toURI());
  28.143 +} catch (e) {
  28.144 +    print(e);
  28.145 +}
    29.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.2 +++ b/samples/heredoc.js	Wed May 14 11:02:04 2014 -0700
    29.3 @@ -0,0 +1,51 @@
    29.4 +#// Usage: jjs -scripting heredoc.js
    29.5 +
    29.6 +/*
    29.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    29.8 + * 
    29.9 + * Redistribution and use in source and binary forms, with or without
   29.10 + * modification, are permitted provided that the following conditions
   29.11 + * are met:
   29.12 + * 
   29.13 + *   - Redistributions of source code must retain the above copyright
   29.14 + *     notice, this list of conditions and the following disclaimer.
   29.15 + * 
   29.16 + *   - Redistributions in binary form must reproduce the above copyright
   29.17 + *     notice, this list of conditions and the following disclaimer in the
   29.18 + *     documentation and/or other materials provided with the distribution.
   29.19 + * 
   29.20 + *   - Neither the name of Oracle nor the names of its
   29.21 + *     contributors may be used to endorse or promote products derived
   29.22 + *     from this software without specific prior written permission.
   29.23 + * 
   29.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   29.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   29.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   29.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   29.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   29.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   29.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   29.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   29.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   29.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   29.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   29.35 + */
   29.36 +
   29.37 +// Nashorn supports Shell script like here-documents
   29.38 +// in -scripting mode. Here-docs are multi-line strings
   29.39 +// that are possibly interpolated with ${} expressions
   29.40 +// See also http://en.wikipedia.org/wiki/Here_document
   29.41 +
   29.42 +var sender = "Buffy the Vampire Slayer";
   29.43 +var recipient = "Spike";
   29.44 + 
   29.45 +print(<<END
   29.46 + 
   29.47 +Dear ${recipient},
   29.48 + 
   29.49 +I wish you to leave Sunnydale and never return.
   29.50 + 
   29.51 +Not Quite Love,
   29.52 +${sender}
   29.53 + 
   29.54 +END);
    30.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    30.2 +++ b/samples/interface_impl.js	Wed May 14 11:02:04 2014 -0700
    30.3 @@ -0,0 +1,48 @@
    30.4 +/*
    30.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    30.6 + * 
    30.7 + * Redistribution and use in source and binary forms, with or without
    30.8 + * modification, are permitted provided that the following conditions
    30.9 + * are met:
   30.10 + * 
   30.11 + *   - Redistributions of source code must retain the above copyright
   30.12 + *     notice, this list of conditions and the following disclaimer.
   30.13 + * 
   30.14 + *   - Redistributions in binary form must reproduce the above copyright
   30.15 + *     notice, this list of conditions and the following disclaimer in the
   30.16 + *     documentation and/or other materials provided with the distribution.
   30.17 + * 
   30.18 + *   - Neither the name of Oracle nor the names of its
   30.19 + *     contributors may be used to endorse or promote products derived
   30.20 + *     from this software without specific prior written permission.
   30.21 + * 
   30.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   30.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   30.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   30.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   30.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   30.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   30.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   30.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   30.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   30.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   30.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   30.33 + */
   30.34 +
   30.35 +// nashorn supports Java interface implementation
   30.36 +// by script using anonymous class-like syntax
   30.37 +
   30.38 +var Runnable = Java.type("java.lang.Runnable");
   30.39 +var Thread = Java.type("java.lang.Thread");
   30.40 +// use anonymous class-like new syntax
   30.41 +var r = new Runnable() {
   30.42 +    run: function() {
   30.43 +        print("I am a runnable " + Thread.currentThread());
   30.44 +    }
   30.45 +}
   30.46 +
   30.47 +r.run();
   30.48 +
   30.49 +var t = new Thread(r);
   30.50 +t.start();
   30.51 +t.join();
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/samples/javaastviewer.js	Wed May 14 11:02:04 2014 -0700
    31.3 @@ -0,0 +1,202 @@
    31.4 +#// Usage: jjs -fx javaastviewer.js -- <.java files>
    31.5 +
    31.6 +/*
    31.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    31.8 + * 
    31.9 + * Redistribution and use in source and binary forms, with or without
   31.10 + * modification, are permitted provided that the following conditions
   31.11 + * are met:
   31.12 + * 
   31.13 + *   - Redistributions of source code must retain the above copyright
   31.14 + *     notice, this list of conditions and the following disclaimer.
   31.15 + * 
   31.16 + *   - Redistributions in binary form must reproduce the above copyright
   31.17 + *     notice, this list of conditions and the following disclaimer in the
   31.18 + *     documentation and/or other materials provided with the distribution.
   31.19 + * 
   31.20 + *   - Neither the name of Oracle nor the names of its
   31.21 + *     contributors may be used to endorse or promote products derived
   31.22 + *     from this software without specific prior written permission.
   31.23 + * 
   31.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   31.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   31.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   31.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   31.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   31.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   31.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   31.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   31.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   31.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   31.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   31.35 + */
   31.36 +
   31.37 +// This example demonstrates Java subclassing by Java.extend
   31.38 +// and javac Compiler and Tree API. This example also uses
   31.39 +// -fx and javafx TreeView to visualize Java AST as TreeView
   31.40 +
   31.41 +if (!$OPTIONS._fx || arguments.length == 0) {
   31.42 +    print("Usage: jjs -fx javaastviewer.js -- <.java files>");
   31.43 +    exit(1);
   31.44 +}
   31.45 +
   31.46 +// Java types used
   31.47 +var Enum = Java.type("java.lang.Enum");
   31.48 +var HashSet  = Java.type("java.util.HashSet");
   31.49 +var Name = Java.type("javax.lang.model.element.Name");
   31.50 +var List = Java.type("java.util.List");
   31.51 +var Set  = Java.type("java.util.Set");
   31.52 +var SimpleTreeVisitor = Java.type("com.sun.source.util.SimpleTreeVisitor");
   31.53 +var StringArray = Java.type("java.lang.String[]");
   31.54 +var ToolProvider = Java.type("javax.tools.ToolProvider");
   31.55 +var Tree = Java.type("com.sun.source.tree.Tree");
   31.56 +
   31.57 +function javaASTToScriptObject(args) {
   31.58 +    // properties ignored (javac implementation class properties) in AST view.
   31.59 +    // may not be exhaustive - any getAbc would become "abc" property or
   31.60 +    // public field becomes a property of same name.
   31.61 +    var ignoredProps = new HashSet();
   31.62 +    for each (var word in 
   31.63 +        ['extending', 'implementing', 'init', 'mods', 'clazz', 'defs', 
   31.64 +         'expr', 'tag', 'preferredPosition', 'qualid', 'recvparam',
   31.65 +         'restype', 'params', 'startPosition', 'thrown',
   31.66 +         'tree', 'typarams', 'typetag', 'vartype']) {
   31.67 +        ignoredProps.add(word);
   31.68 +    }
   31.69 +
   31.70 +    // get the system compiler tool
   31.71 +    var compiler = ToolProvider.systemJavaCompiler;
   31.72 +
   31.73 +    // get standard file manager
   31.74 +    var fileMgr = compiler.getStandardFileManager(null, null, null);
   31.75 +
   31.76 +    // make a list of compilation unit from command line argument file names
   31.77 +    // Using Java.to convert script array (arguments) to a Java String[]
   31.78 +    var compUnits = fileMgr.getJavaFileObjects(Java.to(args, StringArray));
   31.79 +
   31.80 +    // create a new compilation task
   31.81 +    var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
   31.82 +
   31.83 +    // subclass SimpleTreeVisitor - converts Java AST node to
   31.84 +    // a simple script object by walking through it
   31.85 +    var ConverterVisitor = Java.extend(SimpleTreeVisitor);
   31.86 +
   31.87 +    var visitor = new ConverterVisitor() {
   31.88 +        // convert java AST node to a friendly script object
   31.89 +        // which can be viewed. Every node ends up in defaultAction 
   31.90 +        // method of SimpleTreeVisitor method.
   31.91 +
   31.92 +        defaultAction: function (node, p) {
   31.93 +            var resultObj = {};
   31.94 +            // Nashorn does not iterate properties and methods of Java objects
   31.95 +            // But, we can bind properties of any object (including java objects)
   31.96 +            // to a script object and iterate it!
   31.97 +            var obj = {};
   31.98 +            Object.bindProperties(obj, node);
   31.99 +
  31.100 +            // we don't want every property, method of java object
  31.101 +            for (var prop in obj) {
  31.102 +                var val = obj[prop];
  31.103 +                var type = typeof val;
  31.104 +                // ignore 'method' members
  31.105 +                if (type == 'function' || type == 'undefined') {
  31.106 +                    continue;
  31.107 +                }
  31.108 +
  31.109 +                // ignore properties from Javac implementation
  31.110 +                // classes - hack by name!!
  31.111 +                if (ignoredProps.contains(prop)) {
  31.112 +                    continue;
  31.113 +                }
  31.114 +
  31.115 +                // subtree - recurse it
  31.116 +                if (val instanceof Tree) {
  31.117 +                    resultObj[prop] = visitor.visit(val, p);
  31.118 +                } else if (val instanceof List) {
  31.119 +                    // List of trees - recurse each and make an array
  31.120 +                    var len = val.size();
  31.121 +                    if (len != 0) {
  31.122 +                        var arr = [];
  31.123 +                        for (var j = 0; j < len; j++) {
  31.124 +                            var e = val[j];
  31.125 +                            if (e instanceof Tree) {
  31.126 +                                arr.push(visitor.visit(e, p));
  31.127 +                            }
  31.128 +                        }
  31.129 +                        resultObj[prop] = arr;
  31.130 +                    }
  31.131 +                } else if (val instanceof Set) {
  31.132 +                    // Set - used for modifier flags
  31.133 +                    // make array
  31.134 +                    var len = val.size();
  31.135 +                    if (len != 0) {
  31.136 +                        var arr = [];
  31.137 +                        for each (var e in val) {
  31.138 +                            if (e instanceof Enum || typeof e == 'string') {
  31.139 +                                arr.push(e.toString());
  31.140 +                            }
  31.141 +                        }
  31.142 +                        resultObj[prop] = arr;
  31.143 +                    }
  31.144 +                } else if (val instanceof Enum || val instanceof Name) {
  31.145 +                    // make string for any Enum or Name
  31.146 +                    resultObj[prop] = val.toString();
  31.147 +                } else if (type != 'object') {
  31.148 +                    // primitives 'as is'
  31.149 +                    resultObj[prop] = val;
  31.150 +                }
  31.151 +            }
  31.152 +            return resultObj;
  31.153 +        }
  31.154 +    }
  31.155 +
  31.156 +    // top level object with one property for each compilation unit
  31.157 +    var scriptObj = {};
  31.158 +    for each (var cu in task.parse()) {
  31.159 +        scriptObj[cu.sourceFile.name] = cu.accept(visitor, null);
  31.160 +    }
  31.161 +
  31.162 +    return scriptObj;
  31.163 +}
  31.164 +
  31.165 +// JavaFX classes used
  31.166 +var StackPane = Java.type("javafx.scene.layout.StackPane");
  31.167 +var Scene     = Java.type("javafx.scene.Scene");
  31.168 +var TreeItem  = Java.type("javafx.scene.control.TreeItem");
  31.169 +var TreeView  = Java.type("javafx.scene.control.TreeView");
  31.170 +
  31.171 +// Create a javafx TreeItem to view a script object
  31.172 +function treeItemForObject(obj, name) {
  31.173 +    var item = new TreeItem(name);
  31.174 +    for (var prop in obj) {
  31.175 +       var node = obj[prop];
  31.176 +       if (typeof node == 'object') {
  31.177 +           if (node == null) {
  31.178 +               // skip nulls
  31.179 +               continue;
  31.180 +           }
  31.181 +           var subitem = treeItemForObject(node, prop);
  31.182 +       } else {
  31.183 +           var subitem = new TreeItem(prop + ": " + node);
  31.184 +       }
  31.185 +       item.children.add(subitem);
  31.186 +    }
  31.187 +
  31.188 +    item.expanded = true;
  31.189 +    return item;
  31.190 +}
  31.191 +
  31.192 +var commandArgs = arguments;
  31.193 +
  31.194 +// JavaFX start method
  31.195 +function start(stage) {
  31.196 +    var obj = javaASTToScriptObject(commandArgs);
  31.197 +    stage.title = "Java AST Viewer"
  31.198 +    var rootItem = treeItemForObject(obj, "AST");
  31.199 +    rootItem.expanded = true;
  31.200 +    var tree = new TreeView(rootItem);
  31.201 +    var root = new StackPane();
  31.202 +    root.children.add(tree);
  31.203 +    stage.scene = new Scene(root, 300, 450);
  31.204 +    stage.show();
  31.205 +}
    32.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    32.2 +++ b/samples/javacastcounter.js	Wed May 14 11:02:04 2014 -0700
    32.3 @@ -0,0 +1,107 @@
    32.4 +/*
    32.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    32.6 + * 
    32.7 + * Redistribution and use in source and binary forms, with or without
    32.8 + * modification, are permitted provided that the following conditions
    32.9 + * are met:
   32.10 + * 
   32.11 + *   - Redistributions of source code must retain the above copyright
   32.12 + *     notice, this list of conditions and the following disclaimer.
   32.13 + * 
   32.14 + *   - Redistributions in binary form must reproduce the above copyright
   32.15 + *     notice, this list of conditions and the following disclaimer in the
   32.16 + *     documentation and/or other materials provided with the distribution.
   32.17 + * 
   32.18 + *   - Neither the name of Oracle nor the names of its
   32.19 + *     contributors may be used to endorse or promote products derived
   32.20 + *     from this software without specific prior written permission.
   32.21 + * 
   32.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   32.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   32.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   32.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   32.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   32.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   32.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   32.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   32.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   32.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   32.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   32.33 + */
   32.34 +
   32.35 +// Usage: jjs javacastcounter.js -- <.java files>
   32.36 +
   32.37 +// This example demonstrates Nashorn Java.extend API
   32.38 +// to subclass a Java class from script.
   32.39 +
   32.40 +// This example uses Javac Compiler and Tree API
   32.41 +// to list type casts used in java source files.
   32.42 +
   32.43 +if (arguments.length == 0) {
   32.44 +    print("Usage: jjs javacastcounter.js -- <.java files>");
   32.45 +    exit(1);
   32.46 +}
   32.47 +
   32.48 +// Java types used
   32.49 +var ToolProvider = Java.type("javax.tools.ToolProvider");
   32.50 +var TreeScanner = Java.type("com.sun.source.util.TreeScanner");
   32.51 +var Trees = Java.type("com.sun.source.util.Trees");
   32.52 +var StringArray = Java.type("java.lang.String[]");
   32.53 +
   32.54 +// get the system compiler tool
   32.55 +var compiler = ToolProvider.systemJavaCompiler;
   32.56 +
   32.57 +// get standard file manager
   32.58 +var fileMgr = compiler.getStandardFileManager(null, null, null);
   32.59 +
   32.60 +// make a list of compilation unit from command line argument file names
   32.61 +// Using Java.to convert script array (arguments) to a Java String[]
   32.62 +var compUnits = fileMgr.getJavaFileObjects(Java.to(arguments, StringArray));
   32.63 +
   32.64 +// create a new compilation task
   32.65 +var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
   32.66 +
   32.67 +// SourcePositions object to get positions of AST nodes
   32.68 +var sourcePositions = Trees.instance(task).sourcePositions;
   32.69 +
   32.70 +// Subclass TreeScanner class
   32.71 +var CastCounter = Java.extend(TreeScanner);
   32.72 +
   32.73 +var counter = new CastCounter() {
   32.74 +    // current CompilationUnitTree
   32.75 +    compUnit: null,
   32.76 +    // current LineMap (pos -> line, column)
   32.77 +    lineMap: null,
   32.78 +    // current compilation unit's file name
   32.79 +    fileName: null,
   32.80 +
   32.81 +    // overrides of TreeScanner methods
   32.82 +
   32.83 +    visitCompilationUnit: function(node, p) {
   32.84 +        // capture info about current Compilation unit
   32.85 +        this.compUnit = node;
   32.86 +        this.lineMap = node.lineMap;
   32.87 +        this.fileName = node.sourceFile.name;
   32.88 +
   32.89 +        // Using Java.super API to call super class method here        
   32.90 +        return Java.super(counter).visitCompilationUnit(node, p);
   32.91 +    },
   32.92 +
   32.93 +    visitTypeCast: function(node, p) {
   32.94 +        // print information on this type cast node
   32.95 +        var pos = sourcePositions.getStartPosition(this.compUnit, node);
   32.96 +        var line = this.lineMap.getLineNumber(pos);
   32.97 +        var col = this.lineMap.getColumnNumber(pos);
   32.98 +        print(node + " @ " + this.fileName + ":" + line + ":" + col);
   32.99 +
  32.100 +        // count one more type cast
  32.101 +        return 1;
  32.102 +    },
  32.103 +
  32.104 +    reduce: function(r1, r2) {
  32.105 +        return (r1 == null ? 0 : r1) + (r2 == null ? 0 : r2);
  32.106 +    }
  32.107 +};
  32.108 +
  32.109 +// print total number of type cast nodes seen
  32.110 +print("Total casts:", counter.scan(task.parse(), null));
    33.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    33.2 +++ b/samples/javaimporter.js	Wed May 14 11:02:04 2014 -0700
    33.3 @@ -0,0 +1,63 @@
    33.4 +/*
    33.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    33.6 + * 
    33.7 + * Redistribution and use in source and binary forms, with or without
    33.8 + * modification, are permitted provided that the following conditions
    33.9 + * are met:
   33.10 + * 
   33.11 + *   - Redistributions of source code must retain the above copyright
   33.12 + *     notice, this list of conditions and the following disclaimer.
   33.13 + * 
   33.14 + *   - Redistributions in binary form must reproduce the above copyright
   33.15 + *     notice, this list of conditions and the following disclaimer in the
   33.16 + *     documentation and/or other materials provided with the distribution.
   33.17 + * 
   33.18 + *   - Neither the name of Oracle nor the names of its
   33.19 + *     contributors may be used to endorse or promote products derived
   33.20 + *     from this software without specific prior written permission.
   33.21 + * 
   33.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   33.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   33.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   33.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   33.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   33.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   33.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   33.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   33.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   33.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   33.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   33.33 + */
   33.34 +
   33.35 +// JavaImporter along with 'with' statement helps in
   33.36 +// localized Java class references
   33.37 +
   33.38 +function readTextFromURL(url) {
   33.39 +
   33.40 +    // equivalent to 
   33.41 +    // 
   33.42 +    //    import java.io.*;
   33.43 +    //    import java.net.*;
   33.44 +    //    import java.lang.StringBuffer;
   33.45 +    //
   33.46 +    // only inside the 'with' statement
   33.47 +    with (new JavaImporter(java.io, 
   33.48 +        java.net,
   33.49 +        java.lang.StringBuilder)) {
   33.50 +        var buf = new StringBuilder();
   33.51 +        var u = new URL(url);
   33.52 +        var reader = new BufferedReader(
   33.53 +            new InputStreamReader(u.openStream()));
   33.54 +        var line = null;
   33.55 +        try {
   33.56 +            while ((line = reader.readLine()) != null)
   33.57 +                buf.append(line).append('\n');
   33.58 +        } finally {
   33.59 +            reader.close();
   33.60 +        }
   33.61 +
   33.62 +        return buf.toString();
   33.63 +    }
   33.64 +}
   33.65 +
   33.66 +print(readTextFromURL("https://twitter.com/"));
    34.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    34.2 +++ b/samples/javalist.js	Wed May 14 11:02:04 2014 -0700
    34.3 @@ -0,0 +1,63 @@
    34.4 +/*
    34.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    34.6 + * 
    34.7 + * Redistribution and use in source and binary forms, with or without
    34.8 + * modification, are permitted provided that the following conditions
    34.9 + * are met:
   34.10 + * 
   34.11 + *   - Redistributions of source code must retain the above copyright
   34.12 + *     notice, this list of conditions and the following disclaimer.
   34.13 + * 
   34.14 + *   - Redistributions in binary form must reproduce the above copyright
   34.15 + *     notice, this list of conditions and the following disclaimer in the
   34.16 + *     documentation and/or other materials provided with the distribution.
   34.17 + * 
   34.18 + *   - Neither the name of Oracle nor the names of its
   34.19 + *     contributors may be used to endorse or promote products derived
   34.20 + *     from this software without specific prior written permission.
   34.21 + * 
   34.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   34.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   34.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   34.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   34.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   34.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   34.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   34.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   34.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   34.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   34.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   34.33 + */
   34.34 +
   34.35 +// Java List elements accessed/modified via
   34.36 +// array element access/update syntax
   34.37 +
   34.38 +var ArrayList = Java.type("java.util.ArrayList");
   34.39 +var list = new ArrayList();
   34.40 +
   34.41 +// add elements to list by List's add method calls
   34.42 +list.add("js");
   34.43 +list.add("ecmascript");
   34.44 +list.add("nashorn");
   34.45 +
   34.46 +// get by List's get(int) method
   34.47 +print(list[0]);
   34.48 +print(list[1]);
   34.49 +print(list[2]);
   34.50 +
   34.51 +// access list elements by indexed access as well
   34.52 +print(list[0]);
   34.53 +print(list[1]);
   34.54 +print(list[2]);
   34.55 +
   34.56 +// assign to list elements by index as well
   34.57 +list[0] = list[0].toUpperCase();
   34.58 +list[1] = list[1].toUpperCase();
   34.59 +list[2] = list[2].toUpperCase();
   34.60 +
   34.61 +print(list.get(0));
   34.62 +print(list.get(1));
   34.63 +print(list.get(2));
   34.64 +print(list[0]);
   34.65 +print(list[1]);
   34.66 +print(list[2]);
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/samples/javamap.js	Wed May 14 11:02:04 2014 -0700
    35.3 @@ -0,0 +1,58 @@
    35.4 +/*
    35.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    35.6 + * 
    35.7 + * Redistribution and use in source and binary forms, with or without
    35.8 + * modification, are permitted provided that the following conditions
    35.9 + * are met:
   35.10 + * 
   35.11 + *   - Redistributions of source code must retain the above copyright
   35.12 + *     notice, this list of conditions and the following disclaimer.
   35.13 + * 
   35.14 + *   - Redistributions in binary form must reproduce the above copyright
   35.15 + *     notice, this list of conditions and the following disclaimer in the
   35.16 + *     documentation and/or other materials provided with the distribution.
   35.17 + * 
   35.18 + *   - Neither the name of Oracle nor the names of its
   35.19 + *     contributors may be used to endorse or promote products derived
   35.20 + *     from this software without specific prior written permission.
   35.21 + * 
   35.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   35.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   35.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   35.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   35.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   35.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   35.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   35.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   35.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   35.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   35.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   35.33 + */
   35.34 +
   35.35 +// Java Map keys as properties
   35.36 +
   35.37 +// Demonstrating Java Map key/value can be accessed
   35.38 +// as property/value from script.
   35.39 +
   35.40 +var HashMap = Java.type("java.util.HashMap");
   35.41 +var map = new HashMap();
   35.42 +
   35.43 +// map key-value access by java get/put method calls
   35.44 +map.put('js', 'nashorn');
   35.45 +print(map.get('js'));
   35.46 +
   35.47 +// access keys of map as properties
   35.48 +print(map['js']);
   35.49 +print(map.js);
   35.50 +
   35.51 +// also assign new key-value pair 
   35.52 +// as 'property-value'
   35.53 +map['language'] = 'java';
   35.54 +print(map.get("language"));
   35.55 +print(map.language);
   35.56 +print(map['language']);
   35.57 +
   35.58 +map.answer = 42;
   35.59 +print(map.get("answer"));
   35.60 +print(map.answer);
   35.61 +print(map['answer']);
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/samples/javashell.js	Wed May 14 11:02:04 2014 -0700
    36.3 @@ -0,0 +1,146 @@
    36.4 +#// Usage: jjs -scripting javashell.js
    36.5 +
    36.6 +/*
    36.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    36.8 + * 
    36.9 + * Redistribution and use in source and binary forms, with or without
   36.10 + * modification, are permitted provided that the following conditions
   36.11 + * are met:
   36.12 + * 
   36.13 + *   - Redistributions of source code must retain the above copyright
   36.14 + *     notice, this list of conditions and the following disclaimer.
   36.15 + * 
   36.16 + *   - Redistributions in binary form must reproduce the above copyright
   36.17 + *     notice, this list of conditions and the following disclaimer in the
   36.18 + *     documentation and/or other materials provided with the distribution.
   36.19 + * 
   36.20 + *   - Neither the name of Oracle nor the names of its
   36.21 + *     contributors may be used to endorse or promote products derived
   36.22 + *     from this software without specific prior written permission.
   36.23 + * 
   36.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   36.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   36.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   36.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   36.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   36.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   36.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   36.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   36.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   36.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   36.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   36.35 + */
   36.36 +
   36.37 +// Simple Java "shell" with which you can try out
   36.38 +// your few liner Java code leaving imports, main etc.
   36.39 +// And you can leave even compilation as this script
   36.40 +// takes care boilerplate+compile step for you.
   36.41 +
   36.42 +// Java types used
   36.43 +var Arrays = Java.type("java.util.Arrays");
   36.44 +var BufferedReader = Java.type("java.io.BufferedReader");
   36.45 +var FileWriter = Java.type("java.io.FileWriter");
   36.46 +var LocalDateTime = Java.type("java.time.LocalDateTime");
   36.47 +var InputStreamReader = Java.type("java.io.InputStreamReader");
   36.48 +var PrintWriter = Java.type("java.io.PrintWriter");
   36.49 +var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
   36.50 +var System = Java.type("java.lang.System");
   36.51 +
   36.52 +// read multiple lines of input from stdin till user
   36.53 +// enters an empty line
   36.54 +function input(endMarker, prompt) {
   36.55 +    if (!endMarker) {
   36.56 +        endMarker = "";
   36.57 +    }
   36.58 +
   36.59 +    if (!prompt) {
   36.60 +        prompt = " >> ";
   36.61 +    }
   36.62 +
   36.63 +    var str = "";
   36.64 +    var reader = new BufferedReader(new InputStreamReader(System.in));
   36.65 +    var line;
   36.66 +    while (true) {
   36.67 +        System.out.print(prompt);
   36.68 +        line = reader.readLine();
   36.69 +        if (line == null || line == endMarker) {
   36.70 +            break;
   36.71 +        }
   36.72 +        str += line + "\n";
   36.73 +    }
   36.74 +    return str;
   36.75 +}
   36.76 +
   36.77 +// write the string to the given file
   36.78 +function writeTo(file, str) {
   36.79 +    var w = new PrintWriter(new FileWriter(file));
   36.80 +    try {
   36.81 +        w.print(str);
   36.82 +    } finally {
   36.83 +        w.close();
   36.84 +    }
   36.85 +}
   36.86 +
   36.87 +// generate Java code with user's input
   36.88 +// put inside generated main method
   36.89 +function generate(className) {
   36.90 +    var usercode = input();
   36.91 +    if (usercode == "") {
   36.92 +        return false;
   36.93 +    }
   36.94 +
   36.95 +    var fullcode = <<EOF
   36.96 +// userful imports, add more here if you want
   36.97 +// more imports.
   36.98 +import static java.lang.System.*;
   36.99 +import java.io.*;
  36.100 +import java.net.*;
  36.101 +import java.math.*;
  36.102 +import java.nio.file.*;
  36.103 +import java.time.*;
  36.104 +import java.time.chrono.*;
  36.105 +import java.time.format.*;
  36.106 +import java.time.temporal.*;
  36.107 +import java.time.zone.*;
  36.108 +import java.util.*;
  36.109 +import java.util.concurrent.*;
  36.110 +import java.util.function.*;
  36.111 +import java.util.stream.*;
  36.112 +
  36.113 +public class ${className} {
  36.114 +   public static void main(String[] args) throws Exception {
  36.115 +       ${usercode}
  36.116 +   }
  36.117 +}
  36.118 +EOF
  36.119 +
  36.120 +    writeTo("${className}.java", fullcode);
  36.121 +    return true;
  36.122 +}
  36.123 +
  36.124 +// execute code command
  36.125 +function exec(args) {
  36.126 +    // build child process and start it!
  36.127 +    new ProcessBuilder(Arrays.asList(args.split(' ')))
  36.128 +         .inheritIO()
  36.129 +         .start()
  36.130 +         .waitFor();
  36.131 +}
  36.132 +
  36.133 +// generate unique name
  36.134 +function uniqueName() {
  36.135 +    var now = LocalDateTime.now().toString();
  36.136 +    // replace unsafe chars with '_' 
  36.137 +    return "JavaShell" + now.replace(/-|:|\./g, '_');
  36.138 +}
  36.139 +
  36.140 +// read-compile-run loop
  36.141 +while(true) {
  36.142 +    var className = uniqueName();
  36.143 +    if (generate(className)) {
  36.144 +        exec("javac ${className}.java");
  36.145 +        exec("java ${className}");
  36.146 +    } else {
  36.147 +        break;
  36.148 +    }
  36.149 +}
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/samples/jsadapter_dom.js	Wed May 14 11:02:04 2014 -0700
    37.3 @@ -0,0 +1,189 @@
    37.4 +#// Usage: jjs -scripting jsadapter_dom.js
    37.5 +
    37.6 +/*
    37.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    37.8 + * 
    37.9 + * Redistribution and use in source and binary forms, with or without
   37.10 + * modification, are permitted provided that the following conditions
   37.11 + * are met:
   37.12 + * 
   37.13 + *   - Redistributions of source code must retain the above copyright
   37.14 + *     notice, this list of conditions and the following disclaimer.
   37.15 + * 
   37.16 + *   - Redistributions in binary form must reproduce the above copyright
   37.17 + *     notice, this list of conditions and the following disclaimer in the
   37.18 + *     documentation and/or other materials provided with the distribution.
   37.19 + * 
   37.20 + *   - Neither the name of Oracle nor the names of its
   37.21 + *     contributors may be used to endorse or promote products derived
   37.22 + *     from this software without specific prior written permission.
   37.23 + * 
   37.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   37.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   37.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   37.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   37.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   37.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   37.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   37.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   37.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   37.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   37.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   37.35 + */
   37.36 +
   37.37 +// Simple example that demonstrates reading XML Rss feed
   37.38 +// to generate a HTML file from script and show it by browser
   37.39 +// Uses XML DOM parser and DOM element wrapped by script 
   37.40 +// "proxy" (JSAdapter constructor)
   37.41 +
   37.42 +// Java classes used
   37.43 +var DocBuilderFac = Java.type("javax.xml.parsers.DocumentBuilderFactory");
   37.44 +var Node = Java.type("org.w3c.dom.Node");
   37.45 +var File = Java.type("java.io.File");
   37.46 +var FileWriter = Java.type("java.io.FileWriter");
   37.47 +var PrintWriter = Java.type("java.io.PrintWriter");
   37.48 +
   37.49 +// constants from Node class
   37.50 +var ELEMENT_NODE = Node.ELEMENT_NODE;
   37.51 +var TEXT_NODE = Node.TEXT_NODE;
   37.52 +
   37.53 +// parse XML from uri and return Document
   37.54 +function parseXML(uri) {
   37.55 +    var docBuilder = DocBuilderFac.newInstance().newDocumentBuilder();
   37.56 +    return docBuilder["parse(java.lang.String)"](uri);
   37.57 +}
   37.58 +
   37.59 +// get child Elements of given name of the parent element given
   37.60 +function getChildElements(elem, name) {
   37.61 +    var nodeList = elem.childNodes;
   37.62 +    var childElems = [];
   37.63 +    var len = nodeList.length;
   37.64 +    for (var i = 0; i < len; i++) {
   37.65 +        var node = nodeList.item(i);
   37.66 +        if (node.nodeType == ELEMENT_NODE &&
   37.67 +            node.tagName == name) {
   37.68 +            childElems.push(wrapElement(node));
   37.69 +        }
   37.70 +    }
   37.71 +
   37.72 +    return childElems;
   37.73 +}
   37.74 +
   37.75 +// get concatenated child text content of an Element
   37.76 +function getElemText(elem) {
   37.77 +    var nodeList = elem.childNodes;
   37.78 +    var len = nodeList.length;
   37.79 +    var text = '';
   37.80 +    for (var i = 0; i < len; i++) {
   37.81 +        var node = nodeList.item(i);
   37.82 +        if (node.nodeType == TEXT_NODE) {
   37.83 +            text += node.nodeValue;
   37.84 +        } 
   37.85 +    }
   37.86 +
   37.87 +    return text;
   37.88 +}
   37.89 +
   37.90 +// Wrap DOM Element object as a convenient script object
   37.91 +// using JSAdapter. JSAdapter is like java.lang.reflect.Proxy
   37.92 +// in that it allows property access, method calls be trapped
   37.93 +// by 'magic' methods like __get__, __call__.
   37.94 +function wrapElement(elem) {
   37.95 +    if (! elem) {
   37.96 +        return elem;
   37.97 +    }
   37.98 +    return new JSAdapter() {
   37.99 +        // getter to expose child elements and attributes by name
  37.100 +        __get__: function(name) {
  37.101 +            if (typeof name == 'string') {
  37.102 +                if (name.startsWith('@')) {
  37.103 +                    var attr = elem.getAttributeNode(name.substring(1));
  37.104 +                    return !attr? undefined : attr.value;
  37.105 +                }
  37.106 +
  37.107 +                var arr = getChildElements(elem, name);
  37.108 +                if (arr.length == 1) {
  37.109 +                    // single child element, expose as single element
  37.110 +                    return arr[0];
  37.111 +                } else {
  37.112 +                    // multiple children of given name, expose as array
  37.113 +                    return arr;
  37.114 +                }
  37.115 +            }
  37.116 +            return undefined;
  37.117 +        },
  37.118 +
  37.119 +        __call__: function(name) {
  37.120 +            // toString override to get text content of this Element
  37.121 +            if (name == 'toString' || name == 'valueOf') {
  37.122 +                return getElemText(elem);
  37.123 +            }
  37.124 +            return undefined;
  37.125 +        }
  37.126 +    }
  37.127 +}
  37.128 +
  37.129 +// generate HTML using here-doc and string interpolation
  37.130 +function getBooksHtml() {
  37.131 +    var doc = parseXML("http://www.gutenberg.org/cache/epub/feeds/today.rss");
  37.132 +    // wrap document root Element as script convenient object
  37.133 +    var rss = wrapElement(doc.documentElement);
  37.134 +    print("rss file version " + rss['@version']);
  37.135 +
  37.136 +    var str = <<HEAD
  37.137 +
  37.138 +<html>
  37.139 +<title>${rss.channel.title}</title>
  37.140 +<body>
  37.141 +<h1>${rss.channel.description}</h1>
  37.142 +<p>
  37.143 +Published on ${rss.channel.pubDate}
  37.144 +</p>
  37.145 +
  37.146 +HEAD
  37.147 +
  37.148 +    var items = rss.channel.item;
  37.149 +    for each (var i in items) {
  37.150 +        str += <<LIST
  37.151 +
  37.152 +<dl>
  37.153 +<dt><a href="${i.link}">${i.title}</a></dt>
  37.154 +<dd>${i.description}</dd>
  37.155 +</dl>
  37.156 +
  37.157 +LIST
  37.158 +    }
  37.159 +    str += <<END
  37.160 +
  37.161 +</body>
  37.162 +</html>
  37.163 +
  37.164 +END
  37.165 +    return str;
  37.166 +}
  37.167 +
  37.168 +// write the string to the given file
  37.169 +function writeTo(file, str) {
  37.170 +    var w = new PrintWriter(new FileWriter(file));
  37.171 +    try {
  37.172 +        w.print(str);
  37.173 +    } finally {
  37.174 +        w.close();
  37.175 +    }
  37.176 +}
  37.177 +
  37.178 +// generate books HTML
  37.179 +var str = getBooksHtml();
  37.180 +
  37.181 +// write to file. __DIR__ is directory where
  37.182 +// this script is stored.
  37.183 +var file = new File(__DIR__ + "books.html");
  37.184 +writeTo(file, str);
  37.185 +
  37.186 +// show it by desktop browser
  37.187 +try {
  37.188 +    var Desktop = Java.type("java.awt.Desktop");
  37.189 +    Desktop.desktop.browse(file.toURI());
  37.190 +} catch (e) {
  37.191 +    print(e);
  37.192 +}
    38.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    38.2 +++ b/samples/jsobject.js	Wed May 14 11:02:04 2014 -0700
    38.3 @@ -0,0 +1,75 @@
    38.4 +#// Usage: jjs -scripting -cp . jsobject.js
    38.5 +
    38.6 +/*
    38.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    38.8 + * 
    38.9 + * Redistribution and use in source and binary forms, with or without
   38.10 + * modification, are permitted provided that the following conditions
   38.11 + * are met:
   38.12 + * 
   38.13 + *   - Redistributions of source code must retain the above copyright
   38.14 + *     notice, this list of conditions and the following disclaimer.
   38.15 + * 
   38.16 + *   - Redistributions in binary form must reproduce the above copyright
   38.17 + *     notice, this list of conditions and the following disclaimer in the
   38.18 + *     documentation and/or other materials provided with the distribution.
   38.19 + * 
   38.20 + *   - Neither the name of Oracle nor the names of its
   38.21 + *     contributors may be used to endorse or promote products derived
   38.22 + *     from this software without specific prior written permission.
   38.23 + * 
   38.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   38.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   38.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   38.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   38.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   38.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   38.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   38.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   38.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   38.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   38.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   38.35 + */
   38.36 +
   38.37 +// This sample demonstrats how to expose a
   38.38 +// script friendly object from your java code
   38.39 +// by implementing jdk.nashorn.api.scripting.JSObject
   38.40 +
   38.41 +// compile the java program
   38.42 +`javac BufferArray.java`;
   38.43 +
   38.44 +// print error, if any and exit
   38.45 +if ($ERR != '') {
   38.46 +    print($ERR);
   38.47 +    exit($EXIT);
   38.48 +}
   38.49 +
   38.50 +// create BufferArray
   38.51 +var BufferArray = Java.type("BufferArray");
   38.52 +var bb = new BufferArray(10);
   38.53 +
   38.54 +// 'magic' methods called to retrieve set/get
   38.55 +// properties on BufferArray instance
   38.56 +var len = bb.length;
   38.57 +print("bb.length = " + len)
   38.58 +for (var i = 0; i < len; i++) {
   38.59 +    bb[i] = i*i;
   38.60 +}
   38.61 +
   38.62 +for (var i = 0; i < len; i++) {
   38.63 +    print(bb[i]);
   38.64 +}
   38.65 +
   38.66 +// get underlying buffer by calling a method
   38.67 +// on BufferArray magic object
   38.68 +
   38.69 +// 'buf' is a function member
   38.70 +print(typeof bb.buf);
   38.71 +var buf = bb.buf();
   38.72 +
   38.73 +// use retrieved underlying nio buffer
   38.74 +var cap = buf.capacity();
   38.75 +print("buf.capacity() = " + cap);
   38.76 +for (var i = 0; i < cap; i++) {
   38.77 +   print(buf.get(i));
   38.78 +}
    39.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    39.2 +++ b/samples/jsobject_mapreduce.js	Wed May 14 11:02:04 2014 -0700
    39.3 @@ -0,0 +1,62 @@
    39.4 +#// Usage: jjs -scripting -cp . jsobject_mapreduce.js
    39.5 +
    39.6 +/*
    39.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    39.8 + * 
    39.9 + * Redistribution and use in source and binary forms, with or without
   39.10 + * modification, are permitted provided that the following conditions
   39.11 + * are met:
   39.12 + * 
   39.13 + *   - Redistributions of source code must retain the above copyright
   39.14 + *     notice, this list of conditions and the following disclaimer.
   39.15 + * 
   39.16 + *   - Redistributions in binary form must reproduce the above copyright
   39.17 + *     notice, this list of conditions and the following disclaimer in the
   39.18 + *     documentation and/or other materials provided with the distribution.
   39.19 + * 
   39.20 + *   - Neither the name of Oracle nor the names of its
   39.21 + *     contributors may be used to endorse or promote products derived
   39.22 + *     from this software without specific prior written permission.
   39.23 + * 
   39.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   39.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   39.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   39.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   39.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   39.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   39.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   39.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   39.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   39.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   39.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   39.35 + */
   39.36 +
   39.37 +// Many Array.prototype functions such as map, 
   39.38 +// filter, reduce, reduceRight, every, some are generic.
   39.39 +// These functions accept ECMAScript array as well as 
   39.40 +// many array-like objects including JSObjects.
   39.41 +// See also http://en.wikipedia.org/wiki/MapReduce
   39.42 +
   39.43 +`javac BufferArray.java`;
   39.44 +
   39.45 +var BufferArray = Java.type("BufferArray");
   39.46 +var buf = new BufferArray(10);
   39.47 +
   39.48 +var map = Array.prototype.map;
   39.49 +var filter = Array.prototype.filter;
   39.50 +var reduce = Array.prototype.reduce;
   39.51 +
   39.52 +// make random list of numbers
   39.53 +for (var i = 0; i < 10; i++)
   39.54 +    buf[i] = Math.random();
   39.55 +
   39.56 +var forEach = Array.prototype.forEach;
   39.57 +// print numbers in the list
   39.58 +forEach.call(buf, function(x) print(x));
   39.59 +
   39.60 +// print sum of squares of the random numbers
   39.61 +print("Square sum:",
   39.62 +    reduce.call(
   39.63 +        map.call(buf, function(x) x*x), 
   39.64 +        function(x, y) x + y)
   39.65 +);
    40.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    40.2 +++ b/samples/jsonviewer.js	Wed May 14 11:02:04 2014 -0700
    40.3 @@ -0,0 +1,120 @@
    40.4 +#// Usage: jjs -fx jsonviewer.js
    40.5 +// or
    40.6 +//        jjs -fx jsonviewer.js -- <url-of-json-doc>
    40.7 +
    40.8 +/*
    40.9 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   40.10 + * 
   40.11 + * Redistribution and use in source and binary forms, with or without
   40.12 + * modification, are permitted provided that the following conditions
   40.13 + * are met:
   40.14 + * 
   40.15 + *   - Redistributions of source code must retain the above copyright
   40.16 + *     notice, this list of conditions and the following disclaimer.
   40.17 + * 
   40.18 + *   - Redistributions in binary form must reproduce the above copyright
   40.19 + *     notice, this list of conditions and the following disclaimer in the
   40.20 + *     documentation and/or other materials provided with the distribution.
   40.21 + * 
   40.22 + *   - Neither the name of Oracle nor the names of its
   40.23 + *     contributors may be used to endorse or promote products derived
   40.24 + *     from this software without specific prior written permission.
   40.25 + * 
   40.26 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   40.27 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   40.28 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   40.29 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   40.30 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   40.31 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   40.32 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   40.33 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   40.34 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   40.35 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   40.36 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   40.37 + */
   40.38 +
   40.39 +if (! $OPTIONS._fx) {
   40.40 +    print("Usage: jjs -fx jsonviewer.js -- <url-of-json-doc>");
   40.41 +    exit(1);
   40.42 +}
   40.43 +
   40.44 +// This example downloads a JSON file from a URL and
   40.45 +// shows the same as a JavaFX tree view.
   40.46 +
   40.47 +// Using JavaFX from Nashorn. See also:
   40.48 +// http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/javafx.html
   40.49 +
   40.50 +// JavaFX classes used
   40.51 +var StackPane = Java.type("javafx.scene.layout.StackPane");
   40.52 +var Scene     = Java.type("javafx.scene.Scene");
   40.53 +var TreeItem  = Java.type("javafx.scene.control.TreeItem");
   40.54 +var TreeView  = Java.type("javafx.scene.control.TreeView");
   40.55 +
   40.56 +// read text content of a URL
   40.57 +function readTextFromURL(url) {
   40.58 +    // equivalent to 
   40.59 +    // 
   40.60 +    //    import java.io.*;
   40.61 +    //    import java.net.*;
   40.62 +    //    import java.lang.StringBuffer;
   40.63 +    //
   40.64 +    // only inside the 'with' statement
   40.65 +    with (new JavaImporter(java.io,
   40.66 +        java.net,
   40.67 +        java.lang.StringBuilder)) {
   40.68 +        var buf = new StringBuilder();
   40.69 +        var u = new URL(url);
   40.70 +        var reader = new BufferedReader(
   40.71 +            new InputStreamReader(u.openStream()));
   40.72 +        var line = null;
   40.73 +        try {
   40.74 +            while ((line = reader.readLine()) != null)
   40.75 +                buf.append(line).append('\n');
   40.76 +        } finally {
   40.77 +            reader.close();
   40.78 +        }
   40.79 +
   40.80 +        return buf.toString();
   40.81 +    }
   40.82 +}
   40.83 +
   40.84 +// Create a javafx TreeItem to view a script object
   40.85 +function treeItemForObject(obj, name) {
   40.86 +    var item = new TreeItem(name);
   40.87 +    for (var prop in obj) {
   40.88 +       var node = obj[prop];
   40.89 +       if (typeof node == 'object') {
   40.90 +           if (node == null) {
   40.91 +               // skip nulls
   40.92 +               continue;
   40.93 +           }
   40.94 +
   40.95 +           if (Array.isArray(node) && node.length == 0) {
   40.96 +               // skip empty arrays
   40.97 +               continue;
   40.98 +           }
   40.99 +
  40.100 +           var subitem = treeItemForObject(node, prop);
  40.101 +       } else {
  40.102 +           var subitem = new TreeItem(prop + ": " + node);
  40.103 +       }
  40.104 +       item.children.add(subitem);
  40.105 +    }
  40.106 +    return item;
  40.107 +}
  40.108 +
  40.109 +var DEFAULT_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&amp;mode=json&amp;units=metric&amp;cnt=7`";
  40.110 +
  40.111 +var url = arguments.length == 0? DEFAULT_URL : arguments[0];
  40.112 +var obj = JSON.parse(readTextFromURL(url));
  40.113 +
  40.114 +// JavaFX start method
  40.115 +function start(stage) {
  40.116 +    stage.title = "JSON Viewer";
  40.117 +    var rootItem = treeItemForObject(obj, url);
  40.118 +    var tree = new TreeView(rootItem);
  40.119 +    var root = new StackPane();
  40.120 +    root.children.add(tree);
  40.121 +    stage.scene = new Scene(root, 300, 450);
  40.122 +    stage.show();
  40.123 +}
    41.1 --- a/samples/letter.js	Tue May 13 23:18:50 2014 -0700
    41.2 +++ b/samples/letter.js	Wed May 14 11:02:04 2014 -0700
    41.3 @@ -1,3 +1,5 @@
    41.4 +#// Usage: jjs -scripting letter.js -- <sender> <recipient>
    41.5 +
    41.6  /*
    41.7   * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    41.8   * 
    42.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    42.2 +++ b/samples/list_mapreduce.js	Wed May 14 11:02:04 2014 -0700
    42.3 @@ -0,0 +1,86 @@
    42.4 +/*
    42.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    42.6 + * 
    42.7 + * Redistribution and use in source and binary forms, with or without
    42.8 + * modification, are permitted provided that the following conditions
    42.9 + * are met:
   42.10 + * 
   42.11 + *   - Redistributions of source code must retain the above copyright
   42.12 + *     notice, this list of conditions and the following disclaimer.
   42.13 + * 
   42.14 + *   - Redistributions in binary form must reproduce the above copyright
   42.15 + *     notice, this list of conditions and the following disclaimer in the
   42.16 + *     documentation and/or other materials provided with the distribution.
   42.17 + * 
   42.18 + *   - Neither the name of Oracle nor the names of its
   42.19 + *     contributors may be used to endorse or promote products derived
   42.20 + *     from this software without specific prior written permission.
   42.21 + * 
   42.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   42.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   42.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   42.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   42.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   42.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   42.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   42.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   42.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   42.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   42.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   42.33 + */
   42.34 +
   42.35 +// Usage: jjs list_mapreduce.js
   42.36 +
   42.37 +// Many Array.prototype functions such as map, 
   42.38 +// filter, reduce, reduceRight, every, some are generic.
   42.39 +// These functions accept ECMAScript array as well as 
   42.40 +// many array-like objects including java.util.ArrayLists.
   42.41 +// So, you can do map/filter/reduce with Java streams or
   42.42 +// you can also use Array.prototype functions as below.
   42.43 +// See also http://en.wikipedia.org/wiki/MapReduce
   42.44 +
   42.45 +var ArrayList = Java.type("java.util.ArrayList");
   42.46 +var list = new ArrayList();
   42.47 +list.add("nashorn");
   42.48 +list.add("ecmascript");
   42.49 +list.add("javascript");
   42.50 +list.add("js");
   42.51 +list.add("scheme");
   42.52 +
   42.53 +var map = Array.prototype.map;
   42.54 +var filter = Array.prototype.filter;
   42.55 +var reduce = Array.prototype.reduce;
   42.56 +
   42.57 +// sum of word lengths
   42.58 +print("Sum word length:",
   42.59 +    reduce.call(
   42.60 +        map.call(list, function(x) x.length),
   42.61 +        function(x, y) x + y)
   42.62 +);
   42.63 +
   42.64 +// filter use to filter out "j*" and concatenate rest with ":"
   42.65 +// after uppercasing all strings
   42.66 +print(
   42.67 +    reduce.call(
   42.68 +        map.call(
   42.69 +            filter.call(list, function(x) !x.startsWith("j")),
   42.70 +            function(x) x.toUpperCase()),
   42.71 +        function(x, y) x + ":" + y)
   42.72 +);
   42.73 +
   42.74 +// another list example involving numbers
   42.75 +list.clear();
   42.76 +// make random list of numbers
   42.77 +for (var i = 0; i < 10; i++)
   42.78 +    list.add(Math.random());
   42.79 +
   42.80 +var forEach = Array.prototype.forEach;
   42.81 +// print numbers in the list
   42.82 +forEach.call(list, function(x) print(x));
   42.83 +
   42.84 +// print sum of squares of the random numbers
   42.85 +print("Square sum:",
   42.86 +    reduce.call(
   42.87 +        map.call(list, function(x) x*x), 
   42.88 +        function(x, y) x + y)
   42.89 +);
    43.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    43.2 +++ b/samples/locales.js	Wed May 14 11:02:04 2014 -0700
    43.3 @@ -0,0 +1,58 @@
    43.4 +/*
    43.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    43.6 + * 
    43.7 + * Redistribution and use in source and binary forms, with or without
    43.8 + * modification, are permitted provided that the following conditions
    43.9 + * are met:
   43.10 + * 
   43.11 + *   - Redistributions of source code must retain the above copyright
   43.12 + *     notice, this list of conditions and the following disclaimer.
   43.13 + * 
   43.14 + *   - Redistributions in binary form must reproduce the above copyright
   43.15 + *     notice, this list of conditions and the following disclaimer in the
   43.16 + *     documentation and/or other materials provided with the distribution.
   43.17 + * 
   43.18 + *   - Neither the name of Oracle nor the names of its
   43.19 + *     contributors may be used to endorse or promote products derived
   43.20 + *     from this software without specific prior written permission.
   43.21 + * 
   43.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   43.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   43.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   43.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   43.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   43.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   43.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   43.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   43.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   43.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   43.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   43.33 + */
   43.34 +
   43.35 +// Simple program that lists available locals. This is ECMAScript
   43.36 +// port of Java example by @brunoborges
   43.37 +
   43.38 +// Java classes used
   43.39 +var Arrays = Java.type("java.util.Arrays");
   43.40 +var Collectors = Java.type("java.util.stream.Collectors");
   43.41 +var JString = Java.type("java.lang.String");
   43.42 +var Locale = Java.type("java.util.Locale");
   43.43 +
   43.44 +var formatStr = "Country : %s \t\t\t\t:\t Country Code : %s";
   43.45 +
   43.46 +// Nashorn allows script functions to be passed
   43.47 +// whereever Java8 lambdas are expected.
   43.48 +
   43.49 +// Nashorn also supports "expression closures" supported by
   43.50 +// Mozilla JavaScript 1.8 version. See also
   43.51 +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8
   43.52 +
   43.53 +// The following prints locales in (country) display name order
   43.54 +var list = Arrays.asList(Locale.getISOCountries())
   43.55 +    .stream()
   43.56 +    .map(function(x) new Locale("", x))
   43.57 +    .sorted(function(c0, c1) c0.displayCountry.compareTo(c1.displayCountry))
   43.58 +    .map(function(l) JString.format(formatStr, l.displayCountry, l.country))
   43.59 +    .collect(Collectors.toList());
   43.60 +
   43.61 +list.forEach(print);
    44.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    44.2 +++ b/samples/logisticmap.js	Wed May 14 11:02:04 2014 -0700
    44.3 @@ -0,0 +1,82 @@
    44.4 +#// Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>
    44.5 +
    44.6 +/*
    44.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    44.8 + * 
    44.9 + * Redistribution and use in source and binary forms, with or without
   44.10 + * modification, are permitted provided that the following conditions
   44.11 + * are met:
   44.12 + * 
   44.13 + *   - Redistributions of source code must retain the above copyright
   44.14 + *     notice, this list of conditions and the following disclaimer.
   44.15 + * 
   44.16 + *   - Redistributions in binary form must reproduce the above copyright
   44.17 + *     notice, this list of conditions and the following disclaimer in the
   44.18 + *     documentation and/or other materials provided with the distribution.
   44.19 + * 
   44.20 + *   - Neither the name of Oracle nor the names of its
   44.21 + *     contributors may be used to endorse or promote products derived
   44.22 + *     from this software without specific prior written permission.
   44.23 + * 
   44.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   44.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   44.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   44.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   44.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   44.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   44.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   44.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   44.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   44.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   44.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   44.35 + */
   44.36 +
   44.37 +// Logistic map viewer using Java8 Streams and JavaFX
   44.38 +// See also http://en.wikipedia.org/wiki/Logistic_map
   44.39 +
   44.40 +if (!$OPTIONS._fx || arguments.length < 2) {
   44.41 +    print("Usage: jjs -fx -scripting logisticmap.js -- <initial_x> <R>");
   44.42 +    exit(1);
   44.43 +}
   44.44 +
   44.45 +// parameters for the logistic map
   44.46 +var x = parseFloat(arguments[0]);
   44.47 +var R = parseFloat(arguments[1]);
   44.48 +var NUM_POINTS = arguments.length > 2? parseFloat(arguments[2]) : 20;
   44.49 +
   44.50 +// Java classes used
   44.51 +var DoubleStream = Java.type('java.util.stream.DoubleStream');
   44.52 +var LineChart = Java.type("javafx.scene.chart.LineChart");
   44.53 +var NumberAxis = Java.type("javafx.scene.chart.NumberAxis");
   44.54 +var Scene = Java.type("javafx.scene.Scene");
   44.55 +var Stage = Java.type("javafx.stage.Stage");
   44.56 +var XYChart = Java.type("javafx.scene.chart.XYChart");
   44.57 +
   44.58 +function start(stage) {
   44.59 +    stage.title = "Logistic Map: initial x = ${x}, R = ${R}";
   44.60 +    // make chart
   44.61 +    var xAxis = new NumberAxis();
   44.62 +    var yAxis = new NumberAxis();
   44.63 +    var lineChart = new LineChart(xAxis, yAxis);
   44.64 +    xAxis.setLabel("iteration");
   44.65 +    yAxis.setLabel("x");
   44.66 +    // make chart data series
   44.67 +    var series = new XYChart.Series();
   44.68 +    var data = series.data;
   44.69 +    // populate data using logistic iteration
   44.70 +    var i = 0;
   44.71 +    DoubleStream
   44.72 +        .generate(function() x = R*x*(1-x))
   44.73 +        .limit(NUM_POINTS)
   44.74 +        .forEach(
   44.75 +            function(value) {
   44.76 +                data.add(new XYChart.Data(i, value));
   44.77 +                i++;
   44.78 +            }
   44.79 +         );
   44.80 +    // add to stage
   44.81 +    var scene = new Scene(lineChart, 800, 600);
   44.82 +    lineChart.data.add(series);
   44.83 +    stage.scene = scene;
   44.84 +    stage.show();
   44.85 +}
    45.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    45.2 +++ b/samples/options.js	Wed May 14 11:02:04 2014 -0700
    45.3 @@ -0,0 +1,37 @@
    45.4 +#// Usage: jjs -scripting options.js
    45.5 +
    45.6 +/*
    45.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    45.8 + * 
    45.9 + * Redistribution and use in source and binary forms, with or without
   45.10 + * modification, are permitted provided that the following conditions
   45.11 + * are met:
   45.12 + * 
   45.13 + *   - Redistributions of source code must retain the above copyright
   45.14 + *     notice, this list of conditions and the following disclaimer.
   45.15 + * 
   45.16 + *   - Redistributions in binary form must reproduce the above copyright
   45.17 + *     notice, this list of conditions and the following disclaimer in the
   45.18 + *     documentation and/or other materials provided with the distribution.
   45.19 + * 
   45.20 + *   - Neither the name of Oracle nor the names of its
   45.21 + *     contributors may be used to endorse or promote products derived
   45.22 + *     from this software without specific prior written permission.
   45.23 + * 
   45.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   45.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   45.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   45.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   45.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   45.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   45.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   45.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   45.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   45.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   45.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   45.35 + */
   45.36 +
   45.37 +// print all option names and values
   45.38 +for (i in $OPTIONS) {
   45.39 +    print(i, '=', $OPTIONS[i]);
   45.40 +}
    46.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    46.2 +++ b/samples/readLine.js	Wed May 14 11:02:04 2014 -0700
    46.3 @@ -0,0 +1,38 @@
    46.4 +#// Usage: jjs -scripting greeting.js
    46.5 +
    46.6 +/*
    46.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    46.8 + * 
    46.9 + * Redistribution and use in source and binary forms, with or without
   46.10 + * modification, are permitted provided that the following conditions
   46.11 + * are met:
   46.12 + * 
   46.13 + *   - Redistributions of source code must retain the above copyright
   46.14 + *     notice, this list of conditions and the following disclaimer.
   46.15 + * 
   46.16 + *   - Redistributions in binary form must reproduce the above copyright
   46.17 + *     notice, this list of conditions and the following disclaimer in the
   46.18 + *     documentation and/or other materials provided with the distribution.
   46.19 + * 
   46.20 + *   - Neither the name of Oracle nor the names of its
   46.21 + *     contributors may be used to endorse or promote products derived
   46.22 + *     from this software without specific prior written permission.
   46.23 + * 
   46.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   46.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   46.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   46.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   46.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   46.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   46.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   46.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   46.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   46.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   46.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   46.35 + */
   46.36 +
   46.37 +// readLine prints prompt and reads user response
   46.38 +var name = readLine("Your name please: ");
   46.39 +
   46.40 +// user name is interpolated within string
   46.41 +print("Hello ${name}");
    47.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    47.2 +++ b/samples/sam_function.js	Wed May 14 11:02:04 2014 -0700
    47.3 @@ -0,0 +1,51 @@
    47.4 +/*
    47.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    47.6 + * 
    47.7 + * Redistribution and use in source and binary forms, with or without
    47.8 + * modification, are permitted provided that the following conditions
    47.9 + * are met:
   47.10 + * 
   47.11 + *   - Redistributions of source code must retain the above copyright
   47.12 + *     notice, this list of conditions and the following disclaimer.
   47.13 + * 
   47.14 + *   - Redistributions in binary form must reproduce the above copyright
   47.15 + *     notice, this list of conditions and the following disclaimer in the
   47.16 + *     documentation and/or other materials provided with the distribution.
   47.17 + * 
   47.18 + *   - Neither the name of Oracle nor the names of its
   47.19 + *     contributors may be used to endorse or promote products derived
   47.20 + *     from this software without specific prior written permission.
   47.21 + * 
   47.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   47.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   47.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   47.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   47.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   47.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   47.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   47.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   47.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   47.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   47.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   47.33 + */
   47.34 +
   47.35 +// nashorn supports passing script functions whenever
   47.36 +// a SAM (single abstract method) type object is expected
   47.37 +
   47.38 +var System = Java.type("java.lang.System");
   47.39 +var Timer = Java.type("java.util.Timer");
   47.40 +var timer = new Timer();
   47.41 +
   47.42 +// schedule method accepts java.util.TimerTask
   47.43 +// which is a single-abstract-method type. you
   47.44 +// can pass a script function and nashorn will
   47.45 +// wrap it as SAM implementor.
   47.46 +
   47.47 +timer.schedule(function() {
   47.48 +    print("Hello World!");
   47.49 +}, 1000);
   47.50 +
   47.51 +// wait for timer thread to print by
   47.52 +// reading from stdin. 
   47.53 +print("press any key to exit after message from timer...");
   47.54 +System.in.read();
    48.1 --- a/samples/shell.js	Tue May 13 23:18:50 2014 -0700
    48.2 +++ b/samples/shell.js	Wed May 14 11:02:04 2014 -0700
    48.3 @@ -1,5 +1,5 @@
    48.4  /*
    48.5 - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    48.6 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    48.7   * 
    48.8   * Redistribution and use in source and binary forms, with or without
    48.9   * modification, are permitted provided that the following conditions
   48.10 @@ -29,50 +29,53 @@
   48.11   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   48.12   */
   48.13  
   48.14 -/**
   48.15 - * This is a simple shell tool in JavaScript.
   48.16 +// Usage: jjs shell.js
   48.17 +
   48.18 +/* This is a simple shell tool in JavaScript.
   48.19   *
   48.20   * Runs any operating system command using Java "exec". When "eval" command is
   48.21   * used, evaluates argument(s) as JavaScript code.
   48.22   */
   48.23  
   48.24 -var imports = new JavaImporter(java.io, java.lang, java.util);
   48.25 +(function() {
   48.26 +    // Java classes used
   48.27 +    var Arrays = Java.type("java.util.Arrays");
   48.28 +    var BufferedReader = Java.type("java.io.BufferedReader");
   48.29 +    var InputStreamReader = Java.type("java.io.InputStreamReader");
   48.30 +    var ProcessBuilder = Java.type("java.lang.ProcessBuilder");
   48.31 +    var System = Java.type("java.lang.System");
   48.32  
   48.33 -function prompt() {
   48.34 -    java.lang.System.out.print(">");
   48.35 -}
   48.36 +    // print prompt
   48.37 +    function prompt() {
   48.38 +        System.out.print("> ");
   48.39 +    }
   48.40  
   48.41 -with (imports) {
   48.42 -    var reader = new BufferedReader(new InputStreamReader(System["in"]));
   48.43 -    var line = null;
   48.44 +    var reader = new BufferedReader(new InputStreamReader(System.in));
   48.45      prompt();
   48.46 -    while ((line = reader.readLine()) != null) {
   48.47 -        if (line != "") {
   48.48 -            var args = line.split(" ");
   48.49 +    // read and evaluate each line from stdin
   48.50 +    reader.lines().forEach(function(line) {
   48.51 +        if (! line.isEmpty()) {
   48.52 +            var args = line.split(' ');
   48.53              try {
   48.54 -                if (args[0] == "eval") {
   48.55 -                    var code = line.substring("eval".length);
   48.56 +                // special 'eval' command to evaluate JS code
   48.57 +                if (args[0] == 'eval') {
   48.58 +                    var code = line.substring('eval'.length);
   48.59                      var res = eval(code);
   48.60                      if (res != undefined) {
   48.61                          print(res);
   48.62                      }
   48.63                  } else {
   48.64 -                    var argList = new ArrayList();
   48.65 -                    for (i in args) { argList.add(args[i]); }                
   48.66 -                    var procBuilder = new ProcessBuilder(argList);
   48.67 -                    procBuilder.redirectErrorStream();
   48.68 -                    var proc = procBuilder.start();
   48.69 -                    var out = new BufferedReader(new InputStreamReader(proc.getInputStream()));
   48.70 -                    var line = null;
   48.71 -                    while ((line = out.readLine()) != null) {
   48.72 -                        System.out.println(line);
   48.73 -                    }
   48.74 -                    proc.waitFor();
   48.75 +                    // build child process and start it!
   48.76 +                    new ProcessBuilder(Arrays.asList(args))
   48.77 +                        .inheritIO()
   48.78 +                        .start()
   48.79 +                        .waitFor();
   48.80                  }
   48.81              } catch (e) {
   48.82 +                // print exception, if any
   48.83                  print(e);
   48.84              }
   48.85          }
   48.86          prompt();
   48.87 -    }
   48.88 -}
   48.89 +    })
   48.90 +})()
    49.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    49.2 +++ b/samples/stack.js	Wed May 14 11:02:04 2014 -0700
    49.3 @@ -0,0 +1,55 @@
    49.4 +/*
    49.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    49.6 + * 
    49.7 + * Redistribution and use in source and binary forms, with or without
    49.8 + * modification, are permitted provided that the following conditions
    49.9 + * are met:
   49.10 + * 
   49.11 + *   - Redistributions of source code must retain the above copyright
   49.12 + *     notice, this list of conditions and the following disclaimer.
   49.13 + * 
   49.14 + *   - Redistributions in binary form must reproduce the above copyright
   49.15 + *     notice, this list of conditions and the following disclaimer in the
   49.16 + *     documentation and/or other materials provided with the distribution.
   49.17 + * 
   49.18 + *   - Neither the name of Oracle nor the names of its
   49.19 + *     contributors may be used to endorse or promote products derived
   49.20 + *     from this software without specific prior written permission.
   49.21 + * 
   49.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   49.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   49.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   49.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   49.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   49.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   49.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   49.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   49.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   49.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   49.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   49.33 + */
   49.34 +
   49.35 +// nashorn supports 'stack' property on ECMAScript
   49.36 +// error objects. This property's value is a string
   49.37 +// that shows script stack trace.
   49.38 +
   49.39 +function g() { 
   49.40 +    throw new Error("wrong");
   49.41 +}
   49.42 +
   49.43 +function f() {
   49.44 +    g();
   49.45 +}
   49.46 +
   49.47 +// Output looks something like:
   49.48 +//
   49.49 +//  Error: wrong
   49.50 +//	at g (stack.js:37)
   49.51 +//	at f (stack.js:41)
   49.52 +//	at <program> (stack.js:52)
   49.53 +
   49.54 +try {
   49.55 +   f();
   49.56 +} catch (e) {
   49.57 +   print(e.stack);
   49.58 +}
    50.1 --- a/samples/test.js	Tue May 13 23:18:50 2014 -0700
    50.2 +++ b/samples/test.js	Wed May 14 11:02:04 2014 -0700
    50.3 @@ -30,4 +30,3 @@
    50.4   */
    50.5  
    50.6  print("Hello World");
    50.7 -
    51.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    51.2 +++ b/samples/uniform_random.js	Wed May 14 11:02:04 2014 -0700
    51.3 @@ -0,0 +1,49 @@
    51.4 +/*
    51.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    51.6 + * 
    51.7 + * Redistribution and use in source and binary forms, with or without
    51.8 + * modification, are permitted provided that the following conditions
    51.9 + * are met:
   51.10 + * 
   51.11 + *   - Redistributions of source code must retain the above copyright
   51.12 + *     notice, this list of conditions and the following disclaimer.
   51.13 + * 
   51.14 + *   - Redistributions in binary form must reproduce the above copyright
   51.15 + *     notice, this list of conditions and the following disclaimer in the
   51.16 + *     documentation and/or other materials provided with the distribution.
   51.17 + * 
   51.18 + *   - Neither the name of Oracle nor the names of its
   51.19 + *     contributors may be used to endorse or promote products derived
   51.20 + *     from this software without specific prior written permission.
   51.21 + * 
   51.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   51.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   51.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   51.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   51.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   51.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   51.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   51.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   51.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   51.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   51.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   51.33 + */
   51.34 +
   51.35 +// generate/print 100 uniformly distributed random values
   51.36 +// and print summary statistics on it
   51.37 +
   51.38 +var DoubleStream = Java.type("java.util.stream.DoubleStream");
   51.39 +
   51.40 +// pass script function when a lambda is required
   51.41 +// Math.random passed here for double generator lambda
   51.42 +// print passed to forEach method
   51.43 +
   51.44 +DoubleStream
   51.45 +    .generate(Math.random)
   51.46 +    .limit(100)
   51.47 +    .forEach(print);
   51.48 +
   51.49 +print(DoubleStream
   51.50 +    .generate(Math.random)
   51.51 +    .limit(100)
   51.52 +    .summaryStatistics());
    52.1 --- a/samples/uniq.js	Tue May 13 23:18:50 2014 -0700
    52.2 +++ b/samples/uniq.js	Wed May 14 11:02:04 2014 -0700
    52.3 @@ -1,5 +1,5 @@
    52.4  /*
    52.5 - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    52.6 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    52.7   * 
    52.8   * Redistribution and use in source and binary forms, with or without
    52.9   * modification, are permitted provided that the following conditions
   52.10 @@ -29,27 +29,28 @@
   52.11   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   52.12   */
   52.13  
   52.14 -/**
   52.15 - * Prints unique lines from a given file.
   52.16 - */
   52.17 +// Usage: jjs uniq.js
   52.18 +// or: jjs uniq.js -- <file>
   52.19  
   52.20 -if (arguments.length != 1) {
   52.21 -    print("Usage: jjs uniq.js -- <file>");
   52.22 -    java.lang.System.exit(1);
   52.23 +// omit repeated lines and print unique lines
   52.24 +
   52.25 +var BufferedReader = Java.type("java.io.BufferedReader");
   52.26 +var FileReader = Java.type("java.io.FileReader");
   52.27 +var InputStreamReader = Java.type("java.io.InputStreamReader");
   52.28 +var System = Java.type("java.lang.System");
   52.29 +
   52.30 +// use object as set - but insertion order preserved
   52.31 +var uniqueLines = {};
   52.32 +var reader = arguments.length > 0 ?
   52.33 +    new FileReader(arguments[0])  :
   52.34 +    new InputStreamReader(System.in);
   52.35 +reader = new BufferedReader(reader);
   52.36 +
   52.37 +// add unique lines
   52.38 +reader.lines().forEach(function(line) {
   52.39 +    uniqueLines[line] = true;
   52.40 +})
   52.41 +
   52.42 +for (line in uniqueLines) {
   52.43 +    print(line);
   52.44  }
   52.45 -
   52.46 -var imports = new JavaImporter(java.io);
   52.47 -
   52.48 -var uniqueLines = {};
   52.49 -with (imports) {
   52.50 -    var reader = new BufferedReader(new FileReader(arguments[0]));
   52.51 -    while ((line = reader.readLine()) != null) {
   52.52 -        // using a JS object as a map...
   52.53 -        uniqueLines[line] = true;
   52.54 -    }
   52.55 -}
   52.56 -
   52.57 -// now print the collected lines
   52.58 -for (i in uniqueLines) {
   52.59 -    print(i);
   52.60 -}
    53.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    53.2 +++ b/samples/uniqs.js	Wed May 14 11:02:04 2014 -0700
    53.3 @@ -0,0 +1,48 @@
    53.4 +/*
    53.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    53.6 + * 
    53.7 + * Redistribution and use in source and binary forms, with or without
    53.8 + * modification, are permitted provided that the following conditions
    53.9 + * are met:
   53.10 + * 
   53.11 + *   - Redistributions of source code must retain the above copyright
   53.12 + *     notice, this list of conditions and the following disclaimer.
   53.13 + * 
   53.14 + *   - Redistributions in binary form must reproduce the above copyright
   53.15 + *     notice, this list of conditions and the following disclaimer in the
   53.16 + *     documentation and/or other materials provided with the distribution.
   53.17 + * 
   53.18 + *   - Neither the name of Oracle nor the names of its
   53.19 + *     contributors may be used to endorse or promote products derived
   53.20 + *     from this software without specific prior written permission.
   53.21 + * 
   53.22 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   53.23 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   53.24 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   53.25 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   53.26 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   53.27 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   53.28 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   53.29 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   53.30 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   53.31 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   53.32 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   53.33 + */
   53.34 +
   53.35 +// Usage: jjs uniqs.js -- <file>
   53.36 +// omit repeated lines and print unique lines
   53.37 +// But this version uses Stream API 
   53.38 +
   53.39 +if (arguments.length < 1) {
   53.40 +    print("Usage: jjs uniqs.js -- <file>");
   53.41 +    exit(1);
   53.42 +}
   53.43 +
   53.44 +var Files = Java.type("java.nio.file.Files");
   53.45 +var FileSystems = Java.type("java.nio.file.FileSystems");
   53.46 +print('Unique lines:',
   53.47 +   Files
   53.48 +    .lines(FileSystems.default.getPath(arguments[0]))
   53.49 +    .distinct()
   53.50 +    .peek(print)
   53.51 +    .count());
    54.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    54.2 +++ b/samples/weather.js	Wed May 14 11:02:04 2014 -0700
    54.3 @@ -0,0 +1,63 @@
    54.4 +#// usage: jjs -scripting weather.js
    54.5 +
    54.6 +/*
    54.7 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    54.8 + * 
    54.9 + * Redistribution and use in source and binary forms, with or without
   54.10 + * modification, are permitted provided that the following conditions
   54.11 + * are met:
   54.12 + * 
   54.13 + *   - Redistributions of source code must retain the above copyright
   54.14 + *     notice, this list of conditions and the following disclaimer.
   54.15 + * 
   54.16 + *   - Redistributions in binary form must reproduce the above copyright
   54.17 + *     notice, this list of conditions and the following disclaimer in the
   54.18 + *     documentation and/or other materials provided with the distribution.
   54.19 + * 
   54.20 + *   - Neither the name of Oracle nor the names of its
   54.21 + *     contributors may be used to endorse or promote products derived
   54.22 + *     from this software without specific prior written permission.
   54.23 + * 
   54.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   54.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
   54.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   54.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   54.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   54.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   54.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   54.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   54.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   54.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   54.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   54.35 + */
   54.36 +
   54.37 +// Simple nashorn example showing back-quote exec process,
   54.38 +// JSON and Java8 streams
   54.39 +
   54.40 +var Arrays = Java.type("java.util.Arrays");
   54.41 +
   54.42 +// use curl to download JSON weather data from the net
   54.43 +// use backquote -scripting mode syntax to exec a process
   54.44 +
   54.45 +`curl http://api.openweathermap.org/data/2.5/forecast/daily?q=Chennai&amp;mode=json&amp;units=metric&amp;cnt=7`;
   54.46 +
   54.47 +// parse JSON
   54.48 +var weather = JSON.parse($OUT);
   54.49 +
   54.50 +// pull out humidity as array
   54.51 +var humidity = weather.list.map(function(curVal) {
   54.52 +    return curVal.humidity;
   54.53 +})
   54.54 +
   54.55 +// Stream API to print stat
   54.56 +print("Humidity");
   54.57 +print(Arrays["stream(int[])"](humidity).summaryStatistics());
   54.58 +
   54.59 +// pull maximum day time temperature
   54.60 +var temp = weather.list.map(function(curVal) {
   54.61 +    return curVal.temp.max;
   54.62 +});
   54.63 +
   54.64 +// Stream API to print stat
   54.65 +print("Max Temperature");
   54.66 +print(Arrays["stream(double[])"](temp).summaryStatistics());
    55.1 --- a/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Tue May 13 23:18:50 2014 -0700
    55.2 +++ b/src/jdk/nashorn/api/scripting/NashornScriptEngine.java	Wed May 14 11:02:04 2014 -0700
    55.3 @@ -27,16 +27,14 @@
    55.4  
    55.5  import static jdk.nashorn.internal.runtime.ECMAErrors.referenceError;
    55.6  import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
    55.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    55.8  
    55.9  import java.io.IOException;
   55.10 -import java.io.InputStream;
   55.11 -import java.io.InputStreamReader;
   55.12  import java.io.Reader;
   55.13  import java.lang.invoke.MethodHandles;
   55.14  import java.lang.reflect.Method;
   55.15  import java.lang.reflect.Modifier;
   55.16  import java.net.URL;
   55.17 -import java.nio.charset.Charset;
   55.18  import java.security.AccessControlContext;
   55.19  import java.security.AccessController;
   55.20  import java.security.Permissions;
   55.21 @@ -124,21 +122,21 @@
   55.22          }
   55.23      }
   55.24  
   55.25 -    // load engine.js and return content as a char[]
   55.26 +    // load engine.js
   55.27      @SuppressWarnings("resource")
   55.28 -    private static char[] loadEngineJSSource() {
   55.29 +    private static Source loadEngineJSSource() {
   55.30          final String script = "resources/engine.js";
   55.31          try {
   55.32 -            final InputStream is = AccessController.doPrivileged(
   55.33 -                    new PrivilegedExceptionAction<InputStream>() {
   55.34 +            return AccessController.doPrivileged(
   55.35 +                    new PrivilegedExceptionAction<Source>() {
   55.36                          @Override
   55.37 -                        public InputStream run() throws Exception {
   55.38 +                        public Source run() throws IOException {
   55.39                              final URL url = NashornScriptEngine.class.getResource(script);
   55.40 -                            return url.openStream();
   55.41 +                            return sourceFor(NashornException.ENGINE_SCRIPT_SOURCE_NAME, url);
   55.42                          }
   55.43 -                    });
   55.44 -            return Source.readFully(new InputStreamReader(is));
   55.45 -        } catch (final PrivilegedActionException | IOException e) {
   55.46 +                    }
   55.47 +            );
   55.48 +        } catch (final PrivilegedActionException e) {
   55.49              if (Context.DEBUG) {
   55.50                  e.printStackTrace();
   55.51              }
   55.52 @@ -147,7 +145,7 @@
   55.53      }
   55.54  
   55.55      // Source object for engine.js
   55.56 -    private static final Source ENGINE_SCRIPT_SRC = new Source(NashornException.ENGINE_SCRIPT_SOURCE_NAME, loadEngineJSSource());
   55.57 +    private static final Source ENGINE_SCRIPT_SRC = loadEngineJSSource();
   55.58  
   55.59      NashornScriptEngine(final NashornScriptEngineFactory factory, final ClassLoader appLoader) {
   55.60          this(factory, DEFAULT_OPTIONS, appLoader);
   55.61 @@ -282,19 +280,14 @@
   55.62  
   55.63      private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException {
   55.64          try {
   55.65 -            if (reader instanceof URLReader) {
   55.66 -                final URL url = ((URLReader)reader).getURL();
   55.67 -                final Charset cs = ((URLReader)reader).getCharset();
   55.68 -                return new Source(url.toString(), url, cs);
   55.69 -            }
   55.70 -            return new Source(getScriptName(ctxt), Source.readFully(reader));
   55.71 -        } catch (final IOException e) {
   55.72 +            return sourceFor(getScriptName(ctxt), reader);
   55.73 +        } catch (IOException e) {
   55.74              throw new ScriptException(e);
   55.75          }
   55.76      }
   55.77  
   55.78      private static Source makeSource(final String src, final ScriptContext ctxt) {
   55.79 -        return new Source(getScriptName(ctxt), src);
   55.80 +        return sourceFor(getScriptName(ctxt), src);
   55.81      }
   55.82  
   55.83      private static String getScriptName(final ScriptContext ctxt) {
   55.84 @@ -532,6 +525,31 @@
   55.85          return evalImpl(script, ctxt, getNashornGlobalFrom(ctxt));
   55.86      }
   55.87  
   55.88 +    private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
   55.89 +        final Global oldGlobal = Context.getGlobal();
   55.90 +        final boolean globalChanged = (oldGlobal != ctxtGlobal);
   55.91 +        try {
   55.92 +            if (globalChanged) {
   55.93 +                Context.setGlobal(ctxtGlobal);
   55.94 +            }
   55.95 +
   55.96 +            final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
   55.97 +
   55.98 +            // set ScriptContext variables if ctxt is non-null
   55.99 +            if (ctxt != null) {
  55.100 +                setContextVariables(ctxtGlobal, ctxt);
  55.101 +            }
  55.102 +            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
  55.103 +        } catch (final Exception e) {
  55.104 +            throwAsScriptException(e, ctxtGlobal);
  55.105 +            throw new AssertionError("should not reach here");
  55.106 +        } finally {
  55.107 +            if (globalChanged) {
  55.108 +                Context.setGlobal(oldGlobal);
  55.109 +            }
  55.110 +        }
  55.111 +    }
  55.112 +
  55.113      private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
  55.114          if (script == null) {
  55.115              return null;
  55.116 @@ -578,18 +596,38 @@
  55.117      }
  55.118  
  55.119      private CompiledScript asCompiledScript(final Source source) throws ScriptException {
  55.120 -        final ScriptFunction func = compileImpl(source, context);
  55.121 +        final Context.MultiGlobalCompiledScript mgcs;
  55.122 +        final ScriptFunction func;
  55.123 +        final Global oldGlobal = Context.getGlobal();
  55.124 +        final Global newGlobal = getNashornGlobalFrom(context);
  55.125 +        final boolean globalChanged = (oldGlobal != newGlobal);
  55.126 +        try {
  55.127 +            if (globalChanged) {
  55.128 +                Context.setGlobal(newGlobal);
  55.129 +            }
  55.130 +
  55.131 +            mgcs = nashornContext.compileScript(source);
  55.132 +            func = mgcs.getFunction(newGlobal);
  55.133 +        } catch (final Exception e) {
  55.134 +            throwAsScriptException(e, newGlobal);
  55.135 +            throw new AssertionError("should not reach here");
  55.136 +        } finally {
  55.137 +            if (globalChanged) {
  55.138 +                Context.setGlobal(oldGlobal);
  55.139 +            }
  55.140 +        }
  55.141 +
  55.142          return new CompiledScript() {
  55.143              @Override
  55.144              public Object eval(final ScriptContext ctxt) throws ScriptException {
  55.145                  final Global globalObject = getNashornGlobalFrom(ctxt);
  55.146 -                // Are we running the script in the correct global?
  55.147 +                // Are we running the script in the same global in which it was compiled?
  55.148                  if (func.getScope() == globalObject) {
  55.149                      return evalImpl(func, ctxt, globalObject);
  55.150                  }
  55.151 -                // ScriptContext with a different global. Compile again!
  55.152 -                // Note that we may still hit per-global compilation cache.
  55.153 -                return evalImpl(compileImpl(source, ctxt), ctxt, globalObject);
  55.154 +
  55.155 +                // different global
  55.156 +                return evalImpl(mgcs, ctxt, globalObject);
  55.157              }
  55.158              @Override
  55.159              public ScriptEngine getEngine() {
    56.1 --- a/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Tue May 13 23:18:50 2014 -0700
    56.2 +++ b/src/jdk/nashorn/internal/codegen/CodeGenerator.java	Wed May 14 11:02:04 2014 -0700
    56.3 @@ -1451,7 +1451,10 @@
    56.4  
    56.5              if (value == null) {
    56.6                  hasGettersSetters = true;
    56.7 -            } else if (key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
    56.8 +            } else if (propertyNode.getKey() instanceof IdentNode &&
    56.9 +                       key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
   56.10 +                // ES6 draft compliant __proto__ inside object literal
   56.11 +                // Identifier key and name is __proto__
   56.12                  protoNode = value;
   56.13                  continue;
   56.14              }
    57.1 --- a/src/jdk/nashorn/internal/ir/debug/JSONWriter.java	Tue May 13 23:18:50 2014 -0700
    57.2 +++ b/src/jdk/nashorn/internal/ir/debug/JSONWriter.java	Wed May 14 11:02:04 2014 -0700
    57.3 @@ -25,6 +25,8 @@
    57.4  
    57.5  package jdk.nashorn.internal.ir.debug;
    57.6  
    57.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    57.8 +
    57.9  import java.util.Arrays;
   57.10  import java.util.List;
   57.11  import java.util.ArrayList;
   57.12 @@ -88,7 +90,7 @@
   57.13       * @return JSON string representation of AST of the supplied code
   57.14       */
   57.15      public static String parse(final ScriptEnvironment env, final String code, final String name, final boolean includeLoc) {
   57.16 -        final Parser       parser     = new Parser(env, new Source(name, code), new Context.ThrowErrorManager(), env._strict);
   57.17 +        final Parser       parser     = new Parser(env, sourceFor(name, code), new Context.ThrowErrorManager(), env._strict);
   57.18          final JSONWriter   jsonWriter = new JSONWriter(includeLoc);
   57.19          try {
   57.20              final FunctionNode functionNode = parser.parse(CompilerConstants.RUN_SCRIPT.symbolName());
    58.1 --- a/src/jdk/nashorn/internal/objects/Global.java	Tue May 13 23:18:50 2014 -0700
    58.2 +++ b/src/jdk/nashorn/internal/objects/Global.java	Wed May 14 11:02:04 2014 -0700
    58.3 @@ -1906,6 +1906,13 @@
    58.4          // Object.getPrototypeOf(Function.prototype) === Object.prototype
    58.5          anon.setInitialProto(ObjectPrototype);
    58.6  
    58.7 +        // ES6 draft compliant __proto__ property of Object.prototype
    58.8 +        // accessors on Object.prototype for "__proto__"
    58.9 +        final ScriptFunction getProto = ScriptFunctionImpl.makeFunction("getProto", ScriptObject.GETPROTO);
   58.10 +        final ScriptFunction setProto = ScriptFunctionImpl.makeFunction("setProto", ScriptObject.SETPROTOCHECK);
   58.11 +        ObjectPrototype.addOwnProperty("__proto__", Attribute.NOT_ENUMERABLE, getProto, setProto);
   58.12 +
   58.13 +
   58.14          // Function valued properties of Function.prototype were not properly
   58.15          // initialized. Because, these were created before global.function and
   58.16          // global.object were not initialized.
    59.1 --- a/src/jdk/nashorn/internal/objects/NativeFunction.java	Tue May 13 23:18:50 2014 -0700
    59.2 +++ b/src/jdk/nashorn/internal/objects/NativeFunction.java	Wed May 14 11:02:04 2014 -0700
    59.3 @@ -27,6 +27,7 @@
    59.4  
    59.5  import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
    59.6  import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
    59.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    59.8  
    59.9  import java.util.List;
   59.10  
   59.11 @@ -257,7 +258,7 @@
   59.12      }
   59.13  
   59.14      private static void checkFunctionParameters(final String params) {
   59.15 -        final Source src = new Source("<function>", params);
   59.16 +        final Source src = sourceFor("<function>", params);
   59.17          final Parser parser = new Parser(Global.getEnv(), src, new Context.ThrowErrorManager());
   59.18          try {
   59.19              parser.parseFormalParameterList();
   59.20 @@ -267,7 +268,7 @@
   59.21      }
   59.22  
   59.23      private static void checkFunctionBody(final String funcBody) {
   59.24 -        final Source src = new Source("<function>", funcBody);
   59.25 +        final Source src = sourceFor("<function>", funcBody);
   59.26          final Parser parser = new Parser(Global.getEnv(), src, new Context.ThrowErrorManager());
   59.27          try {
   59.28              parser.parseFunctionBody();
    60.1 --- a/src/jdk/nashorn/internal/parser/Parser.java	Tue May 13 23:18:50 2014 -0700
    60.2 +++ b/src/jdk/nashorn/internal/parser/Parser.java	Wed May 14 11:02:04 2014 -0700
    60.3 @@ -33,6 +33,7 @@
    60.4  import static jdk.nashorn.internal.parser.TokenType.CATCH;
    60.5  import static jdk.nashorn.internal.parser.TokenType.COLON;
    60.6  import static jdk.nashorn.internal.parser.TokenType.COMMARIGHT;
    60.7 +import static jdk.nashorn.internal.parser.TokenType.CONST;
    60.8  import static jdk.nashorn.internal.parser.TokenType.DECPOSTFIX;
    60.9  import static jdk.nashorn.internal.parser.TokenType.DECPREFIX;
   60.10  import static jdk.nashorn.internal.parser.TokenType.ELSE;
   60.11 @@ -849,6 +850,11 @@
   60.12              expect(SEMICOLON);
   60.13              break;
   60.14          default:
   60.15 +            if (env._const_as_var && type == CONST) {
   60.16 +                variableStatement(true);
   60.17 +                break;
   60.18 +            }
   60.19 +
   60.20              if (type == IDENT || isNonStrictModeIdent()) {
   60.21                  if (T(k + 1) == COLON) {
   60.22                      labelStatement();
   60.23 @@ -1110,6 +1116,12 @@
   60.24              case SEMICOLON:
   60.25                  break;
   60.26              default:
   60.27 +                if (env._const_as_var && type == CONST) {
   60.28 +                    // Var statements captured in for outer block.
   60.29 +                    vars = variableStatement(false);
   60.30 +                    break;
   60.31 +                }
   60.32 +
   60.33                  final Expression expression = expression(unaryExpression(), COMMARIGHT.getPrecedence(), true);
   60.34                  forNode = forNode.setInit(lc, expression);
   60.35                  break;
    61.1 --- a/src/jdk/nashorn/internal/parser/TokenType.java	Tue May 13 23:18:50 2014 -0700
    61.2 +++ b/src/jdk/nashorn/internal/parser/TokenType.java	Wed May 14 11:02:04 2014 -0700
    61.3 @@ -111,7 +111,7 @@
    61.4      CATCH          (KEYWORD,  "catch"),
    61.5  //  CHAR           (FUTURE,   "char"),
    61.6      CLASS          (FUTURE,   "class"),
    61.7 -    CONST          (FUTURE,  "const"),
    61.8 +    CONST          (KEYWORD,  "const"),
    61.9      CONTINUE       (KEYWORD,  "continue"),
   61.10      DEBUGGER       (KEYWORD,  "debugger"),
   61.11      DEFAULT        (KEYWORD,  "default"),
    62.1 --- a/src/jdk/nashorn/internal/runtime/Context.java	Tue May 13 23:18:50 2014 -0700
    62.2 +++ b/src/jdk/nashorn/internal/runtime/Context.java	Wed May 14 11:02:04 2014 -0700
    62.3 @@ -32,6 +32,7 @@
    62.4  import static jdk.nashorn.internal.lookup.Lookup.MH;
    62.5  import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
    62.6  import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
    62.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    62.8  
    62.9  import java.io.File;
   62.10  import java.io.IOException;
   62.11 @@ -490,6 +491,39 @@
   62.12      }
   62.13  
   62.14      /**
   62.15 +     * Interface to represent compiled code that can be re-used across many
   62.16 +     * global scope instances
   62.17 +     */
   62.18 +    public static interface MultiGlobalCompiledScript {
   62.19 +        /**
   62.20 +         * Obtain script function object for a specific global scope object.
   62.21 +         *
   62.22 +         * @param newGlobal global scope for which function object is obtained
   62.23 +         * @return script function for script level expressions
   62.24 +         */
   62.25 +        public ScriptFunction getFunction(final Global newGlobal);
   62.26 +    }
   62.27 +
   62.28 +    /**
   62.29 +     * Compile a top level script.
   62.30 +     *
   62.31 +     * @param source the script source
   62.32 +     * @return reusable compiled script across many global scopes.
   62.33 +     */
   62.34 +    public MultiGlobalCompiledScript compileScript(final Source source) {
   62.35 +        final Class<?> clazz = compile(source, this.errors, this._strict);
   62.36 +        final MethodHandle runMethodHandle = getRunScriptHandle(clazz);
   62.37 +        final boolean strict = isStrict(clazz);
   62.38 +
   62.39 +        return new MultiGlobalCompiledScript() {
   62.40 +            @Override
   62.41 +            public ScriptFunction getFunction(final Global newGlobal) {
   62.42 +                return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, newGlobal, strict);
   62.43 +            }
   62.44 +        };
   62.45 +    }
   62.46 +
   62.47 +    /**
   62.48       * Entry point for {@code eval}
   62.49       *
   62.50       * @param initialScope The scope of this eval call
   62.51 @@ -502,7 +536,7 @@
   62.52       */
   62.53      public Object eval(final ScriptObject initialScope, final String string, final Object callThis, final Object location, final boolean strict) {
   62.54          final String  file       = (location == UNDEFINED || location == null) ? "<eval>" : location.toString();
   62.55 -        final Source  source     = new Source(file, string);
   62.56 +        final Source  source     = sourceFor(file, string);
   62.57          final boolean directEval = location != UNDEFINED; // is this direct 'eval' call or indirectly invoked eval?
   62.58          final Global  global = Context.getGlobal();
   62.59  
   62.60 @@ -569,7 +603,7 @@
   62.61                          public Source run() {
   62.62                              try {
   62.63                                  final URL resURL = Context.class.getResource(resource);
   62.64 -                                return (resURL != null)? new Source(srcStr, resURL) : null;
   62.65 +                                return (resURL != null)? sourceFor(srcStr, resURL) : null;
   62.66                              } catch (final IOException exp) {
   62.67                                  return null;
   62.68                              }
   62.69 @@ -601,7 +635,7 @@
   62.70              final String srcStr = (String)src;
   62.71              if (srcStr.startsWith(LOAD_CLASSPATH)) {
   62.72                  URL url = getResourceURL(srcStr.substring(LOAD_CLASSPATH.length()));
   62.73 -                source = (url != null)? new Source(url.toString(), url) : null;
   62.74 +                source = (url != null)? sourceFor(url.toString(), url) : null;
   62.75              } else {
   62.76                  final File file = new File(srcStr);
   62.77                  if (srcStr.indexOf(':') != -1) {
   62.78 @@ -614,31 +648,31 @@
   62.79                          } catch (final MalformedURLException e) {
   62.80                              url = file.toURI().toURL();
   62.81                          }
   62.82 -                        source = new Source(url.toString(), url);
   62.83 +                        source = sourceFor(url.toString(), url);
   62.84                      }
   62.85                  } else if (file.isFile()) {
   62.86 -                    source = new Source(srcStr, file);
   62.87 +                    source = sourceFor(srcStr, file);
   62.88                  }
   62.89              }
   62.90          } else if (src instanceof File && ((File)src).isFile()) {
   62.91              final File file = (File)src;
   62.92 -            source = new Source(file.getName(), file);
   62.93 +            source = sourceFor(file.getName(), file);
   62.94          } else if (src instanceof URL) {
   62.95              final URL url = (URL)src;
   62.96 -            source = new Source(url.toString(), url);
   62.97 +            source = sourceFor(url.toString(), url);
   62.98          } else if (src instanceof ScriptObject) {
   62.99              final ScriptObject sobj = (ScriptObject)src;
  62.100              if (sobj.has("script") && sobj.has("name")) {
  62.101                  final String script = JSType.toString(sobj.get("script"));
  62.102                  final String name   = JSType.toString(sobj.get("name"));
  62.103 -                source = new Source(name, script);
  62.104 +                source = sourceFor(name, script);
  62.105              }
  62.106          } else if (src instanceof Map) {
  62.107              final Map<?,?> map = (Map<?,?>)src;
  62.108              if (map.containsKey("script") && map.containsKey("name")) {
  62.109                  final String script = JSType.toString(map.get("script"));
  62.110                  final String name   = JSType.toString(map.get("name"));
  62.111 -                source = new Source(name, script);
  62.112 +                source = sourceFor(name, script);
  62.113              }
  62.114          }
  62.115  
  62.116 @@ -949,14 +983,8 @@
  62.117          return ScriptRuntime.apply(script, thiz);
  62.118      }
  62.119  
  62.120 -    private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
  62.121 -        if (script == null) {
  62.122 -            return null;
  62.123 -        }
  62.124 -
  62.125 -        // Get run method - the entry point to the script
  62.126 -        final MethodHandle runMethodHandle =
  62.127 -                MH.findStatic(
  62.128 +    private static MethodHandle getRunScriptHandle(final Class<?> script) {
  62.129 +        return MH.findStatic(
  62.130                      MethodHandles.lookup(),
  62.131                      script,
  62.132                      RUN_SCRIPT.symbolName(),
  62.133 @@ -964,15 +992,25 @@
  62.134                          Object.class,
  62.135                          ScriptFunction.class,
  62.136                          Object.class));
  62.137 +    }
  62.138  
  62.139 -        boolean strict;
  62.140 +    private static boolean isStrict(final Class<?> script) {
  62.141 +        try {
  62.142 +            return script.getField(STRICT_MODE.symbolName()).getBoolean(null);
  62.143 +        } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
  62.144 +            return false;
  62.145 +        }
  62.146 +    }
  62.147  
  62.148 -        try {
  62.149 -            strict = script.getField(STRICT_MODE.symbolName()).getBoolean(null);
  62.150 -        } catch (final NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
  62.151 -            strict = false;
  62.152 +    private static ScriptFunction getRunScriptFunction(final Class<?> script, final ScriptObject scope) {
  62.153 +        if (script == null) {
  62.154 +            return null;
  62.155          }
  62.156  
  62.157 +        // Get run method - the entry point to the script
  62.158 +        final MethodHandle runMethodHandle = getRunScriptHandle(script);
  62.159 +        boolean strict = isStrict(script);
  62.160 +
  62.161          // Package as a JavaScript function and pass function back to shell.
  62.162          return Context.getGlobal().newScriptFunction(RUN_SCRIPT.symbolName(), runMethodHandle, scope, strict);
  62.163      }
    63.1 --- a/src/jdk/nashorn/internal/runtime/JSONFunctions.java	Tue May 13 23:18:50 2014 -0700
    63.2 +++ b/src/jdk/nashorn/internal/runtime/JSONFunctions.java	Wed May 14 11:02:04 2014 -0700
    63.3 @@ -39,6 +39,8 @@
    63.4  import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
    63.5  import jdk.nashorn.internal.runtime.linker.Bootstrap;
    63.6  
    63.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    63.8 +
    63.9  /**
   63.10   * Utilities used by "JSON" object implementation.
   63.11   */
   63.12 @@ -77,9 +79,7 @@
   63.13       */
   63.14      public static Object parse(final Object text, final Object reviver) {
   63.15          final String     str     = JSType.toString(text);
   63.16 -        final JSONParser parser  = new JSONParser(
   63.17 -                new Source("<json>", str),
   63.18 -                new Context.ThrowErrorManager());
   63.19 +        final JSONParser parser  = new JSONParser(sourceFor("<json>", str), new Context.ThrowErrorManager());
   63.20  
   63.21          Node node;
   63.22  
    64.1 --- a/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java	Tue May 13 23:18:50 2014 -0700
    64.2 +++ b/src/jdk/nashorn/internal/runtime/ScriptEnvironment.java	Wed May 14 11:02:04 2014 -0700
    64.3 @@ -62,6 +62,9 @@
    64.4      /** Only compile script, do not run it or generate other ScriptObjects */
    64.5      public final boolean _compile_only;
    64.6  
    64.7 +    /** Accept "const" keyword and treat it as variable. Interim feature */
    64.8 +    public final boolean _const_as_var;
    64.9 +
   64.10      /** Accumulated callsite flags that will be used when bootstrapping script callsites */
   64.11      public final int     _callsite_flags;
   64.12  
   64.13 @@ -200,6 +203,7 @@
   64.14  
   64.15          _class_cache_size     = options.getInteger("class.cache.size");
   64.16          _compile_only         = options.getBoolean("compile.only");
   64.17 +        _const_as_var         = options.getBoolean("const.as.var");
   64.18          _debug_lines          = options.getBoolean("debug.lines");
   64.19          _dest_dir             = options.getString("d");
   64.20          _dump_on_error        = options.getBoolean("doe");
    65.1 --- a/src/jdk/nashorn/internal/runtime/ScriptObject.java	Tue May 13 23:18:50 2014 -0700
    65.2 +++ b/src/jdk/nashorn/internal/runtime/ScriptObject.java	Wed May 14 11:02:04 2014 -0700
    65.3 @@ -91,7 +91,7 @@
    65.4   */
    65.5  
    65.6  public abstract class ScriptObject implements PropertyAccess {
    65.7 -    /** __proto__ special property name */
    65.8 +    /** __proto__ special property name inside object literals. ES6 draft. */
    65.9      public static final String PROTO_PROPERTY_NAME   = "__proto__";
   65.10  
   65.11      /** Search fall back routine name for "no such method" */
   65.12 @@ -130,8 +130,10 @@
   65.13      /** Indexed array data. */
   65.14      private ArrayData arrayData;
   65.15  
   65.16 -    static final MethodHandle GETPROTO           = findOwnMH("getProto", ScriptObject.class);
   65.17 -    static final MethodHandle SETPROTOCHECK      = findOwnMH("setProtoCheck", void.class, Object.class);
   65.18 +    /** Method handle to retrive prototype of this object */
   65.19 +    public static final MethodHandle GETPROTO           = findOwnMH("getProto", ScriptObject.class);
   65.20 +    /** Method handle to set prototype of this object */
   65.21 +    public static final MethodHandle SETPROTOCHECK      = findOwnMH("setProtoCheck", void.class, Object.class);
   65.22      static final MethodHandle MEGAMORPHIC_GET    = findOwnMH("megamorphicGet", Object.class, String.class, boolean.class, boolean.class);
   65.23      static final MethodHandle GLOBALFILTER       = findOwnMH("globalFilter", Object.class, Object.class);
   65.24  
   65.25 @@ -1732,10 +1734,6 @@
   65.26          MethodHandle methodHandle;
   65.27  
   65.28          if (find == null) {
   65.29 -            if (PROTO_PROPERTY_NAME.equals(name)) {
   65.30 -                return new GuardedInvocation(GETPROTO, NashornGuards.getScriptObjectGuard());
   65.31 -            }
   65.32 -
   65.33              if ("getProp".equals(operator)) {
   65.34                  return noSuchProperty(desc, request);
   65.35              } else if ("getMethod".equals(operator)) {
   65.36 @@ -1890,9 +1888,7 @@
   65.37                  return createEmptySetMethod(desc, "property.not.writable", true);
   65.38              }
   65.39          } else {
   65.40 -            if (PROTO_PROPERTY_NAME.equals(name)) {
   65.41 -                return new GuardedInvocation(SETPROTOCHECK, NashornGuards.getScriptObjectGuard());
   65.42 -            } else if (! isExtensible()) {
   65.43 +            if (! isExtensible()) {
   65.44                  return createEmptySetMethod(desc, "object.non.extensible", false);
   65.45              }
   65.46          }
    66.1 --- a/src/jdk/nashorn/internal/runtime/Source.java	Tue May 13 23:18:50 2014 -0700
    66.2 +++ b/src/jdk/nashorn/internal/runtime/Source.java	Wed May 14 11:02:04 2014 -0700
    66.3 @@ -27,13 +27,16 @@
    66.4  
    66.5  import java.io.ByteArrayOutputStream;
    66.6  import java.io.File;
    66.7 +import java.io.FileNotFoundException;
    66.8  import java.io.IOError;
    66.9  import java.io.IOException;
   66.10  import java.io.InputStream;
   66.11  import java.io.Reader;
   66.12 +import java.lang.ref.WeakReference;
   66.13  import java.net.MalformedURLException;
   66.14  import java.net.URISyntaxException;
   66.15  import java.net.URL;
   66.16 +import java.net.URLConnection;
   66.17  import java.nio.charset.Charset;
   66.18  import java.nio.charset.StandardCharsets;
   66.19  import java.nio.file.Files;
   66.20 @@ -43,13 +46,19 @@
   66.21  import java.security.NoSuchAlgorithmException;
   66.22  import java.util.Arrays;
   66.23  import java.util.Objects;
   66.24 +import java.util.WeakHashMap;
   66.25 +import jdk.nashorn.api.scripting.URLReader;
   66.26  import jdk.nashorn.internal.parser.Token;
   66.27  
   66.28  /**
   66.29   * Source objects track the origin of JavaScript entities.
   66.30 - *
   66.31   */
   66.32  public final class Source {
   66.33 +
   66.34 +    private static final DebugLogger DEBUG = new DebugLogger("source");
   66.35 +    private static final int BUF_SIZE = 8 * 1024;
   66.36 +    private static final Cache CACHE = new Cache();
   66.37 +
   66.38      /**
   66.39       * Descriptive name of the source as supplied by the user. Used for error
   66.40       * reporting to the user. For example, SyntaxError will use this to print message.
   66.41 @@ -64,11 +73,8 @@
   66.42       */
   66.43      private final String base;
   66.44  
   66.45 -    /** Cached source content. */
   66.46 -    private final char[] content;
   66.47 -
   66.48 -    /** Length of source content. */
   66.49 -    private final int length;
   66.50 +    /** Source content */
   66.51 +    private final Data data;
   66.52  
   66.53      /** Cached hash code */
   66.54      private int hash;
   66.55 @@ -76,40 +82,297 @@
   66.56      /** Message digest */
   66.57      private byte[] digest;
   66.58  
   66.59 -    /** Source URL if available */
   66.60 -    private final URL url;
   66.61 +    // Do *not* make this public, ever! Trusts the URL and content.
   66.62 +    private Source(final String name, final String base, final Data data) {
   66.63 +        this.name = name;
   66.64 +        this.base = base;
   66.65 +        this.data = data;
   66.66 +    }
   66.67  
   66.68 -    private static final int BUFSIZE = 8 * 1024;
   66.69 +    private static synchronized Source sourceFor(final String name, final String base, final URLData data) throws IOException {
   66.70 +        try {
   66.71 +            final Source newSource = new Source(name, base, data);
   66.72 +            final Source existingSource = CACHE.get(newSource);
   66.73 +            if (existingSource != null) {
   66.74 +                // Force any access errors
   66.75 +                data.checkPermissionAndClose();
   66.76 +                return existingSource;
   66.77 +            } else {
   66.78 +                // All sources in cache must be fully loaded
   66.79 +                data.load();
   66.80 +                CACHE.put(newSource, newSource);
   66.81 +                return newSource;
   66.82 +            }
   66.83 +        } catch (RuntimeException e) {
   66.84 +            final Throwable cause = e.getCause();
   66.85 +            if (cause instanceof IOException) {
   66.86 +                throw (IOException) cause;
   66.87 +            }
   66.88 +            throw e;
   66.89 +        }
   66.90 +    }
   66.91  
   66.92 -    // Do *not* make this public ever! Trusts the URL and content. So has to be called
   66.93 -    // from other public constructors. Note that this can not be some init method as
   66.94 -    // we initialize final fields from here.
   66.95 -    private Source(final String name, final String base, final char[] content, final URL url) {
   66.96 -        this.name    = name;
   66.97 -        this.base    = base;
   66.98 -        this.content = content;
   66.99 -        this.length  = content.length;
  66.100 -        this.url     = url;
  66.101 +    private static class Cache extends WeakHashMap<Source, WeakReference<Source>> {
  66.102 +        public Source get(final Source key) {
  66.103 +            final WeakReference<Source> ref = super.get(key);
  66.104 +            return ref == null ? null : ref.get();
  66.105 +        }
  66.106 +
  66.107 +        public void put(final Source key, final Source value) {
  66.108 +            assert !(value.data instanceof RawData);
  66.109 +            put(key, new WeakReference<>(value));
  66.110 +        }
  66.111 +    }
  66.112 +
  66.113 +    // Wrapper to manage lazy loading
  66.114 +    private static interface Data {
  66.115 +
  66.116 +        URL url();
  66.117 +
  66.118 +        int length();
  66.119 +
  66.120 +        long lastModified();
  66.121 +
  66.122 +        char[] array();
  66.123 +    }
  66.124 +
  66.125 +    private static class RawData implements Data {
  66.126 +        private final char[] array;
  66.127 +        private int hash;
  66.128 +
  66.129 +        private RawData(final char[] array) {
  66.130 +            this.array = Objects.requireNonNull(array);
  66.131 +        }
  66.132 +
  66.133 +        private RawData(final String source) {
  66.134 +            this.array = Objects.requireNonNull(source).toCharArray();
  66.135 +        }
  66.136 +
  66.137 +        private RawData(final Reader reader) throws IOException {
  66.138 +            this(readFully(reader));
  66.139 +        }
  66.140 +
  66.141 +        @Override
  66.142 +        public int hashCode() {
  66.143 +            int h = hash;
  66.144 +            if (h == 0) {
  66.145 +                h = hash = Arrays.hashCode(array);
  66.146 +            }
  66.147 +            return h;
  66.148 +        }
  66.149 +
  66.150 +        @Override
  66.151 +        public boolean equals(Object obj) {
  66.152 +            if (this == obj) {
  66.153 +                return true;
  66.154 +            }
  66.155 +            if (obj instanceof RawData) {
  66.156 +                return Arrays.equals(array, ((RawData)obj).array);
  66.157 +            }
  66.158 +            return false;
  66.159 +        }
  66.160 +
  66.161 +        @Override
  66.162 +        public String toString() {
  66.163 +            return new String(array());
  66.164 +        }
  66.165 +
  66.166 +        @Override
  66.167 +        public URL url() {
  66.168 +            return null;
  66.169 +        }
  66.170 +
  66.171 +        @Override
  66.172 +        public int length() {
  66.173 +            return array.length;
  66.174 +        }
  66.175 +
  66.176 +        @Override
  66.177 +        public long lastModified() {
  66.178 +            return 0;
  66.179 +        }
  66.180 +
  66.181 +        @Override
  66.182 +        public char[] array() {
  66.183 +            return array;
  66.184 +        }
  66.185 +
  66.186 +
  66.187 +    }
  66.188 +
  66.189 +    private static class URLData implements Data {
  66.190 +        private final URL url;
  66.191 +        protected final Charset cs;
  66.192 +        private int hash;
  66.193 +        protected char[] array;
  66.194 +        protected int length;
  66.195 +        protected long lastModified;
  66.196 +
  66.197 +        private URLData(final URL url, final Charset cs) {
  66.198 +            this.url = Objects.requireNonNull(url);
  66.199 +            this.cs = cs;
  66.200 +        }
  66.201 +
  66.202 +        @Override
  66.203 +        public int hashCode() {
  66.204 +            int h = hash;
  66.205 +            if (h == 0) {
  66.206 +                h = hash = url.hashCode();
  66.207 +            }
  66.208 +            return h;
  66.209 +        }
  66.210 +
  66.211 +        @Override
  66.212 +        public boolean equals(Object other) {
  66.213 +            if (this == other) {
  66.214 +                return true;
  66.215 +            }
  66.216 +            if (!(other instanceof URLData)) {
  66.217 +                return false;
  66.218 +            }
  66.219 +
  66.220 +            URLData otherData = (URLData) other;
  66.221 +
  66.222 +            if (url.equals(otherData.url)) {
  66.223 +                // Make sure both have meta data loaded
  66.224 +                try {
  66.225 +                    if (isDeferred()) {
  66.226 +                        // Data in cache is always loaded, and we only compare to cached data.
  66.227 +                        assert !otherData.isDeferred();
  66.228 +                        loadMeta();
  66.229 +                    } else if (otherData.isDeferred()) {
  66.230 +                        otherData.loadMeta();
  66.231 +                    }
  66.232 +                } catch (IOException e) {
  66.233 +                    throw new RuntimeException(e);
  66.234 +                }
  66.235 +
  66.236 +                // Compare meta data
  66.237 +                return this.length == otherData.length && this.lastModified == otherData.lastModified;
  66.238 +            }
  66.239 +            return false;
  66.240 +        }
  66.241 +
  66.242 +        @Override
  66.243 +        public String toString() {
  66.244 +            return new String(array());
  66.245 +        }
  66.246 +
  66.247 +        @Override
  66.248 +        public URL url() {
  66.249 +            return url;
  66.250 +        }
  66.251 +
  66.252 +        @Override
  66.253 +        public int length() {
  66.254 +            return length;
  66.255 +        }
  66.256 +
  66.257 +        @Override
  66.258 +        public long lastModified() {
  66.259 +            return lastModified;
  66.260 +        }
  66.261 +
  66.262 +        @Override
  66.263 +        public char[] array() {
  66.264 +            assert !isDeferred();
  66.265 +            return array;
  66.266 +        }
  66.267 +
  66.268 +        boolean isDeferred() {
  66.269 +            return array == null;
  66.270 +        }
  66.271 +
  66.272 +        protected void checkPermissionAndClose() throws IOException {
  66.273 +            try (InputStream in = url.openStream()) {}
  66.274 +            debug("permission checked for ", url);
  66.275 +        }
  66.276 +
  66.277 +        protected void load() throws IOException {
  66.278 +            if (array == null) {
  66.279 +                final URLConnection c = url.openConnection();
  66.280 +                try (InputStream in = c.getInputStream()) {
  66.281 +                    array = cs == null ? readFully(in) : readFully(in, cs);
  66.282 +                    length = array.length;
  66.283 +                    lastModified = c.getLastModified();
  66.284 +                    debug("loaded content for ", url);
  66.285 +                }
  66.286 +            }
  66.287 +        }
  66.288 +
  66.289 +        protected void loadMeta() throws IOException {
  66.290 +            if (length == 0 && lastModified == 0) {
  66.291 +                final URLConnection c = url.openConnection();
  66.292 +                length = c.getContentLength();
  66.293 +                lastModified = c.getLastModified();
  66.294 +                debug("loaded metadata for ", url);
  66.295 +            }
  66.296 +        }
  66.297 +    }
  66.298 +
  66.299 +    private static class FileData extends URLData {
  66.300 +        private final File file;
  66.301 +
  66.302 +        private FileData(final File file, final Charset cs) {
  66.303 +            super(getURLFromFile(file), cs);
  66.304 +            this.file = file;
  66.305 +
  66.306 +        }
  66.307 +
  66.308 +        @Override
  66.309 +        protected void checkPermissionAndClose() throws IOException {
  66.310 +            if (!file.canRead()) {
  66.311 +                throw new FileNotFoundException(file + " (Permission Denied)");
  66.312 +            }
  66.313 +            debug("permission checked for ", file);
  66.314 +        }
  66.315 +
  66.316 +        @Override
  66.317 +        protected void loadMeta() {
  66.318 +            if (length == 0 && lastModified == 0) {
  66.319 +                length = (int) file.length();
  66.320 +                lastModified = file.lastModified();
  66.321 +                debug("loaded metadata for ", file);
  66.322 +            }
  66.323 +        }
  66.324 +
  66.325 +        @Override
  66.326 +        protected void load() throws IOException {
  66.327 +            if (array == null) {
  66.328 +                array = cs == null ? readFully(file) : readFully(file, cs);
  66.329 +                length = array.length;
  66.330 +                lastModified = file.lastModified();
  66.331 +                debug("loaded content for ", file);
  66.332 +            }
  66.333 +        }
  66.334 +    }
  66.335 +
  66.336 +    private static void debug(final Object... msg) {
  66.337 +        DEBUG.info(msg);
  66.338 +    }
  66.339 +
  66.340 +    private char[] data() {
  66.341 +        return data.array();
  66.342      }
  66.343  
  66.344      /**
  66.345 -     * Constructor
  66.346 +     * Returns an instance
  66.347       *
  66.348       * @param name    source name
  66.349       * @param content contents as char array
  66.350       */
  66.351 -    public Source(final String name, final char[] content) {
  66.352 -        this(name, baseName(name, null), content, null);
  66.353 +    public static Source sourceFor(final String name, final char[] content) {
  66.354 +        return new Source(name, baseName(name), new RawData(content));
  66.355      }
  66.356  
  66.357      /**
  66.358 -     * Constructor
  66.359 +     * Returns an instance
  66.360       *
  66.361       * @param name    source name
  66.362       * @param content contents as string
  66.363       */
  66.364 -    public Source(final String name, final String content) {
  66.365 -        this(name, content.toCharArray());
  66.366 +    public static Source sourceFor(final String name, final String content) {
  66.367 +        return new Source(name, baseName(name), new RawData(content));
  66.368      }
  66.369  
  66.370      /**
  66.371 @@ -120,8 +383,8 @@
  66.372       *
  66.373       * @throws IOException if source cannot be loaded
  66.374       */
  66.375 -    public Source(final String name, final URL url) throws IOException {
  66.376 -        this(name, baseURL(url, null), readFully(url), url);
  66.377 +    public static Source sourceFor(final String name, final URL url) throws IOException {
  66.378 +        return sourceFor(name, url, null);
  66.379      }
  66.380  
  66.381      /**
  66.382 @@ -133,8 +396,8 @@
  66.383       *
  66.384       * @throws IOException if source cannot be loaded
  66.385       */
  66.386 -    public Source(final String name, final URL url, final Charset cs) throws IOException {
  66.387 -        this(name, baseURL(url, null), readFully(url, cs), url);
  66.388 +    public static Source sourceFor(final String name, final URL url, final Charset cs) throws IOException {
  66.389 +        return sourceFor(name, baseURL(url), new URLData(url, cs));
  66.390      }
  66.391  
  66.392      /**
  66.393 @@ -145,8 +408,8 @@
  66.394       *
  66.395       * @throws IOException if source cannot be loaded
  66.396       */
  66.397 -    public Source(final String name, final File file) throws IOException {
  66.398 -        this(name, dirName(file, null), readFully(file), getURLFromFile(file));
  66.399 +    public static Source sourceFor(final String name, final File file) throws IOException {
  66.400 +        return sourceFor(name, file, null);
  66.401      }
  66.402  
  66.403      /**
  66.404 @@ -158,8 +421,25 @@
  66.405       *
  66.406       * @throws IOException if source cannot be loaded
  66.407       */
  66.408 -    public Source(final String name, final File file, final Charset cs) throws IOException {
  66.409 -        this(name, dirName(file, null), readFully(file, cs), getURLFromFile(file));
  66.410 +    public static Source sourceFor(final String name, final File file, final Charset cs) throws IOException {
  66.411 +        final File absFile = file.getAbsoluteFile();
  66.412 +        return sourceFor(name, dirName(absFile, null), new FileData(file, cs));
  66.413 +    }
  66.414 +
  66.415 +    /**
  66.416 +     * Returns an instance
  66.417 +     *
  66.418 +     * @param name source name
  66.419 +     * @param reader reader from which source can be loaded
  66.420 +     * @throws IOException if source cannot be loaded
  66.421 +     */
  66.422 +    public static Source sourceFor(final String name, final Reader reader) throws IOException {
  66.423 +        // Extract URL from URLReader to defer loading and reuse cached data if available.
  66.424 +        if (reader instanceof URLReader) {
  66.425 +            final URLReader urlReader = (URLReader) reader;
  66.426 +            return sourceFor(name, urlReader.getURL(), urlReader.getCharset());
  66.427 +        }
  66.428 +        return new Source(name, baseName(name), new RawData(reader));
  66.429      }
  66.430  
  66.431      @Override
  66.432 @@ -167,21 +447,18 @@
  66.433          if (this == obj) {
  66.434              return true;
  66.435          }
  66.436 -
  66.437          if (!(obj instanceof Source)) {
  66.438              return false;
  66.439          }
  66.440 -
  66.441 -        final Source src = (Source)obj;
  66.442 -        // Only compare content as a last resort measure
  66.443 -        return length == src.length && Objects.equals(url, src.url) && Objects.equals(name, src.name) && Arrays.equals(content, src.content);
  66.444 +        final Source other = (Source) obj;
  66.445 +        return Objects.equals(name, other.name) && data.equals(other.data);
  66.446      }
  66.447  
  66.448      @Override
  66.449      public int hashCode() {
  66.450          int h = hash;
  66.451          if (h == 0) {
  66.452 -            h = hash = Arrays.hashCode(content) ^ Objects.hashCode(name);
  66.453 +            h = hash = data.hashCode() ^ Objects.hashCode(name);
  66.454          }
  66.455          return h;
  66.456      }
  66.457 @@ -191,7 +468,7 @@
  66.458       * @return Source content.
  66.459       */
  66.460      public String getString() {
  66.461 -        return new String(content, 0, length);
  66.462 +        return data.toString();
  66.463      }
  66.464  
  66.465      /**
  66.466 @@ -203,6 +480,14 @@
  66.467      }
  66.468  
  66.469      /**
  66.470 +     * Get the last modified time of this script.
  66.471 +     * @return Last modified time.
  66.472 +     */
  66.473 +    public long getLastModified() {
  66.474 +        return data.lastModified();
  66.475 +    }
  66.476 +
  66.477 +    /**
  66.478       * Get the "directory" part of the file or "base" of the URL.
  66.479       * @return base of file or URL.
  66.480       */
  66.481 @@ -217,7 +502,7 @@
  66.482       * @return Source content portion.
  66.483       */
  66.484      public String getString(final int start, final int len) {
  66.485 -        return new String(content, start, len);
  66.486 +        return new String(data(), start, len);
  66.487      }
  66.488  
  66.489      /**
  66.490 @@ -228,7 +513,7 @@
  66.491      public String getString(final long token) {
  66.492          final int start = Token.descPosition(token);
  66.493          final int len = Token.descLength(token);
  66.494 -        return new String(content, start, len);
  66.495 +        return new String(data(), start, len);
  66.496      }
  66.497  
  66.498      /**
  66.499 @@ -238,7 +523,7 @@
  66.500       * @return URL source or null
  66.501       */
  66.502      public URL getURL() {
  66.503 -        return url;
  66.504 +        return data.url();
  66.505      }
  66.506  
  66.507      /**
  66.508 @@ -247,8 +532,9 @@
  66.509       * @return Index of first character of line.
  66.510       */
  66.511      private int findBOLN(final int position) {
  66.512 +        final char[] data = data();
  66.513          for (int i = position - 1; i > 0; i--) {
  66.514 -            final char ch = content[i];
  66.515 +            final char ch = data[i];
  66.516  
  66.517              if (ch == '\n' || ch == '\r') {
  66.518                  return i + 1;
  66.519 @@ -264,8 +550,10 @@
  66.520       * @return Index of last character of line.
  66.521       */
  66.522      private int findEOLN(final int position) {
  66.523 -         for (int i = position; i < length; i++) {
  66.524 -            final char ch = content[i];
  66.525 +        final char[] data = data();
  66.526 +        final int length = data.length;
  66.527 +        for (int i = position; i < length; i++) {
  66.528 +            final char ch = data[i];
  66.529  
  66.530              if (ch == '\n' || ch == '\r') {
  66.531                  return i - 1;
  66.532 @@ -285,11 +573,12 @@
  66.533       * @return Line number.
  66.534       */
  66.535      public int getLine(final int position) {
  66.536 +        final char[] data = data();
  66.537          // Line count starts at 1.
  66.538          int line = 1;
  66.539  
  66.540          for (int i = 0; i < position; i++) {
  66.541 -            final char ch = content[i];
  66.542 +            final char ch = data[i];
  66.543              // Works for both \n and \r\n.
  66.544              if (ch == '\n') {
  66.545                  line++;
  66.546 @@ -320,7 +609,7 @@
  66.547          // Find end of this line.
  66.548          final int last = findEOLN(position);
  66.549  
  66.550 -        return new String(content, first, last - first + 1);
  66.551 +        return new String(data(), first, last - first + 1);
  66.552      }
  66.553  
  66.554      /**
  66.555 @@ -328,7 +617,7 @@
  66.556       * @return content
  66.557       */
  66.558      public char[] getContent() {
  66.559 -        return content.clone();
  66.560 +        return data().clone();
  66.561      }
  66.562  
  66.563      /**
  66.564 @@ -336,19 +625,18 @@
  66.565       * @return length
  66.566       */
  66.567      public int getLength() {
  66.568 -        return length;
  66.569 +        return data.length();
  66.570      }
  66.571  
  66.572      /**
  66.573       * Read all of the source until end of file. Return it as char array
  66.574       *
  66.575 -     * @param reader  reader opened to source stream
  66.576 +     * @param reader reader opened to source stream
  66.577       * @return source as content
  66.578 -     *
  66.579       * @throws IOException if source could not be read
  66.580       */
  66.581      public static char[] readFully(final Reader reader) throws IOException {
  66.582 -        final char[]        arr = new char[BUFSIZE];
  66.583 +        final char[]        arr = new char[BUF_SIZE];
  66.584          final StringBuilder sb  = new StringBuilder();
  66.585  
  66.586          try {
  66.587 @@ -366,9 +654,8 @@
  66.588      /**
  66.589       * Read all of the source until end of file. Return it as char array
  66.590       *
  66.591 -     * @param file  source file
  66.592 +     * @param file source file
  66.593       * @return source as content
  66.594 -     *
  66.595       * @throws IOException if source could not be read
  66.596       */
  66.597      public static char[] readFully(final File file) throws IOException {
  66.598 @@ -381,10 +668,9 @@
  66.599      /**
  66.600       * Read all of the source until end of file. Return it as char array
  66.601       *
  66.602 -     * @param file  source file
  66.603 +     * @param file source file
  66.604       * @param cs Charset used to convert bytes to chars
  66.605       * @return source as content
  66.606 -     *
  66.607       * @throws IOException if source could not be read
  66.608       */
  66.609      public static char[] readFully(final File file, final Charset cs) throws IOException {
  66.610 @@ -393,7 +679,7 @@
  66.611          }
  66.612  
  66.613          final byte[] buf = Files.readAllBytes(file.toPath());
  66.614 -        return (cs != null)? new String(buf, cs).toCharArray() : byteToCharArray(buf);
  66.615 +        return (cs != null) ? new String(buf, cs).toCharArray() : byteToCharArray(buf);
  66.616      }
  66.617  
  66.618      /**
  66.619 @@ -401,7 +687,6 @@
  66.620       *
  66.621       * @param url URL to read content from
  66.622       * @return source as content
  66.623 -     *
  66.624       * @throws IOException if source could not be read
  66.625       */
  66.626      public static char[] readFully(final URL url) throws IOException {
  66.627 @@ -414,7 +699,6 @@
  66.628       * @param url URL to read content from
  66.629       * @param cs Charset used to convert bytes to chars
  66.630       * @return source as content
  66.631 -     *
  66.632       * @throws IOException if source could not be read
  66.633       */
  66.634      public static char[] readFully(final URL url, final Charset cs) throws IOException {
  66.635 @@ -428,7 +712,7 @@
  66.636       */
  66.637      public synchronized byte[] getDigest() {
  66.638          if (digest == null) {
  66.639 -
  66.640 +            final char[] content = data();
  66.641              final byte[] bytes = new byte[content.length * 2];
  66.642  
  66.643              for (int i = 0; i < content.length; i++) {
  66.644 @@ -444,8 +728,8 @@
  66.645                  if (base != null) {
  66.646                      md.update(base.getBytes(StandardCharsets.UTF_8));
  66.647                  }
  66.648 -                if (url != null) {
  66.649 -                    md.update(url.toString().getBytes(StandardCharsets.UTF_8));
  66.650 +                if (getURL() != null) {
  66.651 +                    md.update(getURL().toString().getBytes(StandardCharsets.UTF_8));
  66.652                  }
  66.653                  digest = md.digest(bytes);
  66.654              } catch (NoSuchAlgorithmException e) {
  66.655 @@ -461,50 +745,46 @@
  66.656       * @return base URL for url
  66.657       */
  66.658      public static String baseURL(final URL url) {
  66.659 -        return baseURL(url, null);
  66.660 -    }
  66.661 -
  66.662 -    private static String baseURL(final URL url, final String defaultValue) {
  66.663          if (url.getProtocol().equals("file")) {
  66.664              try {
  66.665                  final Path path = Paths.get(url.toURI());
  66.666                  final Path parent = path.getParent();
  66.667 -                return (parent != null) ? (parent + File.separator) : defaultValue;
  66.668 +                return (parent != null) ? (parent + File.separator) : null;
  66.669              } catch (final SecurityException | URISyntaxException | IOError e) {
  66.670 -                return defaultValue;
  66.671 +                return null;
  66.672              }
  66.673          }
  66.674  
  66.675          // FIXME: is there a better way to find 'base' URL of a given URL?
  66.676          String path = url.getPath();
  66.677          if (path.isEmpty()) {
  66.678 -            return defaultValue;
  66.679 +            return null;
  66.680          }
  66.681          path = path.substring(0, path.lastIndexOf('/') + 1);
  66.682          final int port = url.getPort();
  66.683          try {
  66.684              return new URL(url.getProtocol(), url.getHost(), port, path).toString();
  66.685          } catch (final MalformedURLException e) {
  66.686 -            return defaultValue;
  66.687 +            return null;
  66.688          }
  66.689      }
  66.690  
  66.691 -    private static String dirName(final File file, final String defaultValue) {
  66.692 +    private static String dirName(final File file, final String DEFAULT_BASE_NAME) {
  66.693          final String res = file.getParent();
  66.694 -        return (res != null)? (res + File.separator) : defaultValue;
  66.695 +        return (res != null) ? (res + File.separator) : DEFAULT_BASE_NAME;
  66.696      }
  66.697  
  66.698      // fake directory like name
  66.699 -    private static String baseName(final String name, final String defaultValue) {
  66.700 +    private static String baseName(final String name) {
  66.701          int idx = name.lastIndexOf('/');
  66.702          if (idx == -1) {
  66.703              idx = name.lastIndexOf('\\');
  66.704          }
  66.705 -        return (idx != -1)? name.substring(0, idx + 1) : defaultValue;
  66.706 +        return (idx != -1) ? name.substring(0, idx + 1) : null;
  66.707      }
  66.708  
  66.709      private static char[] readFully(final InputStream is, final Charset cs) throws IOException {
  66.710 -        return (cs != null)? new String(readBytes(is), cs).toCharArray() : readFully(is);
  66.711 +        return (cs != null) ? new String(readBytes(is), cs).toCharArray() : readFully(is);
  66.712      }
  66.713  
  66.714      private static char[] readFully(final InputStream is) throws IOException {
  66.715 @@ -515,19 +795,19 @@
  66.716          Charset cs = StandardCharsets.UTF_8;
  66.717          int start = 0;
  66.718          // BOM detection.
  66.719 -        if (bytes.length > 1 && bytes[0] == (byte)0xFE && bytes[1] == (byte)0xFF) {
  66.720 +        if (bytes.length > 1 && bytes[0] == (byte) 0xFE && bytes[1] == (byte) 0xFF) {
  66.721              start = 2;
  66.722              cs = StandardCharsets.UTF_16BE;
  66.723 -        } else if (bytes.length > 1 && bytes[0] == (byte)0xFF && bytes[1] == (byte)0xFE) {
  66.724 +        } else if (bytes.length > 1 && bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xFE) {
  66.725              start = 2;
  66.726              cs = StandardCharsets.UTF_16LE;
  66.727 -        } else if (bytes.length > 2 && bytes[0] == (byte)0xEF && bytes[1] == (byte)0xBB && bytes[2] == (byte)0xBF) {
  66.728 +        } else if (bytes.length > 2 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
  66.729              start = 3;
  66.730              cs = StandardCharsets.UTF_8;
  66.731 -        } else if (bytes.length > 3 && bytes[0] == (byte)0xFF && bytes[1] == (byte)0xFE && bytes[2] == 0 && bytes[3] == 0) {
  66.732 +        } else if (bytes.length > 3 && bytes[0] == (byte) 0xFF && bytes[1] == (byte) 0xFE && bytes[2] == 0 && bytes[3] == 0) {
  66.733              start = 4;
  66.734              cs = Charset.forName("UTF-32LE");
  66.735 -        } else if (bytes.length > 3 && bytes[0] == 0 && bytes[1] == 0 && bytes[2] == (byte)0xFE && bytes[3] == (byte)0xFF) {
  66.736 +        } else if (bytes.length > 3 && bytes[0] == 0 && bytes[1] == 0 && bytes[2] == (byte) 0xFE && bytes[3] == (byte) 0xFF) {
  66.737              start = 4;
  66.738              cs = Charset.forName("UTF-32BE");
  66.739          }
  66.740 @@ -536,7 +816,7 @@
  66.741      }
  66.742  
  66.743      static byte[] readBytes(final InputStream is) throws IOException {
  66.744 -        final byte[] arr = new byte[BUFSIZE];
  66.745 +        final byte[] arr = new byte[BUF_SIZE];
  66.746          try {
  66.747              try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
  66.748                  int numBytes;
    67.1 --- a/src/jdk/nashorn/internal/runtime/regexp/JdkRegExp.java	Tue May 13 23:18:50 2014 -0700
    67.2 +++ b/src/jdk/nashorn/internal/runtime/regexp/JdkRegExp.java	Wed May 14 11:02:04 2014 -0700
    67.3 @@ -46,9 +46,6 @@
    67.4      /** Java regexp pattern to use for match. We compile to one of these */
    67.5      private Pattern pattern;
    67.6  
    67.7 -    /** The matcher */
    67.8 -    private RegExpMatcher matcher;
    67.9 -
   67.10      /**
   67.11       * Construct a Regular expression from the given {@code source} and {@code flags} strings.
   67.12       *
   67.13 @@ -95,14 +92,7 @@
   67.14              return null; // never matches or similar, e.g. a[]
   67.15          }
   67.16  
   67.17 -        RegExpMatcher currentMatcher = this.matcher;
   67.18 -
   67.19 -        if (currentMatcher == null || matcher.getInput() != str) {
   67.20 -            currentMatcher = new DefaultMatcher(str);
   67.21 -            this.matcher  = currentMatcher;
   67.22 -        }
   67.23 -
   67.24 -        return currentMatcher;
   67.25 +        return new DefaultMatcher(str);
   67.26      }
   67.27  
   67.28      class DefaultMatcher implements RegExpMatcher {
    68.1 --- a/src/jdk/nashorn/internal/runtime/regexp/JoniRegExp.java	Tue May 13 23:18:50 2014 -0700
    68.2 +++ b/src/jdk/nashorn/internal/runtime/regexp/JoniRegExp.java	Wed May 14 11:02:04 2014 -0700
    68.3 @@ -44,9 +44,6 @@
    68.4      /** Compiled Joni Regex */
    68.5      private Regex regex;
    68.6  
    68.7 -    /** Matcher */
    68.8 -    private RegExpMatcher matcher;
    68.9 -
   68.10      /**
   68.11       * Construct a Regular expression from the given {@code pattern} and {@code flags} strings.
   68.12       *
   68.13 @@ -95,14 +92,7 @@
   68.14              return null;
   68.15          }
   68.16  
   68.17 -        RegExpMatcher currentMatcher = this.matcher;
   68.18 -
   68.19 -        if (currentMatcher == null || input != currentMatcher.getInput()) {
   68.20 -            currentMatcher = new JoniMatcher(input);
   68.21 -            this.matcher   = currentMatcher;
   68.22 -        }
   68.23 -
   68.24 -        return currentMatcher;
   68.25 +        return new JoniMatcher(input);
   68.26      }
   68.27  
   68.28      /**
    69.1 --- a/src/jdk/nashorn/internal/runtime/regexp/joni/Regex.java	Tue May 13 23:18:50 2014 -0700
    69.2 +++ b/src/jdk/nashorn/internal/runtime/regexp/joni/Regex.java	Wed May 14 11:02:04 2014 -0700
    69.3 @@ -131,12 +131,13 @@
    69.4          this.warnings = null;
    69.5      }
    69.6  
    69.7 -    public void compile() {
    69.8 +    public synchronized MatcherFactory compile() {
    69.9          if (factory == null && analyser != null) {
   69.10 -            Compiler compiler = new ArrayCompiler(analyser);
   69.11 +            new ArrayCompiler(analyser).compile();
   69.12              analyser = null; // only do this once
   69.13 -            compiler.compile();
   69.14          }
   69.15 +        assert factory != null;
   69.16 +        return factory;
   69.17      }
   69.18  
   69.19      public Matcher matcher(char[] chars) {
   69.20 @@ -144,8 +145,11 @@
   69.21      }
   69.22  
   69.23      public Matcher matcher(char[] chars, int p, int end) {
   69.24 -        compile();
   69.25 -        return factory.create(this, chars, p, end);
   69.26 +        MatcherFactory matcherFactory = factory;
   69.27 +        if (matcherFactory == null) {
   69.28 +            matcherFactory = compile();
   69.29 +        }
   69.30 +        return matcherFactory.create(this, chars, p, end);
   69.31      }
   69.32  
   69.33      public WarnCallback getWarnings() {
    70.1 --- a/src/jdk/nashorn/internal/runtime/resources/Options.properties	Tue May 13 23:18:50 2014 -0700
    70.2 +++ b/src/jdk/nashorn/internal/runtime/resources/Options.properties	Wed May 14 11:02:04 2014 -0700
    70.3 @@ -102,6 +102,13 @@
    70.4      type=Boolean                      \
    70.5  }
    70.6  
    70.7 +nashorn.option.const.as.var = {          \
    70.8 +    name="--const-as-var",               \
    70.9 +    is_undocumented=true,                \
   70.10 +    desc="Replace 'const' with 'var'.",  \
   70.11 +    type=Boolean                         \
   70.12 +}
   70.13 +
   70.14  nashorn.option.d = {                                             \
   70.15      name="--dump-debug-dir",                                     \
   70.16      short_name="-d",                                             \
    71.1 --- a/src/jdk/nashorn/tools/Shell.java	Tue May 13 23:18:50 2014 -0700
    71.2 +++ b/src/jdk/nashorn/tools/Shell.java	Wed May 14 11:02:04 2014 -0700
    71.3 @@ -25,6 +25,8 @@
    71.4  
    71.5  package jdk.nashorn.tools;
    71.6  
    71.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    71.8 +
    71.9  import java.io.BufferedReader;
   71.10  import java.io.File;
   71.11  import java.io.FileReader;
   71.12 @@ -50,7 +52,6 @@
   71.13  import jdk.nashorn.internal.runtime.Property;
   71.14  import jdk.nashorn.internal.runtime.ScriptEnvironment;
   71.15  import jdk.nashorn.internal.runtime.ScriptFunction;
   71.16 -import jdk.nashorn.internal.runtime.ScriptObject;
   71.17  import jdk.nashorn.internal.runtime.ScriptRuntime;
   71.18  import jdk.nashorn.internal.runtime.Source;
   71.19  import jdk.nashorn.internal.runtime.options.Options;
   71.20 @@ -244,7 +245,7 @@
   71.21  
   71.22              // For each file on the command line.
   71.23              for (final String fileName : files) {
   71.24 -                final FunctionNode functionNode = new Parser(env, new Source(fileName, new File(fileName)), errors).parse();
   71.25 +                final FunctionNode functionNode = new Parser(env, sourceFor(fileName, new File(fileName)), errors).parse();
   71.26  
   71.27                  if (errors.getNumberOfErrors() != 0) {
   71.28                      return COMPILATION_ERROR;
   71.29 @@ -302,7 +303,7 @@
   71.30                  }
   71.31  
   71.32                  final File file = new File(fileName);
   71.33 -                final ScriptFunction script = context.compileScript(new Source(fileName, file.toURI().toURL()), global);
   71.34 +                final ScriptFunction script = context.compileScript(sourceFor(fileName, file), global);
   71.35                  if (script == null || errors.getNumberOfErrors() != 0) {
   71.36                      return COMPILATION_ERROR;
   71.37                  }
   71.38 @@ -405,7 +406,7 @@
   71.39  
   71.40              // initialize with "shell.js" script
   71.41              try {
   71.42 -                final Source source = new Source("<shell.js>", Shell.class.getResource("resources/shell.js"));
   71.43 +                final Source source = sourceFor("<shell.js>", Shell.class.getResource("resources/shell.js"));
   71.44                  context.eval(global, source.getString(), global, "<shell.js>", false);
   71.45              } catch (final Exception e) {
   71.46                  err.println(e);
   71.47 @@ -452,7 +453,7 @@
   71.48              }
   71.49          } finally {
   71.50              if (globalChanged) {
   71.51 -                Context.setGlobal(global);
   71.52 +                Context.setGlobal(oldGlobal);
   71.53              }
   71.54          }
   71.55  
    72.1 --- a/test/script/basic/JDK-8008448.js	Tue May 13 23:18:50 2014 -0700
    72.2 +++ b/test/script/basic/JDK-8008448.js	Wed May 14 11:02:04 2014 -0700
    72.3 @@ -26,6 +26,7 @@
    72.4   * Ensure that all parseable files can be parsed using parser API.
    72.5   *
    72.6   * @test
    72.7 + * @option --const-as-var
    72.8   * @option -scripting
    72.9   * @run
   72.10   */
    73.1 --- a/test/script/basic/JDK-8024120.js	Tue May 13 23:18:50 2014 -0700
    73.2 +++ b/test/script/basic/JDK-8024120.js	Wed May 14 11:02:04 2014 -0700
    73.3 @@ -32,10 +32,6 @@
    73.4  
    73.5  obj.__proto__ = null;
    73.6  
    73.7 -if (obj.__proto__ !== null || typeof(obj.__proto__) != 'object') {
    73.8 -    fail("obj.__proto__ is expected to be null");
    73.9 -}
   73.10 -
   73.11  var p = Object.getPrototypeOf(obj);
   73.12  if (p !== null || typeof(p) != 'object') {
   73.13      fail("Object.getPrototypeOf(obj) is expected to be null");
    74.1 --- a/test/script/basic/JDK-8024174.js	Tue May 13 23:18:50 2014 -0700
    74.2 +++ b/test/script/basic/JDK-8024174.js	Wed May 14 11:02:04 2014 -0700
    74.3 @@ -46,6 +46,6 @@
    74.4      __proto__: null
    74.5  };
    74.6  
    74.7 -if (obj2.__proto__ !== null || Object.getPrototypeOf(obj2) !== null) {
    74.8 +if (Object.getPrototypeOf(obj2) !== null) {
    74.9      fail("obj2.__proto__ was not set to null inside literal");
   74.10  }
    75.1 --- a/test/script/basic/JDK-8026161.js	Tue May 13 23:18:50 2014 -0700
    75.2 +++ b/test/script/basic/JDK-8026161.js	Wed May 14 11:02:04 2014 -0700
    75.3 @@ -1,5 +1,5 @@
    75.4  /*
    75.5 - * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
    75.6 + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
    75.7   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    75.8   * 
    75.9   * This code is free software; you can redistribute it and/or modify it
   75.10 @@ -28,5 +28,5 @@
   75.11   * @run
   75.12   */
   75.13  
   75.14 -print(new java.awt.Color(1, 1, 1)) // creates Color[r=1,g=1,b=1]
   75.15 -print(new java.awt.Color(1.0, 1.0, 1.0)) // Color[r=255,g=255,b=255]
   75.16 +print(Java.type("jdk.nashorn.test.models.IntFloatOverloadSelection").overloadedMethod(1))
   75.17 +print(Java.type("jdk.nashorn.test.models.IntFloatOverloadSelection").overloadedMethod(1.0))
    76.1 --- a/test/script/basic/JDK-8026161.js.EXPECTED	Tue May 13 23:18:50 2014 -0700
    76.2 +++ b/test/script/basic/JDK-8026161.js.EXPECTED	Wed May 14 11:02:04 2014 -0700
    76.3 @@ -1,2 +1,2 @@
    76.4 -java.awt.Color[r=1,g=1,b=1]
    76.5 -java.awt.Color[r=255,g=255,b=255]
    76.6 +int
    76.7 +float
    77.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    77.2 +++ b/test/script/basic/JDK-8027933.js	Wed May 14 11:02:04 2014 -0700
    77.3 @@ -0,0 +1,38 @@
    77.4 +/*
    77.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    77.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    77.7 + * 
    77.8 + * This code is free software; you can redistribute it and/or modify it
    77.9 + * under the terms of the GNU General Public License version 2 only, as
   77.10 + * published by the Free Software Foundation.
   77.11 + * 
   77.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
   77.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   77.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   77.15 + * version 2 for more details (a copy is included in the LICENSE file that
   77.16 + * accompanied this code).
   77.17 + * 
   77.18 + * You should have received a copy of the GNU General Public License version
   77.19 + * 2 along with this work; if not, write to the Free Software Foundation,
   77.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   77.21 + * 
   77.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   77.23 + * or visit www.oracle.com if you need additional information or have any
   77.24 + * questions.
   77.25 + */
   77.26 +
   77.27 +/**
   77.28 + * JDK-8027933: Add const.as.var option
   77.29 + *
   77.30 + * @test
   77.31 + * @option --const-as-var
   77.32 + * @run
   77.33 + */
   77.34 +
   77.35 +const THE_ANSWER = 42;
   77.36 +print("Answer to all questions: " + THE_ANSWER);
   77.37 +
   77.38 +print((function () {
   77.39 +    const FORTY_TWO = 42;
   77.40 +    return FORTY_TWO
   77.41 +})())
    78.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    78.2 +++ b/test/script/basic/JDK-8027933.js.EXPECTED	Wed May 14 11:02:04 2014 -0700
    78.3 @@ -0,0 +1,2 @@
    78.4 +Answer to all questions: 42
    78.5 +42
    79.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    79.2 +++ b/test/script/basic/JDK-8041998.js	Wed May 14 11:02:04 2014 -0700
    79.3 @@ -0,0 +1,52 @@
    79.4 +/*
    79.5 + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
    79.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    79.7 + * 
    79.8 + * This code is free software; you can redistribute it and/or modify it
    79.9 + * under the terms of the GNU General Public License version 2 only, as
   79.10 + * published by the Free Software Foundation.
   79.11 + * 
   79.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
   79.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   79.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   79.15 + * version 2 for more details (a copy is included in the LICENSE file that
   79.16 + * accompanied this code).
   79.17 + * 
   79.18 + * You should have received a copy of the GNU General Public License version
   79.19 + * 2 along with this work; if not, write to the Free Software Foundation,
   79.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   79.21 + * 
   79.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   79.23 + * or visit www.oracle.com if you need additional information or have any
   79.24 + * questions.
   79.25 + */
   79.26 +
   79.27 +/**
   79.28 + * JDK-8041998: RegExp implementation is not thread-safe
   79.29 + *
   79.30 + * @test
   79.31 + * @run
   79.32 + */
   79.33 +
   79.34 +var Thread = java.lang.Thread;
   79.35 +
   79.36 +function run() {
   79.37 +    var line = 'content-type: text/html';
   79.38 +    for (var i = 0; i < 300; i++) {
   79.39 +        Thread.sleep(1);
   79.40 +        line.split(/: /);
   79.41 +    }
   79.42 +    print("done");
   79.43 +}
   79.44 +
   79.45 +var threads = [];
   79.46 +
   79.47 +for (var i = 0; i < 4; i++) {
   79.48 +    var thread = new Thread(run);
   79.49 +    thread.start();
   79.50 +    threads.push(thread);
   79.51 +}
   79.52 +
   79.53 +for (var i = 0; i < 4; i++) {
   79.54 +    threads[i].join();
   79.55 +}
    80.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    80.2 +++ b/test/script/basic/JDK-8041998.js.EXPECTED	Wed May 14 11:02:04 2014 -0700
    80.3 @@ -0,0 +1,4 @@
    80.4 +done
    80.5 +done
    80.6 +done
    80.7 +done
    81.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    81.2 +++ b/test/script/basic/JDK-8042364.js	Wed May 14 11:02:04 2014 -0700
    81.3 @@ -0,0 +1,65 @@
    81.4 +/*
    81.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    81.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    81.7 + * 
    81.8 + * This code is free software; you can redistribute it and/or modify it
    81.9 + * under the terms of the GNU General Public License version 2 only, as
   81.10 + * published by the Free Software Foundation.
   81.11 + * 
   81.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
   81.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   81.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   81.15 + * version 2 for more details (a copy is included in the LICENSE file that
   81.16 + * accompanied this code).
   81.17 + * 
   81.18 + * You should have received a copy of the GNU General Public License version
   81.19 + * 2 along with this work; if not, write to the Free Software Foundation,
   81.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   81.21 + * 
   81.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   81.23 + * or visit www.oracle.com if you need additional information or have any
   81.24 + * questions.
   81.25 + */
   81.26 +
   81.27 +/**
   81.28 + * JDK-8042364: Make __proto__ ES6 draft compliant
   81.29 + * 
   81.30 + * @test
   81.31 + * @run
   81.32 + */
   81.33 +
   81.34 +// check for Object.prototype.__proto__ accessor property
   81.35 +print("Object.prototype has __proto__?",
   81.36 +    Object.prototype.hasOwnProperty("__proto__"))
   81.37 +
   81.38 +var desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__")
   81.39 +print("descriptor");
   81.40 +print(JSON.stringify(desc))
   81.41 +print("getter", desc.get)
   81.42 +print("setter", desc.set)
   81.43 +
   81.44 +// no computed "__proto__" name, only identifier!
   81.45 +var p = {}
   81.46 +var obj = {
   81.47 +    "__proto__" : p
   81.48 +}
   81.49 +
   81.50 +if (Object.getPrototypeOf(obj) === p) {
   81.51 +    fail("obj has wrong __proto__, allows computed __proto__!")
   81.52 +}
   81.53 +
   81.54 +if (obj.__proto__ !== p) {
   81.55 +    fail("__proto__ not created as normal property!")
   81.56 +}
   81.57 +
   81.58 +if (Object.getPrototypeOf(obj) !== Object.prototype) {
   81.59 +    fail("obj has wrong __proto__")
   81.60 +}
   81.61 +
   81.62 +var obj2 = {
   81.63 +    __proto__: p
   81.64 +}
   81.65 +
   81.66 +if (Object.getPrototypeOf(obj2) !== p) {
   81.67 +    fail("can't set __proto__ in object literal")
   81.68 +}
    82.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    82.2 +++ b/test/script/basic/JDK-8042364.js.EXPECTED	Wed May 14 11:02:04 2014 -0700
    82.3 @@ -0,0 +1,5 @@
    82.4 +Object.prototype has __proto__? true
    82.5 +descriptor
    82.6 +{"configurable":true,"enumerable":false}
    82.7 +getter function getProto() { [native code] }
    82.8 +setter function setProto() { [native code] }
    83.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    83.2 +++ b/test/script/error/JDK-8027933.js	Wed May 14 11:02:04 2014 -0700
    83.3 @@ -0,0 +1,31 @@
    83.4 +/*
    83.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    83.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    83.7 + * 
    83.8 + * This code is free software; you can redistribute it and/or modify it
    83.9 + * under the terms of the GNU General Public License version 2 only, as
   83.10 + * published by the Free Software Foundation.
   83.11 + * 
   83.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
   83.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   83.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   83.15 + * version 2 for more details (a copy is included in the LICENSE file that
   83.16 + * accompanied this code).
   83.17 + * 
   83.18 + * You should have received a copy of the GNU General Public License version
   83.19 + * 2 along with this work; if not, write to the Free Software Foundation,
   83.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   83.21 + * 
   83.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   83.23 + * or visit www.oracle.com if you need additional information or have any
   83.24 + * questions.
   83.25 + */
   83.26 +
   83.27 +/**
   83.28 + * JDK-8027933: Add const.as.var option
   83.29 + *
   83.30 + * @test/compile-error
   83.31 + */
   83.32 +
   83.33 +// without --const-as-var the following should fail to compile
   83.34 +const THE_ANSWER = 42;
    84.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    84.2 +++ b/test/script/error/JDK-8027933.js.EXPECTED	Wed May 14 11:02:04 2014 -0700
    84.3 @@ -0,0 +1,3 @@
    84.4 +test/script/error/JDK-8027933.js:31:0 Expected an operand but found const
    84.5 +const THE_ANSWER = 42;
    84.6 +^
    85.1 --- a/test/script/trusted/JDK-8006529.js	Tue May 13 23:18:50 2014 -0700
    85.2 +++ b/test/script/trusted/JDK-8006529.js	Wed May 14 11:02:04 2014 -0700
    85.3 @@ -113,7 +113,7 @@
    85.4  var getContextMethod = Context.class.getMethod("getContext")
    85.5  var getEnvMethod = Context.class.getMethod("getEnv")
    85.6  
    85.7 -var SourceConstructor = Source.class.getConstructor(java.lang.String.class, java.lang.String.class)
    85.8 +var sourceForMethod = Source.class.getMethod("sourceFor", java.lang.String.class, java.lang.String.class)
    85.9  var ParserConstructor = Parser.class.getConstructor(ScriptEnvironment.class, Source.class, ErrorManager.class)
   85.10  var CompilerConstructor = Compiler.class.getConstructor(ScriptEnvironment.class)
   85.11  
   85.12 @@ -121,7 +121,7 @@
   85.13  // source code, returns a jdk.nashorn.internal.ir.FunctionNode object 
   85.14  // representing it.
   85.15  function compile(source) {
   85.16 -    var source = SourceConstructor.newInstance("<no name>", source);
   85.17 +    var source = sourceForMethod.invoke(null, "<no name>", source);
   85.18  
   85.19      var env = getEnvMethod.invoke(getContextMethod.invoke(null))
   85.20  
    86.1 --- a/test/src/jdk/nashorn/internal/codegen/CompilerTest.java	Tue May 13 23:18:50 2014 -0700
    86.2 +++ b/test/src/jdk/nashorn/internal/codegen/CompilerTest.java	Wed May 14 11:02:04 2014 -0700
    86.3 @@ -25,6 +25,9 @@
    86.4  
    86.5  package jdk.nashorn.internal.codegen;
    86.6  
    86.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    86.8 +import static jdk.nashorn.internal.runtime.Source.readFully;
    86.9 +
   86.10  import java.io.File;
   86.11  import java.io.PrintWriter;
   86.12  import java.io.StringWriter;
   86.13 @@ -32,7 +35,6 @@
   86.14  import jdk.nashorn.internal.runtime.Context;
   86.15  import jdk.nashorn.internal.runtime.ErrorManager;
   86.16  import jdk.nashorn.internal.runtime.ScriptFunction;
   86.17 -import jdk.nashorn.internal.runtime.ScriptObject;
   86.18  import jdk.nashorn.internal.runtime.Source;
   86.19  import jdk.nashorn.internal.runtime.options.Options;
   86.20  import org.testng.Assert;
   86.21 @@ -69,6 +71,7 @@
   86.22          options.set("print.ast", true);
   86.23          options.set("print.parse", true);
   86.24          options.set("scripting", true);
   86.25 +        options.set("const.as.var", true);
   86.26  
   86.27          final ErrorManager errors = new ErrorManager() {
   86.28              @Override
   86.29 @@ -151,7 +154,7 @@
   86.30          final boolean globalChanged = (oldGlobal != global);
   86.31  
   86.32          try {
   86.33 -            final char[] buffer = Source.readFully(file);
   86.34 +            final char[] buffer = readFully(file);
   86.35              boolean excluded = false;
   86.36  
   86.37              if (filter != null) {
   86.38 @@ -170,7 +173,7 @@
   86.39              if (globalChanged) {
   86.40                  Context.setGlobal(global);
   86.41              }
   86.42 -            final Source source = new Source(file.getAbsolutePath(), buffer);
   86.43 +            final Source source = sourceFor(file.getAbsolutePath(), buffer);
   86.44              final ScriptFunction script = context.compileScript(source, global);
   86.45              if (script == null || context.getErrorManager().getNumberOfErrors() > 0) {
   86.46                  log("Compile failed: " + file.getAbsolutePath());
    87.1 --- a/test/src/jdk/nashorn/internal/parser/ParserTest.java	Tue May 13 23:18:50 2014 -0700
    87.2 +++ b/test/src/jdk/nashorn/internal/parser/ParserTest.java	Wed May 14 11:02:04 2014 -0700
    87.3 @@ -25,6 +25,9 @@
    87.4  
    87.5  package jdk.nashorn.internal.parser;
    87.6  
    87.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    87.8 +import static jdk.nashorn.internal.runtime.Source.readFully;
    87.9 +
   87.10  import java.io.File;
   87.11  import jdk.nashorn.internal.runtime.Context;
   87.12  import jdk.nashorn.internal.runtime.ErrorManager;
   87.13 @@ -62,6 +65,7 @@
   87.14          options.set("anon.functions", true);
   87.15          options.set("parse.only", true);
   87.16          options.set("scripting", true);
   87.17 +        options.set("const.as.var", true);
   87.18  
   87.19          ErrorManager errors = new ErrorManager();
   87.20          this.context = new Context(options, errors, Thread.currentThread().getContextClassLoader());
   87.21 @@ -131,7 +135,7 @@
   87.22          }
   87.23  
   87.24          try {
   87.25 -            final char[] buffer = Source.readFully(file);
   87.26 +            final char[] buffer = readFully(file);
   87.27              boolean excluded = false;
   87.28              if (filter != null) {
   87.29                  final String content = new String(buffer);
   87.30 @@ -153,7 +157,7 @@
   87.31                  }
   87.32              };
   87.33              errors.setLimit(0);
   87.34 -            final Source   source   = new Source(file.getAbsolutePath(), buffer);
   87.35 +            final Source   source   = sourceFor(file.getAbsolutePath(), buffer);
   87.36              new Parser(context.getEnv(), source, errors).parse();
   87.37              if (errors.getNumberOfErrors() > 0) {
   87.38                  log("Parse failed: " + file.getAbsolutePath());
    88.1 --- a/test/src/jdk/nashorn/internal/runtime/ContextTest.java	Tue May 13 23:18:50 2014 -0700
    88.2 +++ b/test/src/jdk/nashorn/internal/runtime/ContextTest.java	Wed May 14 11:02:04 2014 -0700
    88.3 @@ -25,6 +25,7 @@
    88.4  
    88.5  package jdk.nashorn.internal.runtime;
    88.6  
    88.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    88.8  import static org.testng.Assert.assertEquals;
    88.9  import static org.testng.Assert.assertTrue;
   88.10  
   88.11 @@ -107,7 +108,7 @@
   88.12      }
   88.13  
   88.14      private Object eval(final Context cx, final String name, final String code) {
   88.15 -        final Source source = new Source(name, code);
   88.16 +        final Source source = sourceFor(name, code);
   88.17          final ScriptObject global = Context.getGlobal();
   88.18          final ScriptFunction func = cx.compileScript(source, global);
   88.19          return func != null ? ScriptRuntime.apply(func, global) : null;
    89.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    89.2 +++ b/test/src/jdk/nashorn/internal/runtime/SourceTest.java	Wed May 14 11:02:04 2014 -0700
    89.3 @@ -0,0 +1,128 @@
    89.4 +/*
    89.5 + * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
    89.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    89.7 + *
    89.8 + * This code is free software; you can redistribute it and/or modify it
    89.9 + * under the terms of the GNU General Public License version 2 only, as
   89.10 + * published by the Free Software Foundation.  Oracle designates this
   89.11 + * particular file as subject to the "Classpath" exception as provided
   89.12 + * by Oracle in the LICENSE file that accompanied this code.
   89.13 + *
   89.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   89.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   89.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   89.17 + * version 2 for more details (a copy is included in the LICENSE file that
   89.18 + * accompanied this code).
   89.19 + *
   89.20 + * You should have received a copy of the GNU General Public License version
   89.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   89.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   89.23 + *
   89.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   89.25 + * or visit www.oracle.com if you need additional information or have any
   89.26 + * questions.
   89.27 + */
   89.28 +
   89.29 +package jdk.nashorn.internal.runtime;
   89.30 +
   89.31 +import jdk.nashorn.api.scripting.URLReader;
   89.32 +import org.testng.annotations.Test;
   89.33 +
   89.34 +import java.io.File;
   89.35 +import java.io.IOException;
   89.36 +import java.io.InputStreamReader;
   89.37 +import java.io.Reader;
   89.38 +import java.net.URL;
   89.39 +import java.util.Arrays;
   89.40 +
   89.41 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
   89.42 +import static org.testng.Assert.assertEquals;
   89.43 +import static org.testng.Assert.assertTrue;
   89.44 +import static org.testng.Assert.fail;
   89.45 +
   89.46 +/**
   89.47 + * Tests different Source representations.
   89.48 + */
   89.49 +public class SourceTest {
   89.50 +
   89.51 +    final private static String SOURCE_NAME = "source.js";
   89.52 +    final private static String SOURCE_STRING = "var x = 1;";
   89.53 +    final private static char[] SOURCE_CHARS = SOURCE_STRING.toCharArray();
   89.54 +    final private static String RESOURCE_PATH = "resources/load_test.js";
   89.55 +    final private static File SOURCE_FILE = new File("build/test/classes/jdk/nashorn/internal/runtime/" + RESOURCE_PATH);
   89.56 +    final private static URL  SOURCE_URL = SourceTest.class.getResource(RESOURCE_PATH);
   89.57 +
   89.58 +
   89.59 +    @Test
   89.60 +    public void testStringSource() {
   89.61 +        testSources(sourceFor(SOURCE_NAME, SOURCE_STRING), sourceFor(SOURCE_NAME, SOURCE_STRING));
   89.62 +        testSources(sourceFor(SOURCE_NAME, SOURCE_STRING), sourceFor(SOURCE_NAME, SOURCE_CHARS));
   89.63 +    }
   89.64 +
   89.65 +    @Test
   89.66 +    public void testCharArraySource() {
   89.67 +        testSources(sourceFor(SOURCE_NAME, SOURCE_CHARS), sourceFor(SOURCE_NAME, SOURCE_CHARS));
   89.68 +        testSources(sourceFor(SOURCE_NAME, SOURCE_CHARS), sourceFor(SOURCE_NAME, SOURCE_STRING));
   89.69 +    }
   89.70 +
   89.71 +    @Test
   89.72 +    public void testURLSource() {
   89.73 +        try {
   89.74 +            testSources(sourceFor(SOURCE_NAME, SOURCE_URL), sourceFor(SOURCE_NAME, SOURCE_URL));
   89.75 +            testSources(sourceFor(SOURCE_NAME, SOURCE_URL), sourceFor(SOURCE_NAME, new URLReader(SOURCE_URL)));
   89.76 +
   89.77 +        } catch (final IOException e) {
   89.78 +            fail(e.toString());
   89.79 +        }
   89.80 +    }
   89.81 +
   89.82 +    @Test
   89.83 +    public void testURLReaderSource() {
   89.84 +        try {
   89.85 +            System.err.println(SourceTest.class.getResource(""));
   89.86 +            testSources(sourceFor(SOURCE_NAME, new URLReader(SOURCE_URL)), sourceFor(SOURCE_NAME, new URLReader(SOURCE_URL)));
   89.87 +            testSources(sourceFor(SOURCE_NAME, new URLReader(SOURCE_URL)), sourceFor(SOURCE_NAME, SOURCE_URL));
   89.88 +        } catch (final IOException e) {
   89.89 +            fail(e.toString());
   89.90 +        }
   89.91 +    }
   89.92 +
   89.93 +    @Test
   89.94 +    public void testReaderSource() {
   89.95 +        try {
   89.96 +            testSources(sourceFor(SOURCE_NAME, getReader(RESOURCE_PATH)), sourceFor(SOURCE_NAME, getReader(RESOURCE_PATH)));
   89.97 +        } catch (final IOException e) {
   89.98 +            fail(e.toString());
   89.99 +        }
  89.100 +    }
  89.101 +
  89.102 +    @Test
  89.103 +    public void testFileSource() {
  89.104 +        try {
  89.105 +            testSources(sourceFor(SOURCE_NAME, SOURCE_FILE), sourceFor(SOURCE_NAME, SOURCE_FILE));
  89.106 +        } catch (final IOException e) {
  89.107 +            fail(e.toString());
  89.108 +        }
  89.109 +    }
  89.110 +
  89.111 +    private Reader getReader(final String path) {
  89.112 +        return new InputStreamReader(SourceTest.class.getResourceAsStream(path));
  89.113 +    }
  89.114 +
  89.115 +    private void testSources(final Source source1, final Source source2) {
  89.116 +        final char[] chars1 = source1.getContent();
  89.117 +        final char[] chars2 = source2.getContent();
  89.118 +        final String str1 = source1.getString();
  89.119 +        final String str2 = source2.getString();
  89.120 +        assertTrue(Arrays.equals(chars1, chars2));
  89.121 +        assertEquals(str1, str2);
  89.122 +        assertEquals(source1.hashCode(), source2.hashCode());
  89.123 +        assertTrue(source1.equals(source2));
  89.124 +        // Test for immutability
  89.125 +        Arrays.fill(source1.getContent(), (char)0);
  89.126 +        Arrays.fill(source2.getContent(), (char)1);
  89.127 +        assertTrue(Arrays.equals(source1.getContent(), str1.toCharArray()));
  89.128 +        assertTrue(Arrays.equals(source1.getContent(), chars1));
  89.129 +        assertTrue(Arrays.equals(source1.getContent(), source2.getContent()));
  89.130 +    }
  89.131 +}
    90.1 --- a/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java	Tue May 13 23:18:50 2014 -0700
    90.2 +++ b/test/src/jdk/nashorn/internal/runtime/TrustedScriptEngineTest.java	Wed May 14 11:02:04 2014 -0700
    90.3 @@ -220,4 +220,19 @@
    90.4          // bar should be visible in default context
    90.5          assertTrue(e.eval("typeof bar").equals("function"));
    90.6      }
    90.7 +
    90.8 +
    90.9 +    @Test public void nashornSwallowsConstKeyword() throws Exception {
   90.10 +        final NashornScriptEngineFactory f = new NashornScriptEngineFactory();
   90.11 +        final String[] args = new String[] { "--const-as-var" };
   90.12 +        final ScriptEngine engine = f.getScriptEngine(args);
   90.13 +
   90.14 +        final Object ret = engine.eval(""
   90.15 +            + "(function() {\n"
   90.16 +            + "  const x = 10;\n"
   90.17 +            + "  return x;\n"
   90.18 +            + "})();"
   90.19 +        );
   90.20 +        assertEquals(ret, 10, "Parsed and executed OK");
   90.21 +    }
   90.22  }
    91.1 --- a/test/src/jdk/nashorn/internal/test/framework/SharedContextEvaluator.java	Tue May 13 23:18:50 2014 -0700
    91.2 +++ b/test/src/jdk/nashorn/internal/test/framework/SharedContextEvaluator.java	Wed May 14 11:02:04 2014 -0700
    91.3 @@ -25,6 +25,7 @@
    91.4  
    91.5  package jdk.nashorn.internal.test.framework;
    91.6  
    91.7 +import static jdk.nashorn.internal.runtime.Source.sourceFor;
    91.8  import static jdk.nashorn.tools.Shell.COMPILATION_ERROR;
    91.9  import static jdk.nashorn.tools.Shell.RUNTIME_ERROR;
   91.10  import static jdk.nashorn.tools.Shell.SUCCESS;
   91.11 @@ -39,7 +40,6 @@
   91.12  import jdk.nashorn.internal.runtime.ErrorManager;
   91.13  import jdk.nashorn.internal.runtime.ScriptFunction;
   91.14  import jdk.nashorn.internal.runtime.ScriptRuntime;
   91.15 -import jdk.nashorn.internal.runtime.Source;
   91.16  import jdk.nashorn.internal.runtime.options.Options;
   91.17  
   91.18  /**
   91.19 @@ -125,7 +125,7 @@
   91.20                      continue;
   91.21                  }
   91.22                  final File file = new File(fileName);
   91.23 -                ScriptFunction script = context.compileScript(new Source(fileName, file.toURI().toURL()), global);
   91.24 +                ScriptFunction script = context.compileScript(sourceFor(fileName, file.toURI().toURL()), global);
   91.25  
   91.26                  if (script == null || errors.getNumberOfErrors() != 0) {
   91.27                      return COMPILATION_ERROR;
    92.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    92.2 +++ b/test/src/jdk/nashorn/test/models/IntFloatOverloadSelection.java	Wed May 14 11:02:04 2014 -0700
    92.3 @@ -0,0 +1,36 @@
    92.4 +/*
    92.5 + * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
    92.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    92.7 + *
    92.8 + * This code is free software; you can redistribute it and/or modify it
    92.9 + * under the terms of the GNU General Public License version 2 only, as
   92.10 + * published by the Free Software Foundation.  Oracle designates this
   92.11 + * particular file as subject to the "Classpath" exception as provided
   92.12 + * by Oracle in the LICENSE file that accompanied this code.
   92.13 + *
   92.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
   92.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   92.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   92.17 + * version 2 for more details (a copy is included in the LICENSE file that
   92.18 + * accompanied this code).
   92.19 + *
   92.20 + * You should have received a copy of the GNU General Public License version
   92.21 + * 2 along with this work; if not, write to the Free Software Foundation,
   92.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   92.23 + *
   92.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   92.25 + * or visit www.oracle.com if you need additional information or have any
   92.26 + * questions.
   92.27 + */
   92.28 +package jdk.nashorn.test.models;
   92.29 +
   92.30 +public class IntFloatOverloadSelection {
   92.31 +
   92.32 +    public static String overloadedMethod(int i) {
   92.33 +        return "int";
   92.34 +    }
   92.35 +
   92.36 +    public static String overloadedMethod(float f) {
   92.37 +        return "float";
   92.38 +    }
   92.39 +}
    93.1 --- a/test/src/jdk/nashorn/test/models/SourceHelper.java	Tue May 13 23:18:50 2014 -0700
    93.2 +++ b/test/src/jdk/nashorn/test/models/SourceHelper.java	Wed May 14 11:02:04 2014 -0700
    93.3 @@ -46,7 +46,7 @@
    93.4      }
    93.5  
    93.6      public static String readFully(final URL url) throws IOException {
    93.7 -        return new Source(url.toString(), url).getString();
    93.8 +        return Source.sourceFor(url.toString(), url).getString();
    93.9      }
   93.10  
   93.11      public static String readFully(final Reader reader) throws IOException {

mercurial