changeset 281:1fd18f40ab52

8014797: rename Java.toJavaArray/toJavaScriptArray to Java.to/from, respectively. Reviewed-by: jlaskey, sundar
author attila
date Mon, 20 May 2013 21:25:14 +0200
parents b558e19d5de5
children e955e64fd15d 833a9a584b64
files docs/JavaScriptingProgrammersGuide.html docs/source/javaarray.js src/jdk/nashorn/api/scripting/resources/engine.js src/jdk/nashorn/internal/objects/NativeJava.java src/jdk/nashorn/internal/runtime/resources/Messages.properties test/script/basic/NASHORN-556.js test/script/basic/javaarrayconversion.js test/script/currently-failing/logcoverage.js test/script/trusted/NASHORN-638.js test/script/trusted/NASHORN-653.js
diffstat 10 files changed, 64 insertions(+), 53 deletions(-) [+]
line wrap: on
line diff
--- a/docs/JavaScriptingProgrammersGuide.html	Mon May 20 23:04:01 2013 +0530
+++ b/docs/JavaScriptingProgrammersGuide.html	Mon May 20 21:25:14 2013 +0200
@@ -616,26 +616,26 @@
 </pre>
 <p>
 It is also possible to convert between JavaScript and Java arrays.
-Given a JavaScript array and a Java type, <code>Java.toJavaArray</code> returns a Java array with the same initial contents, and with the specified component type. 
+Given a JavaScript array and a Java type, <code>Java.to</code> returns a Java array with the same initial contents, and with the specified array type. 
 </p>
 <pre><code>
  var anArray = [1, "13", false]
- var javaIntArray = Java.toJavaArray(anArray, "int")
+ var javaIntArray = Java.to(anArray, "int[]")
  print(javaIntArray[0]) // prints 1
  print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
  print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
 </code></pre>
 <p>
-You can use either a string or a type object returned from <code>Java.type()</code> to specify the component type of the array. 
+You can use either a string or a type object returned from <code>Java.type()</code> to specify the type of the array. 
 You can also omit the array type, in which case a <code>Object[]</code> will be created.
 </p>
 <p>
-Given a Java array or Collection, <code>Java.toJavaScriptArray</code> returns a JavaScript array with a shallow copy of its contents. Note that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will want to use this method.
+Given a Java array or Collection, <code>Java.from</code> returns a JavaScript array with a shallow copy of its contents. Note that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will want to use this method.
 </p>
 <pre><code>
 var File = Java.type("java.io.File");
 var listCurDir = new File(".").listFiles();
-var jsList = Java.toJavaScriptArray(listCurDir);
+var jsList = Java.from(listCurDir);
 print(jsList);
 </code></pre>
 <hr>
--- a/docs/source/javaarray.js	Mon May 20 23:04:01 2013 +0530
+++ b/docs/source/javaarray.js	Mon May 20 21:25:14 2013 +0200
@@ -40,7 +40,7 @@
 
 // convert a script array to Java array
 var anArray = [1, "13", false];
-var javaIntArray = Java.toJavaArray(anArray, "int");
+var javaIntArray = Java.to(anArray, "int[]");
 print(javaIntArray[0]);// prints 1
 print(javaIntArray[1]); // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
 print(javaIntArray[2]);// prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
@@ -48,5 +48,5 @@
 // convert a Java array to a JavaScript array
 var File = Java.type("java.io.File");
 var listCurDir = new File(".").listFiles();
-var jsList = Java.toJavaScriptArray(listCurDir);
+var jsList = Java.from(listCurDir);
 print(jsList);
--- a/src/jdk/nashorn/api/scripting/resources/engine.js	Mon May 20 23:04:01 2013 +0530
+++ b/src/jdk/nashorn/api/scripting/resources/engine.js	Mon May 20 21:25:14 2013 +0200
@@ -88,7 +88,7 @@
             }
         }
 
-        array = Java.toJavaArray(array);
+        array = Java.to(array);
         return Packages.jdk.nashorn.api.scripting.ScriptUtils.format(format, array);
     }
 });
