Path: blob/aarch64-shenandoah-jdk8u272-b10/nashorn/samples/autoimports.js
32278 views
# autoimports script requires -scripting mode12/*3* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.4*5* Redistribution and use in source and binary forms, with or without6* modification, are permitted provided that the following conditions7* are met:8*9* - Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11*12* - Redistributions in binary form must reproduce the above copyright13* notice, this list of conditions and the following disclaimer in the14* documentation and/or other materials provided with the distribution.15*16* - Neither the name of Oracle nor the names of its17* contributors may be used to endorse or promote products derived18* from this software without specific prior written permission.19*20* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS21* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,22* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR23* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR24* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,25* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,26* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR27* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF28* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING29* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS30* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.31*/3233/*34* It is tedious to import Java classes used in a script. Sometimes it is easier35* use simple names of java classes and have a script auto import Java classes.36* You can load this script at the start of an interactive jjs session or at the37* start of your script. This script defines a __noSuchProperty__ hook to auto38* import Java classes as needed and when they are referred to for the first time39* in your script. You can also call the "autoimports" function to print script40* statements that you need to use in your script, i.e., have the function generate41* a script to import Java classes used by your script so far. After running your42* script, you can call autoimports to get the exact Java imports you need and replace43* the autoimports load with the generated import statements (to avoid costly init of44* the autoimports script).45*/4647(function() {48var ArrayList = Java.type("java.util.ArrayList");49var HashMap = Java.type("java.util.HashMap");50var JarFile = Java.type("java.util.jar.JarFile");51var File = Java.type("java.io.File");52var Files = Java.type("java.nio.file.Files");53var FileSystems = Java.type("java.nio.file.FileSystems");54var System = Java.type("java.lang.System");55var URI = Java.type("java.net.URI");5657// initialize a class to package map by iterating all58// classes available in the system by walking through "jrt fs"5960var clsToPkg = new HashMap();6162// locate rt.jar from sun.boot.class.path63function findRtJar() {64var paths = System.getProperty("sun.boot.class.path").split(File.pathSeparator);65for each (var p in paths) {66if (p.endsWith("rt.jar") && new File(p).exists()) {67return p;68}69}70}717273function addToClsToPkg(c, p) {74if (clsToPkg.containsKey(c)) {75var val = clsToPkg.get(c);76if (val instanceof ArrayList) {77val.add(p);78} else {79var al = new ArrayList();80al.add(val);81al.add(p);82clsToPkg.put(c, al);83}84} else {85clsToPkg.put(c, p);86}87}8889// handle collision and allow user to choose package90function getPkgOfCls(c) {91var val = clsToPkg.get(c);92if (val instanceof ArrayList) {93var count = 1;94print("Multiple matches for " + c + ", choose package:");95for each (var v in val) {96print(count + ". " + v);97count++;98}99var choice = parseInt(readLine());100if (isNaN(choice) || choice < 1 || choice > val.size()) {101print("invalid choice: " + choice);102return undefined;103}104return val.get(choice - 1);105} else {106return val;107}108}109110var rtJar = findRtJar();111var stream = new JarFile(rtJar).stream();112try {113stream.forEach(114function(entry) {115var str = entry.name;116if (str.endsWith(".class")) {117if (str.startsWith("java") ||118str.startsWith("javax") ||119str.startsWith("org")) {120var lastIdx = str.lastIndexOf('/');121if (lastIdx != -1) {122var pkg = str.substring(0, lastIdx).replaceAll('/', '.');123var cls = str.substring(lastIdx + 1, str.lastIndexOf(".class"));124addToClsToPkg(cls, pkg);125}126}127}128});129} finally {130stream.close();131}132133var imports = new ArrayList();134var global = this;135var oldNoSuchProp = global.__noSuchProperty__;136this.__noSuchProperty__ = function(name) {137'use strict';138139if (clsToPkg.containsKey(name)) {140var pkg = getPkgOfCls(name);141if (pkg) {142var clsName = pkg + "." + name;143imports.add("var " + name + " = Java.type('" + clsName + "');");144return global[name] = Java.type(clsName);145}146} else if (typeof oldNoSuchProp == 'function') {147return oldNoSuchProp.call(this, name);148}149150if (typeof this == 'undefined') {151throw new ReferenceError(name);152} else {153return undefined;154}155}156157this.autoimports = function() {158for each (var im in imports) {159print(im);160}161}162})();163164165