samples/autoimports.js

changeset 1576
398c895674d0
parent 1401
da52a33a5e93
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/samples/autoimports.js	Wed Jun 17 23:30:09 2015 -0700
     1.3 @@ -0,0 +1,163 @@
     1.4 +# autoimports script requires -scripting mode
     1.5 +
     1.6 +/*
     1.7 + * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
     1.8 + *
     1.9 + * Redistribution and use in source and binary forms, with or without
    1.10 + * modification, are permitted provided that the following conditions
    1.11 + * are met:
    1.12 + *
    1.13 + *   - Redistributions of source code must retain the above copyright
    1.14 + *     notice, this list of conditions and the following disclaimer.
    1.15 + *
    1.16 + *   - Redistributions in binary form must reproduce the above copyright
    1.17 + *     notice, this list of conditions and the following disclaimer in the
    1.18 + *     documentation and/or other materials provided with the distribution.
    1.19 + *
    1.20 + *   - Neither the name of Oracle nor the names of its
    1.21 + *     contributors may be used to endorse or promote products derived
    1.22 + *     from this software without specific prior written permission.
    1.23 + *
    1.24 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    1.25 + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    1.26 + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    1.27 + * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    1.28 + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    1.29 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    1.30 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    1.31 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    1.32 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    1.33 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    1.34 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    1.35 + */
    1.36 +
    1.37 +/*
    1.38 + * It is tedious to import Java classes used in a script. Sometimes it is easier
    1.39 + * use simple names of java classes and have a script auto import Java classes. 
    1.40 + * You can load this script at the start of an interactive jjs session or at the
    1.41 + * start of your script. This script defines a __noSuchProperty__ hook to auto 
    1.42 + * import Java classes as needed and when they are referred to for the first time
    1.43 + * in your script. You can also call the "autoimports" function to print script 
    1.44 + * statements that you need to use in your script, i.e., have the function generate
    1.45 + * a script to import Java classes used by your script so far. After running your
    1.46 + * script, you can call autoimports to get the exact Java imports you need and replace
    1.47 + * the autoimports load with the generated import statements (to avoid costly init of
    1.48 + * the autoimports script).
    1.49 + */
    1.50 +
    1.51 +(function() {
    1.52 +    var ArrayList = Java.type("java.util.ArrayList");
    1.53 +    var HashMap = Java.type("java.util.HashMap");
    1.54 +    var JarFile = Java.type("java.util.jar.JarFile");
    1.55 +    var File = Java.type("java.io.File");
    1.56 +    var Files = Java.type("java.nio.file.Files");
    1.57 +    var FileSystems = Java.type("java.nio.file.FileSystems");
    1.58 +    var System = Java.type("java.lang.System");
    1.59 +    var URI = Java.type("java.net.URI");
    1.60 +
    1.61 +    // initialize a class to package map by iterating all
    1.62 +    // classes available in the system by walking through "jrt fs"
    1.63 +
    1.64 +    var clsToPkg = new HashMap();
    1.65 +
    1.66 +    // locate rt.jar from sun.boot.class.path
    1.67 +    function findRtJar() {
    1.68 +        var paths = System.getProperty("sun.boot.class.path").split(File.pathSeparator);
    1.69 +        for each (var p in paths) {
    1.70 +            if (p.endsWith("rt.jar") && new File(p).exists()) {
    1.71 +                return p;
    1.72 +            }
    1.73 +        }
    1.74 +    }
    1.75 +
    1.76 +
    1.77 +    function addToClsToPkg(c, p) {
    1.78 +        if (clsToPkg.containsKey(c)) {
    1.79 +            var val = clsToPkg.get(c);
    1.80 +            if (val instanceof ArrayList) {
    1.81 +                val.add(p);
    1.82 +            } else {
    1.83 +                var al = new ArrayList();
    1.84 +                al.add(val);
    1.85 +                al.add(p);
    1.86 +                clsToPkg.put(c, al);
    1.87 +            }
    1.88 +        } else {
    1.89 +            clsToPkg.put(c, p);
    1.90 +        }
    1.91 +    }
    1.92 +
    1.93 +    // handle collision and allow user to choose package
    1.94 +    function getPkgOfCls(c) {
    1.95 +        var val = clsToPkg.get(c);
    1.96 +        if (val instanceof ArrayList) {
    1.97 +            var count = 1;
    1.98 +            print("Multiple matches for " + c + ", choose package:");
    1.99 +            for each (var v in val) {
   1.100 +                print(count + ". " + v);
   1.101 +                count++;
   1.102 +            }
   1.103 +            var choice = parseInt(readLine());
   1.104 +            if (isNaN(choice) || choice < 1 || choice > val.size()) {
   1.105 +                print("invalid choice: " + choice);
   1.106 +                return undefined;
   1.107 +            }
   1.108 +            return val.get(choice - 1);
   1.109 +        } else {
   1.110 +            return val;
   1.111 +        }
   1.112 +    }
   1.113 +
   1.114 +    var rtJar = findRtJar();
   1.115 +    var stream = new JarFile(rtJar).stream();
   1.116 +    try {
   1.117 +        stream.forEach(
   1.118 +            function(entry) {
   1.119 +                var str = entry.name;
   1.120 +                if (str.endsWith(".class")) {
   1.121 +                    if (str.startsWith("java") ||
   1.122 +                        str.startsWith("javax") ||
   1.123 +                        str.startsWith("org")) {
   1.124 +                        var lastIdx = str.lastIndexOf('/');
   1.125 +                        if (lastIdx != -1) {
   1.126 +                            var pkg = str.substring(0, lastIdx).replaceAll('/', '.');
   1.127 +                            var cls = str.substring(lastIdx + 1, str.lastIndexOf(".class"));
   1.128 +                            addToClsToPkg(cls, pkg);
   1.129 +                        }
   1.130 +                    }
   1.131 +                }
   1.132 +            });
   1.133 +    } finally {
   1.134 +        stream.close();
   1.135 +    }
   1.136 +
   1.137 +    var imports = new ArrayList();
   1.138 +    var global = this;
   1.139 +    var oldNoSuchProp = global.__noSuchProperty__;
   1.140 +    this.__noSuchProperty__ = function(name) {
   1.141 +        'use strict';
   1.142 +
   1.143 +        if (clsToPkg.containsKey(name)) {
   1.144 +            var pkg = getPkgOfCls(name);
   1.145 +            if (pkg) {
   1.146 +                var clsName = pkg + "." + name;
   1.147 +                imports.add("var " + name + " = Java.type('" + clsName + "');");
   1.148 +                return global[name] = Java.type(clsName);
   1.149 +            }
   1.150 +        } else if (typeof oldNoSuchProp == 'function') {
   1.151 +            return oldNoSuchProp.call(this, name);
   1.152 +        }
   1.153 +
   1.154 +        if (typeof this == 'undefined') {
   1.155 +            throw new ReferenceError(name);
   1.156 +        } else {
   1.157 +            return undefined;
   1.158 +        }
   1.159 +    }
   1.160 +
   1.161 +    this.autoimports = function() {
   1.162 +        for each (var im in imports) {
   1.163 +            print(im);
   1.164 +        }
   1.165 +    }
   1.166 +})();

mercurial