# HG changeset patch # User sundar # Date 1441366866 -19800 # Node ID bfe6bd5d57bfaa3e9134588311707ed7ddf007af # Parent 42d8ed4651b62572b39e6fed3fafcb7ee93f9dc2 8135054: Add more samples to nashorn samples directory Reviewed-by: mhaupt, hannesw diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/EvalWithArbitraryThis.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/EvalWithArbitraryThis.java Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.script.*; +import jdk.nashorn.api.scripting.*; + +// Simple nashorn demo that evals a script with arbitrary script +// object bound as "this" for the evaluated script. + +public class EvalWithArbitraryThis { + public static void main(String[] args) throws Exception { + ScriptEngineManager m = new ScriptEngineManager(); + ScriptEngine e = m.getEngineByName("nashorn"); + Object sobj = e.eval("( { foo: 343, bar: 'hello' } )"); + + // "this" bound to sobj in this eval. + // so it prints sobj.foo and sobj.bar. + ((ScriptObjectMirror)sobj).eval("print(this.foo); print(this.bar)"); + } +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/EvalWithArbitraryThis.java.orig --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/EvalWithArbitraryThis.java.orig Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.script.*; +import jdk.nashorn.api.scripting.*; + +// Simple nashorn demo that evals a script with arbitrary script +// object bound as "this" for the evaluated script. + +public class EvalWithArbitraryThis { + public static void main(String[] args) throws Exception { + ScriptEngineManager m = new ScriptEngineManager(); + ScriptEngine e = m.getEngineByName("nashorn"); + Object sobj = e.eval("( { foo: 343, bar: 'hello' } )"); + + // "this" bound to sobj in this eval. + // so it prints sobj.foo and sobj.bar. + ((ScriptObjectMirror)sobj).eval("print(this.foo); print(this.bar)"); + } +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/LambdaAsFunc.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/LambdaAsFunc.java Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.script.*; +import java.util.function.*; + +// example demonstrating that arbitrary Lambda can be called as function from script + +public class LambdaAsFunc { + public static void main(String[] args) throws Exception { + ScriptEngineManager m = new ScriptEngineManager(); + ScriptEngine e = m.getEngineByName("nashorn"); + + // expose a lambda as top-level script function + e.put("upper", (Function) String::toUpperCase); + + // call lambda as though it is a normal script function + System.out.println(e.eval("upper('hello')")); + } +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/Main.asm --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/Main.asm Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Simple sample to demonstrate openjdk asmtools assembler with +// nashorn dynalink linker in a invokedynamic instruction. +// +// To assemble this file, use the following command: +// +// java -cp org.openjdk.asmtools.Main jasm Main.asm +// +// See also: https://wiki.openjdk.java.net/display/CodeTools/asmtools +// +// NOTE: Uses nashorn internals and so *may* break with later nashorn! + +super public class Main + version 52:0 +{ + + +public Method "":"()V" + stack 1 locals 1 +{ + aload_0; + invokespecial Method java/lang/Object."":"()V"; + return; +} + +public static Method main:"([Ljava/lang/String;)V" + stack 2 locals 2 +{ + // List l = new ArrayList(); + new class java/util/ArrayList; + dup; + invokespecial Method java/util/ArrayList."":"()V"; + astore_1; + aload_1; + + // l.add("hello"); + ldc String "hello"; + invokeinterface InterfaceMethod java/util/List.add:"(Ljava/lang/Object;)Z", 2; + pop; + + // l.add("world"); + aload_1; + ldc String "world"; + invokeinterface InterfaceMethod java/util/List.add:"(Ljava/lang/Object;)Z", 2; + pop; + + // printLength(l); + aload_1; + invokestatic Method printLength:"(Ljava/lang/Object;)V"; + + // printLength(args); // args is argument of main method + aload_0; + invokestatic Method printLength:"(Ljava/lang/Object;)V"; + return; +} + +private static Method printLength:"(Ljava/lang/Object;)V" + stack 2 locals 1 +{ + getstatic Field java/lang/System.out:"Ljava/io/PrintStream;"; + aload_0; + + // Using nashorn embedded dynalink linker with the following invokedynamic + // 'length' property on a bean - arrays, lists supported + + invokedynamic InvokeDynamic REF_invokeStatic:jdk/nashorn/internal/runtime/linker/Bootstrap.bootstrap:"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;I)Ljava/lang/invoke/CallSite;":"dyn:getProp|getElem|getMethod:length":"(Ljava/lang/Object;)Ljava/lang/Object;" int 0; + + // print 'length' value + invokevirtual Method java/io/PrintStream.println:"(Ljava/lang/Object;)V"; + return; +} + +} // end Class Main diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/Main.class Binary file samples/Main.class has changed diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/PrintToString.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/PrintToString.java Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.script.*; +import java.io.StringWriter; + +// simple example demonstrating capturing of "print" output +// from script execution as a String via script engine API. + +public class PrintToString { + public static void main(String[] args) throws ScriptException { + ScriptEngineManager m = new ScriptEngineManager(); + ScriptEngine e = m.getEngineByName("nashorn"); + StringWriter sw = new StringWriter(); + e.getContext().setWriter(sw); + e.eval("print('hello world')"); + System.out.println(sw.toString()); + } +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/array_removeif.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/array_removeif.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Sample for Collection.removeIf and Java.to +// See http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate- + +var langs = [ + "java", "javascript", + "C", "C#", "C++", + "Erlang", "Haskell" +]; + +// convert script array to a Java List +function asList(array) { + return Java.to(array, java.util.List); +} + +// remove elements that satisfy a predicate +// using Collection.removeIf(Predicate) +asList(langs).removeIf( + function(s) s.startsWith("C")); + +// print modified array +print(langs); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/bind_on_java.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/bind_on_java.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// sample to demonstrate calling Function.prototype.bind on Java methods. + +var DoubleStream = java.util.stream.DoubleStream; +var r = new java.util.Random(); + +// bind "this" for nextGaussian method of Random class +var next = Function.bind.call(r.nextGaussian, r); + +// next is used as no argument "function" +DoubleStream + .generate(function() next()) + .limit(100) + .forEach(print); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/call_bind_java.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/call_bind_java.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Sample demonstrating calling Java methods like normal +// functions. Bound instance methods, static methods can be +// called like normal script functions. + +// Java types used +var Files = Java.type("java.nio.file.Files"); +var FileSystems = Java.type("java.nio.file.FileSystems"); +var System = Java.type("java.lang.System"); + +var fs = FileSystems.default; +var bind = Function.prototype.bind; + +// Java methods as "functions" + +// Java method with bound "this" +var Path = bind.call(fs.getPath, fs); +// Java static method +var Property = System.getProperty; + +// call Java static methods and bound instance methods +// like normal script functions. + +var root = Path("/"); +// print URI for root dir +print(root.toUri()); +var home = Path(Property("user.home")); +// list home directory +Files.walk(home).forEach(print); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/check_nashorn.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/check_nashorn.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// check if script is being run using nashorn script engine +function isNashorn() { + try { + // "engine" variable is of type javax.script.ScriptEngine is defined + // by nashorn jsr-223 engine. Check the name of the engine from + // javax.script.ScriptEngineFactory associated + + return engine.factory.engineName.contains("Nashorn"); + } catch (e) { + // if engine or any of the properties are undefined + // then script is not being run using nashorn. + return false; + } +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/datetime.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/datetime.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// converting b/w JavaScript Date and Java LocalDateTime + +// JavaScript Date with current time +var d = new Date(); +print(d); + +// Java 8 java.time classes used +var Instant = java.time.Instant; +var LocalDateTime = java.time.LocalDateTime; +var ZoneId = java.time.ZoneId; + +// Date.prototype.getTime + +// getTime() method returns the numeric value corresponding to the time +// for the specified date according to universal time. The value returned +// by the getTime() method is the number of milliseconds since 1 January 1970 00:00:00 UTC. +// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime + +// Java Instant.ofEpochMilli to convert time in milliseconds to Instant object +// https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#ofEpochMilli-long- + +var instant = Instant.ofEpochMilli(d.getTime()); + +// Instant to LocalDateTime using LocalDateTime.ofInstant +// https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#ofInstant-java.time.Instant-java.time.ZoneId- + +var ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); +print(ldt); + +// converting a LocalDateTime to JavaScript Date +// convert LocalDateTime to Instant first +// https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#atZone-java.time.ZoneId- + +var instant = ldt.atZone(ZoneId.systemDefault()).toInstant(); + +// instant to to epoch milliseconds +// https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#toEpochMilli-- +// and then to JavaScript Date from time in milliseconds +// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date + +var d1 = new Date(instant.toEpochMilli()); +print(d1); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/defaults.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/defaults.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// print default methods of a Java class + +if (arguments.length == 0) { + print("Usage: jjs defaults.js -- "); + exit(1); +} + +var jclass = Java.type(arguments[0]).class; +for each (m in jclass.methods) { + // http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#isDefault-- + if (m.default) print(m); +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/find_max_lines.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/find_max_lines.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Find the file with maximum number of lines + +var Files = Java.type("java.nio.file.Files"); +var Integer = Java.type("java.lang.Integer"); +var Paths = Java.type("java.nio.file.Paths"); + +var file = arguments.length == 0? "." : arguments[0]; +var ext = arguments.length > 1? arguments[1] : ".java"; +var path = Paths.get(file); + +// return number of lines in given Path (that represents a file) +function lines(p) { + var strm = Files.lines(p); + try { + return strm.count(); + } finally { + strm.close(); + } +} + +// walk files, map to file and lines, find the max +var obj = Files.find(path, Integer.MAX_VALUE, + function(p, a) !p.toFile().isDirectory() && p.toString().endsWith(ext)). +map(function(p) ({ path : p, lines: lines(p) })). +max(function(x, y) x.lines - y.lines).get(); + +// print path and lines of the max line file +print(obj.path, obj.lines); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/fixed_point.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/fixed_point.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Simple sample demonstrating "fixed point" computation with Streams + +// See also https://mitpress.mit.edu/sicp/chapter1/node21.html#secprocgeneralmethods +var Stream = Java.type("java.util.stream.Stream"); + +// generic fixed point procedure +function fixed_point(f, init_guess) { + var tolerance = 0.00001; + function close_enough(v1, v2) Math.abs(v1 - v2) < tolerance; + + var prev; + return Stream.iterate(init_guess, f) + .filter(function(x) { + try { + return prev == undefined? false : close_enough(prev, x); + } finally { + prev = x; + } + }) + .findFirst() + .get(); +} + +// solution to x = cos(x) +print(fixed_point(Math.cos, 1.0)) + +// solution to x = sin(x) + cos(x) +print(fixed_point(function(x) Math.sin(x) + Math.cos(x), 1.0)); + +// square root by Newton's method +// http://en.wikipedia.org/wiki/Newton's_method +function sqrt(n) + fixed_point(function(x) (x + n/x) / 2, 2.0); + +print(sqrt(2)) +print(sqrt(3)) + + diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/importstatic.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/importstatic.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Java like "import static class_name.*" for nashorn + +function importStatic(clazz) { + // make sure the argument is a Java type + if (! Java.isType(clazz)) { + throw new TypeError(clazz + " is not a Java type"); + } + + // bind properties of clazz to an object + var obj = Object.bindProperties({}, clazz); + + // copy properties to global to "import" those + for (var i in obj) { + this[i] = obj[i]; + } +} + +importStatic(java.time.Instant); +print(now()); +print(ofEpochSecond(1)); +print(parse("2007-12-03T10:15:30.00Z")); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/java_completion.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/java_completion.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Simple sample demonstrating the use of JShell API with nashorn + +// display source code completion suggestions for a Java snippet using JShell's API +// See http://openjdk.java.net/projects/kulla/ + +var repl = Java.type("jdk.jshell.JShell").create() +var analysis = repl.sourceCodeAnalysis() +var code = "System." +var suggestions = analysis.completionSuggestions(code, code.length, [0]) +suggestions.forEach(function(s) print(s.continuation)) diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/jrtlist.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/jrtlist.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// list contents of "jrt" file system in Java 9 + +with(new JavaImporter(java.nio.file, java.net)) { + var fs = FileSystems.getFileSystem(URI.create("jrt:/")) + Files.walk(fs.getPath("/")).forEach(print); +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/mothers_day.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/mothers_day.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,56 @@ +# compute Mothers day of the given the year + +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// print "Mother's day" of the given year using Java Time API + +if (arguments.length == 0) { + print("Usage: jjs mothers_day.js -- year"); + exit(1); +} + +// java classes used +var DayOfWeek = java.time.DayOfWeek; +var LocalDate = java.time.LocalDate; +var TemporalAdjusters = java.time.temporal.TemporalAdjusters; + +var year = parseInt(arguments[0]); + +// See: https://en.wikipedia.org/?title=Mother%27s_Day +// We need second Sunday of May. Make April 30 of the given +// year adjust and adjust to next Sunday from there twice. To adjust a Date +// we use a common TemporalAdjuster provided in JDK8. +// https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAdjusters.html + +print(LocalDate.of(year, 4, 30). + with(TemporalAdjusters.next(DayOfWeek.SUNDAY)). + with(TemporalAdjusters.next(DayOfWeek.SUNDAY))); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/passwordgen.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/passwordgen.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Simple password generator using SecureRandom + stream API + +// accept optional password length from command line +var len = arguments.length? parseInt(arguments[0]) : 8; + +// Java types used +var Collectors = Java.type("java.util.stream.Collectors"); +var SecureRandom = Java.type("java.security.SecureRandom"); + +// allowed password chars +var chars = + "!@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +// generated and print password +print(new SecureRandom(). + ints(len, 0, chars.length). + mapToObj(function(i) chars[i]). + collect(Collectors.joining(""))); diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/print_symlinks.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/print_symlinks.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Print all symbolic links in user's home directory + +// JavaImporter and "with" to simulate "import" statements in Java. +// See https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions + +with (new JavaImporter(java.nio.file, java.lang)) { + + var userDir = System.getProperty("user.dir") + var home = FileSystems.default.getPath(userDir); + + // JS functions can be passed where Java lambdas are required. + // Also, using "Expression closure" extension here. + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Expression_Closures + + Files.walk(home). + filter(function(p) Files.isSymbolicLink(p)). + forEach(function(p) + print(p, '->', Files.readSymbolicLink(p))); +} diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/sort_by_java8.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/sort_by_java8.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// Simple sorting with Java8 APIs + +// Separation key-extraction from key ordering + +// Simple demo for Comparator.comparing +// http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function- + +// data to be sorted +var cards = [ + { name: "hello", email: "foo@hello.com" }, + { name: "world", email: "bar@world.com" }, + { name: "see", email: "see@dontsee.com" }, +]; + +var Collections = java.util.Collections; +var Comparator = java.util.Comparator; + +// sort records name in reverse order of names +Collections.sort(cards, + Comparator.comparing(function(a) a.name).reversed()); + +print(JSON.stringify(cards)) + +// sort records by email +Collections.sort(cards, + Comparator.comparing(function(a) a.email)); + +print(JSON.stringify(cards)) diff -r 42d8ed4651b6 -r bfe6bd5d57bf samples/this_for_eval.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/this_for_eval.js Fri Sep 04 17:11:06 2015 +0530 @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +// how to pass arbitrary "this" object for eval'ed script? + +var obj = { foo: 44 }; + +// the following won't work. eval.apply is indirect eval call +// and so 'this' will be global object always! So, this +// line will print 'undefined' +eval.apply(obj, [ " print(this.foo)" ]); + +obj.myEval = eval; + +// still won't work - still indirect 'eval' call! +// still undefined is printed! +obj.myEval("print(this.foo)"); + +function func(code) { + eval(code); +} + +// eval called inside func and so get's func's "this" as it's "this"! +// So, 44 is printed + +func.apply(obj, [ "print(this.foo)" ]);