--- a/src/jdk/nashorn/internal/objects/NativeJava.java	Mon May 20 23:04:01 2013 +0530
+++ b/src/jdk/nashorn/internal/objects/NativeJava.java	Mon May 20 21:25:14 2013 +0200
@@ -240,39 +240,52 @@
     }
 
     /**
-     * Given a JavaScript array and a Java type, returns a Java array with the same initial contents, and with the
-     * specified component type. Example:
+     * Given a script object and a Java type, converts the script object into the desired Java type. Currently it only
+     * performs shallow creation of Java arrays, but might be extended for other types in the future. Example:
      * <pre>
      * var anArray = [1, "13", false]
-     * var javaIntArray = Java.toJavaArray(anArray, "int")
+     * var javaIntArray = Java.to(anArray, "int[]")
      * print(javaIntArray[0]) // prints 1
      * print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
      * print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
      * </pre>
      * @param self not used
-     * @param objArray the JavaScript array. Can be null.
-     * @param objType either a {@link #type(Object, Object) type object} or a String describing the component type of
-     * the Java array to create. Can not be null. If undefined, Object is assumed (allowing the argument to be omitted).
-     * @return a Java array with the copy of JavaScript array's contents, converted to the appropriate Java component
-     * type. Returns null if objArray is null.
+     * @param objArray the script object. Can be null.
+     * @param objType either a {@link #type(Object, Object) type object} or a String describing the type of the Java
+     * object to create. Can not be null. If undefined, a "default" conversion is presumed (allowing the argument to be
+     * omitted).
+     * @return a Java object whose value corresponds to the original script object's value. Specifically, for array
+     * target types, returns a Java array of the same type with contents converted to the array's component type. Does
+     * not recursively convert for multidimensional arrays.
+     * type. Returns null if scriptObject is null.
      * @throws ClassNotFoundException if the class described by objType is not found
      */
     @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
