1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.tools.jjs;
  27 
  28 import java.io.IOException;
  29 import java.io.File;
  30 import java.util.ArrayList;
  31 import java.util.Collections;
  32 import java.util.EnumSet;
  33 import java.util.HashSet;
  34 import java.util.LinkedHashMap;
  35 import java.util.List;
  36 import java.util.Map;
  37 import java.util.Set;
  38 import java.util.stream.Collectors;
  39 import java.util.stream.Stream;
  40 import javax.tools.JavaCompiler;
  41 import javax.tools.JavaFileManager.Location;
  42 import javax.tools.JavaFileObject;
  43 import javax.tools.StandardJavaFileManager;
  44 import javax.tools.StandardLocation;
  45 import javax.tools.ToolProvider;
  46 
  47 /**
  48  * A helper class to compute properties of a Java package object. Properties of
  49  * package object are (simple) top level class names in that java package and
  50  * immediate subpackages of that package.
  51  */
  52 final class PackagesHelper {
  53     // JavaCompiler may be null on certain platforms (eg. JRE)
  54     private static final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  55 
  56     /**
  57      * Is Java package properties helper available?
  58      *
  59      * @return true if package properties support is available
  60      */
  61     static boolean isAvailable() {
  62         return compiler != null;
  63     }
  64 
  65     private final StandardJavaFileManager fm;
  66     private final Set<JavaFileObject.Kind> fileKinds;
  67 
  68     /**
  69      * Construct a new PackagesHelper.
  70      *
  71      * @param classPath Class path to compute properties of java package objects
  72      */
  73     PackagesHelper(final String classPath) throws IOException {
  74         assert isAvailable() : "no java compiler found!";
  75 
  76         fm = compiler.getStandardFileManager(null, null, null);
  77         fileKinds = EnumSet.of(JavaFileObject.Kind.CLASS);
  78 
  79         if (classPath != null && !classPath.isEmpty()) {
  80             fm.setLocation(StandardLocation.CLASS_PATH, getFiles(classPath));
  81         } else {
  82             // no classpath set. Make sure that it is empty and not any default like "."
  83             fm.setLocation(StandardLocation.CLASS_PATH, Collections.<File>emptyList());
  84         }
  85     }
  86 
  87     // LRU cache for java package properties lists
  88     private final LinkedHashMap<String, List<String>> propsCache =
  89         new LinkedHashMap<>(32, 0.75f, true) {
  90             private static final int CACHE_SIZE = 100;
  91             private static final long serialVersionUID = 1;
  92 
  93             @Override
  94             protected boolean removeEldestEntry(final Map.Entry<String, List<String>> eldest) {
  95                 return size() > CACHE_SIZE;
  96             }
  97         };
  98 
  99     /**
 100      * Return the list of properties of the given Java package or package prefix
 101      *
 102      * @param pkg Java package name or package prefix name
 103      * @return the list of properties of the given Java package or package prefix
 104      */
 105     List<String> getPackageProperties(final String pkg) {
 106         // check the cache first
 107         if (propsCache.containsKey(pkg)) {
 108             return propsCache.get(pkg);
 109         }
 110 
 111         try {
 112             // make sorted list of properties
 113             final List<String> props = new ArrayList<>(listPackage(pkg));
 114             Collections.sort(props);
 115             propsCache.put(pkg, props);
 116             return props;
 117         } catch (final IOException exp) {
 118             if (Main.DEBUG) {
 119                 exp.printStackTrace();
 120             }
 121             return Collections.<String>emptyList();
 122         }
 123     }
 124 
 125     public void close() throws IOException {
 126         fm.close();
 127     }
 128 
 129     private Set<String> listPackage(final String pkg) throws IOException {
 130         final Set<String> props = new HashSet<>();
 131         listPackage(StandardLocation.PLATFORM_CLASS_PATH, pkg, props);
 132         listPackage(StandardLocation.CLASS_PATH, pkg, props);
 133         return props;
 134     }
 135 
 136     private void listPackage(final Location loc, final String pkg, final Set<String> props)
 137             throws IOException {
 138         for (JavaFileObject file : fm.list(loc, pkg, fileKinds, true)) {
 139             final String binaryName = fm.inferBinaryName(loc, file);
 140             // does not start with the given package prefix
 141             if (!binaryName.startsWith(pkg + ".")) {
 142                 continue;
 143             }
 144 
 145             final int nextDot = binaryName.indexOf('.', pkg.length() + 1);
 146             final int start = pkg.length() + 1;
 147 
 148             if (nextDot != -1) {
 149                 // subpackage - eg. "regex" for "java.util"
 150                 props.add(binaryName.substring(start, nextDot));
 151             } else {
 152                 // class - filter out nested, inner, anonymous, local classes.
 153                 // Dynalink supported public nested classes as properties of
 154                 // StaticClass object anyway. We don't want to expose those
 155                 // "$" internal names as properties of package object.
 156 
 157                 final String clsName = binaryName.substring(start);
 158                 if (clsName.indexOf('$') == -1) {
 159                     props.add(clsName);
 160                 }
 161             }
 162         }
 163     }
 164 
 165     // return list of File objects for the given class path
 166     private static List<File> getFiles(final String classPath) {
 167         return Stream.of(classPath.split(File.pathSeparator))
 168                     .map(File::new)
 169                     .collect(Collectors.toList());
 170     }
 171 }