-    public static Object toJavaArray(final Object self, final Object objArray, final Object objType) throws ClassNotFoundException {
-        final StaticClass componentType =
-            objType instanceof StaticClass ?
-                (StaticClass)objType :
-                objType == UNDEFINED ?
-                    StaticClass.forClass(Object.class) :
-                    type(objType);
-
+    public static Object to(final Object self, final Object objArray, final Object objType) throws ClassNotFoundException {
         if (objArray == null) {
             return null;
         }
 
+        final Class<?> componentType;
+        if(objType == UNDEFINED) {
+            componentType = Object.class;
+        } else {
+            final StaticClass arrayType;
+            if(objType instanceof StaticClass) {
+                arrayType = (StaticClass)objType;
+            } else {
+                arrayType = type(objType);
+            }
+            final Class<?> arrayClass = arrayType.getRepresentedClass();
+            if(!arrayClass.isArray()) {
+                throw typeError("to.expects.array.type", arrayClass.getName());
+            }
+            componentType = arrayClass.getComponentType();
+        }
+
         Global.checkObject(objArray);
 
-        return ((ScriptObject)objArray).getArray().asArrayOfType(componentType.getRepresentedClass());
+        return ((ScriptObject)objArray).getArray().asArrayOfType(componentType);
     }
 
     /**
@@ -283,7 +296,7 @@
      * <pre>
      * var File = Java.type("java.io.File")
      * var listHomeDir = new File("~").listFiles()
-     * var jsListHome = Java.toJavaScriptArray(listHomeDir)
+     * var jsListHome = Java.from(listHomeDir)
      * var jpegModifiedDates = jsListHome
      *     .filter(function(val) { return val.getName().endsWith(".jpg") })
      *     .map(function(val) { return val.lastModified() })
@@ -294,7 +307,7 @@
      * null.
      */
     @Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
-    public static Object toJavaScriptArray(final Object self, final Object objArray) {
+    public static Object from(final Object self, final Object objArray) {
         if (objArray == null) {
             return null;
         } else if (objArray instanceof Collection) {
--- a/src/jdk/nashorn/internal/runtime/resources/Messages.properties	Mon May 20 23:04:01 2013 +0530
+++ b/src/jdk/nashorn/internal/runtime/resources/Messages.properties	Mon May 20 21:25:14 2013 +0200
@@ -125,6 +125,7 @@
 type.error.no.method.matches.args=Can not invoke method {0} with the passed arguments; they do not match any of its method signatures.
 type.error.method.not.constructor=Java method {0} can't be used as a constructor.
 type.error.env.not.object=$ENV must be an Object.
+type.error.to.expects.array.type=Java.to() expects an array target type. {0} is not an array type.
 range.error.inappropriate.array.length=inappropriate array length: {0}
 range.error.invalid.fraction.digits=fractionDigits argument to {0} must be in [0, 20]
 range.error.invalid.precision=precision argument toPrecision() must be in [1, 21]
--- a/test/script/basic/NASHORN-556.js	Mon May 20 23:04:01 2013 +0530
+++ b/test/script/basic/NASHORN-556.js	Mon May 20 21:25:14 2013 +0200
@@ -47,7 +47,7 @@
   // (NoTypeArrayData)
   var empty = {};
   empty.length = 10;
-  Java.toJavaArray(empty);
+  Java.to(empty);
   delete empty[0];
   Array.prototype.slice.call(empty, 0, 1);
   Array.prototype.pop.call(empty);
@@ -63,7 +63,7 @@
 function f2() {
   // DeletedArrayFilter
   var deleted = [,1,,2,,3,,4,,];
-  assertEq(2, Java.toJavaArray(deleted)[3]);
+  assertEq(2, Java.to(deleted)[3]);
   assertEq(undefined, deleted.pop());
   assertEq(4, deleted.pop());
   deleted.unshift(5);
@@ -78,7 +78,7 @@
 function f3() {
   // DeletedRangeArrayFilter
   var delrange = [1,2,3,,,,,,,,,,];
-  Java.toJavaArray(delrange);
+  Java.to(delrange);
   delrange.unshift(4);
   p.apply(null, delrange);
   print(delrange.slice(1,3), delrange.slice(2,6));
@@ -88,7 +88,7 @@
 function f4() {
   // NumberArrayData
   var num = [1.1,2.2,3.3,4.4,5.5];
-  Java.toJavaArray(num);
+  Java.to(num);
   assertEq(2, num[3] >>> 1);
   assertEq(5, num[4] | 0);
   assertEq(5.5, num.pop());
@@ -104,7 +104,7 @@
 function f5() {
   // ObjectArrayData
   var obj = [2,"two",3.14,"pi",14,"fourteen"];
-  Java.toJavaArray(obj);
+  Java.to(obj);
   assertEq(-12.86, obj[2] - 16);
   assertEq(7, obj[4] >>> 1);
   obj.unshift("one");
@@ -131,14 +131,14 @@
   sparse.length = 1024*1024;
   sparse.push(sparse.length);
   delete sparse[sparse.length-1];
-  //print(Java.toJavaArray(sparse).length);
+  //print(Java.to(sparse).length);
   (function(){}).apply(null, sparse);
 }
 
 function f7() {
   // UndefinedArrayFilter
   var undef = [1,2,3,4,5,undefined,7,8,9,19];
-  Java.toJavaArray(undef);
+  Java.to(undef);
   assertEq(4, undef[8] >>> 1);
   var tmp = undef[9] >>> 1;
   undef[8] = tmp;
@@ -154,8 +154,8 @@
 
 function f8() {
   // LongArrayData
-  var j = Java.toJavaScriptArray(Java.toJavaArray([23,37,42,86,47], "long"));
-  Java.toJavaArray(j);
+  var j = Java.from(Java.to([23,37,42,86,47], "long[]"));
+  Java.to(j);
   p.apply(null, j);
   assertEq(43, j[3] >>> 1);
   assertEq(36, j[4] - 11);
@@ -164,12 +164,12 @@
   assertEq(7, j.shift());
   assertEq(47, j.pop());
   j.push("asdf");
-  j = Java.toJavaScriptArray(Java.toJavaArray([23,37,42,86,47], "long"));
+  j = Java.from(Java.to([23,37,42,86,47], "long[]"));
   j.length = 3;
   j[0] = 13;
-  j = Java.toJavaScriptArray(Java.toJavaArray([23,37,42,86,47], "long"));
+  j = Java.from(Java.to([23,37,42,86,47], "long[]"));
   delete j[0];
-  j = Java.toJavaScriptArray(Java.toJavaArray([23,37,42,86,47], "long"));
+  j = Java.from(Java.to([23,37,42,86,47], "long[]"));
   j.length = 20;
   j[0] = 13.37;
 }
--- a/test/script/basic/javaarrayconversion.js	Mon May 20 23:04:01 2013 +0530
+++ b/test/script/basic/javaarrayconversion.js	Mon May 20 21:25:14 2013 +0200
@@ -34,7 +34,7 @@
 var testCount = 0;
 
 function testF(inputValue, type, testFn) {
-  var x = Java.toJavaArray([inputValue], type)[0];
+  var x = Java.to([inputValue], type + "[]")[0];
   if(!testFn(x)) {
     throw ("unexpected value: " + x)
   }
@@ -130,7 +130,7 @@
 
 function assertCantConvert(sourceType, targetType) {
   try {
-    Java.toJavaArray([new Java.type(sourceType)()], targetType)
+    Java.to([new Java.type(sourceType)()], targetType + "[]")
     throw "no TypeError encountered"
   } catch(e) {
       if(!(e instanceof TypeError)) {
@@ -164,7 +164,7 @@
 intArray[0] = 1234;
 intArray[1] = 42;
 intArray[2] = 5;
-var jsIntArray = Java.toJavaScriptArray(intArray)
+var jsIntArray = Java.from(intArray)
 assert(jsIntArray instanceof Array);
 assert(jsIntArray[0] === 1234);
 assert(jsIntArray[1] === 42);
@@ -179,7 +179,7 @@
 var byteArray = new (Java.type("byte[]"))(2)
 byteArray[0] = -128;
 byteArray[1] = 127;
-var jsByteArray = Java.toJavaScriptArray(byteArray)
+var jsByteArray = Java.from(byteArray)
 assert(jsByteArray instanceof Array);
 assert(jsByteArray[0] === -128);
 assert(jsByteArray[1] === 127);
@@ -187,7 +187,7 @@
 var shortArray = new (Java.type("short[]"))(2)
 shortArray[0] = -32768;
 shortArray[1] = 32767;
-var jsShortArray = Java.toJavaScriptArray(shortArray)
+var jsShortArray = Java.from(shortArray)
 assert(jsShortArray instanceof Array);
 assert(jsShortArray[0] === -32768);
 assert(jsShortArray[1] === 32767);
@@ -195,7 +195,7 @@
 var floatArray = new (Java.type("float[]"))(2)
 floatArray[0] = java.lang.Float.MIN_VALUE;
 floatArray[1] = java.lang.Float.MAX_VALUE;
-var jsFloatArray = Java.toJavaScriptArray(floatArray)
+var jsFloatArray = Java.from(floatArray)
 assert(jsFloatArray instanceof Array);
 assert(jsFloatArray[0] == java.lang.Float.MIN_VALUE);
 assert(jsFloatArray[1] == java.lang.Float.MAX_VALUE);
@@ -204,7 +204,7 @@
 charArray[0] = "a";
 charArray[1] = "b";
 charArray[2] = "1";
-var jsCharArray = Java.toJavaScriptArray(charArray)
+var jsCharArray = Java.from(charArray)
 assert(jsCharArray instanceof Array);
 assert(jsCharArray[0] === 97);
 assert(jsCharArray[1] === 98);
@@ -213,7 +213,7 @@
 var booleanArray = new (Java.type("boolean[]"))(2)
 booleanArray[0] = true;
 booleanArray[1] = false;
-var jsBooleanArray = Java.toJavaScriptArray(booleanArray)
+var jsBooleanArray = Java.from(booleanArray)
 assert(jsBooleanArray instanceof Array);
 assert(jsBooleanArray[0] === true);
 assert(jsBooleanArray[1] === false);
--- a/test/script/currently-failing/logcoverage.js	Mon May 20 23:04:01 2013 +0530
+++ b/test/script/currently-failing/logcoverage.js	Mon May 20 21:25:14 2013 +0200
@@ -53,8 +53,7 @@
             // set new standard err
             System.setErr(newErr);
             System.setOut(newOut);
-            var strType = Java.type("java.lang.String");
-            var engine = fac.getScriptEngine(Java.toJavaArray(opts, strType));
+            var engine = fac.getScriptEngine(Java.to(opts, "java.lang.String[]"));
 	    var reader = new java.io.FileReader(name);
             engine.eval(reader);
             newErr.flush();
--- a/test/script/trusted/NASHORN-638.js	Mon May 20 23:04:01 2013 +0530
+++ b/test/script/trusted/NASHORN-638.js	Mon May 20 21:25:14 2013 +0200
@@ -47,8 +47,7 @@
         try {
             // set new standard err
             System.setErr(newErr);
-            var strType = Java.type("java.lang.String");
-            var engine = fac.getScriptEngine(Java.toJavaArray(opts, strType));
+            var engine = fac.getScriptEngine(Java.to(opts, "java.lang.String[]"));
             engine.eval(code);
             newErr.flush();
             return new java.lang.String(baos.toByteArray());
--- a/test/script/trusted/NASHORN-653.js	Mon May 20 23:04:01 2013 +0530
+++ b/test/script/trusted/NASHORN-653.js	Mon May 20 21:25:14 2013 +0200
@@ -85,8 +85,7 @@
         try {
             // set new standard err
             System.setErr(newErr);
-            var strType = Java.type("java.lang.String");
-            var engine = fac.getScriptEngine(Java.toJavaArray(opts, strType));
+            var engine = fac.getScriptEngine(Java.to(opts, "java.lang.String[]"));
             engine.eval(code);
             newErr.flush();
             return new java.lang.String(baos.toByteArray());