1 /*
   2  * Copyright (c) 2014, 2016, 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 java.lang.module;
  27 
  28 import java.io.File;
  29 import java.io.FilePermission;
  30 import java.nio.file.Files;
  31 import java.nio.file.Path;
  32 import java.nio.file.Paths;
  33 import java.security.AccessController;
  34 import java.security.Permission;
  35 import java.security.PrivilegedAction;
  36 import java.util.Arrays;
  37 import java.util.Collections;
  38 import java.util.HashMap;
  39 import java.util.HashSet;
  40 import java.util.List;
  41 import java.util.Map;
  42 import java.util.Objects;
  43 import java.util.Optional;
  44 import java.util.Set;
  45 
  46 import sun.security.action.GetPropertyAction;
  47 
  48 /**
  49  * A finder of modules. A {@code ModuleFinder} is used to find modules during
  50  * <a href="Configuration.html#resolution">resolution</a> or
  51  * <a href="Configuration.html#servicebinding">service binding</a>.
  52  *
  53  * <p> A {@code ModuleFinder} can only find one module with a given name. A
  54  * {@code ModuleFinder} that finds modules in a sequence of directories, for
  55  * example, will locate the first occurrence of a module of a given name and
  56  * will ignore other modules of that name that appear in directories later in
  57  * the sequence. </p>
  58  *
  59  * <p> Example usage: </p>
  60  *
  61  * <pre>{@code
  62  *     Path dir1, dir2, dir3;
  63  *
  64  *     ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
  65  *
  66  *     Optional<ModuleReference> omref = finder.find("jdk.foo");
  67  *     omref.ifPresent(mref -> ... );
  68  *
  69  * }</pre>
  70  *
  71  * <p> The {@link #find(String) find} and {@link #findAll() findAll} methods
  72  * defined here can fail for several reasons. These include I/O errors, errors
  73  * detected parsing a module descriptor ({@code module-info.class}), or in the
  74  * case of {@code ModuleFinder} returned by {@link #of ModuleFinder.of}, that
  75  * two or more modules with the same name are found in a directory.
  76  * When an error is detected then these methods throw {@link FindException
  77  * FindException} with an appropriate {@link Throwable#getCause cause}.
  78  * The behavior of a {@code ModuleFinder} after a {@code FindException} is
  79  * thrown is undefined. For example, invoking {@code find} after an exception
  80  * is thrown may or may not scan the same modules that lead to the exception.
  81  * It is recommended that a module finder be discarded after an exception is
  82  * thrown. </p>
  83  *
  84  * <p> A {@code ModuleFinder} is not required to be thread safe. </p>
  85  *
  86  * @since 9
  87  */
  88 
  89 public interface ModuleFinder {
  90 
  91     /**
  92      * Finds a reference to a module of a given name.
  93      *
  94      * <p> A {@code ModuleFinder} provides a consistent view of the
  95      * modules that it locates. If {@code find} is invoked several times to
  96      * locate the same module (by name) then it will return the same result
  97      * each time. If a module is located then it is guaranteed to be a member
  98      * of the set of modules returned by the {@link #findAll() findAll}
  99      * method. </p>
 100      *
 101      * @param  name
 102      *         The name of the module to find
 103      *
 104      * @return A reference to a module with the given name or an empty
 105      *         {@code Optional} if not found
 106      *
 107      * @throws FindException
 108      *         If an error occurs finding the module
 109      *
 110      * @throws SecurityException
 111      *         If denied by the security manager
 112      */
 113     Optional<ModuleReference> find(String name);
 114 
 115     /**
 116      * Returns the set of all module references that this finder can locate.
 117      *
 118      * <p> A {@code ModuleFinder} provides a consistent view of the modules
 119      * that it locates. If {@link #findAll() findAll} is invoked several times
 120      * then it will return the same (equals) result each time. For each {@code
 121      * ModuleReference} element in the returned set then it is guaranteed that
 122      * {@link #find find} will locate the {@code ModuleReference} if invoked
 123      * to find that module. </p>
 124      *
 125      * @apiNote This is important to have for methods such as {@link
 126      * Configuration#resolveRequiresAndUses resolveRequiresAndUses} that need
 127      * to scan the module path to find modules that provide a specific service.
 128      *
 129      * @return The set of all module references that this finder locates
 130      *
 131      * @throws FindException
 132      *         If an error occurs finding all modules
 133      *
 134      * @throws SecurityException
 135      *         If denied by the security manager
 136      */
 137     Set<ModuleReference> findAll();
 138 
 139     /**
 140      * Returns a module finder that locates the <em>system modules</em>. The
 141      * system modules are typically linked into the Java run-time image.
 142      * The module finder will always find {@code java.base}.
 143      *
 144      * <p> If there is a security manager set then its {@link
 145      * SecurityManager#checkPermission(Permission) checkPermission} method is
 146      * invoked to check that the caller has been granted {@link FilePermission}
 147      * to recursively read the directory that is the value of the system
 148      * property {@code java.home}. </p>
 149      *
 150      * @return A {@code ModuleFinder} that locates the system modules
 151      *
 152      * @throws SecurityException
 153      *         If denied by the security manager
 154      */
 155     static ModuleFinder ofSystem() {
 156         String home;
 157 
 158         SecurityManager sm = System.getSecurityManager();
 159         if (sm != null) {
 160             PrivilegedAction<String> pa = new GetPropertyAction("java.home");
 161             home = AccessController.doPrivileged(pa);
 162             Permission p = new FilePermission(home + File.separator + "-", "read");
 163             sm.checkPermission(p);
 164         } else {
 165             home = System.getProperty("java.home");
 166         }
 167 
 168         Path modules = Paths.get(home, "lib", "modules");
 169         if (Files.isRegularFile(modules)) {
 170             return new SystemModuleFinder();
 171         } else {
 172             Path mlib = Paths.get(home, "modules");
 173             if (Files.isDirectory(mlib)) {
 174                 return of(mlib);
 175             } else {
 176                 throw new InternalError("Unable to detect the run-time image");
 177             }
 178         }
 179     }
 180 
 181     /**
 182      * Returns a module finder that locates modules on the file system by
 183      * searching a sequence of directories and/or packaged modules.
 184      *
 185      * Each element in the given array is one of:
 186      * <ol>
 187      *     <li><p> A path to a directory of modules.</p></li>
 188      *     <li><p> A path to the <em>top-level</em> directory of an
 189      *         <em>exploded module</em>. </p></li>
 190      *     <li><p> A path to a <em>packaged module</em>. </p></li>
 191      * </ol>
 192      *
 193      * The module finder locates modules by searching each directory, exploded
 194      * module, or packaged module in array index order. It finds the first
 195      * occurrence of a module with a given name and ignores other modules of
 196      * that name that appear later in the sequence.
 197      *
 198      * <p> If an element is a path to a directory of modules then each entry in
 199      * the directory is a packaged module or the top-level directory of an
 200      * exploded module. The module finder's {@link #find(String) find} or
 201      * {@link #findAll() findAll} methods throw {@link FindException} if a
 202      * directory containing more than one module with the same name is
 203      * encountered. </p>
 204      *
 205      * <p> If an element in the array is a path to a directory, and that
 206      * directory contains a file named {@code module-info.class}, then the
 207      * directory is treated as an exploded module rather than a directory of
 208      * modules. </p>
 209      *
 210      * <p> The module finder returned by this method supports modules that are
 211      * packaged as JAR files. A JAR file with a {@code module-info.class} in
 212      * the top-level directory of the JAR file (or overridden by a versioned
 213      * entry in a {@link java.util.jar.JarFile#isMultiRelease() multi-release}
 214      * JAR file) is a modular JAR and is an <em>explicit module</em>.
 215      * A JAR file that does not have a {@code module-info.class} in the
 216      * top-level directory is an {@link ModuleDescriptor#isAutomatic automatic}
 217      * module. The {@link ModuleDescriptor} for an automatic module is created as
 218      * follows:
 219      *
 220      * <ul>
 221      *
 222      *     <li><p> The module {@link ModuleDescriptor#name() name}, and {@link
 223      *     ModuleDescriptor#version() version} if applicable, is derived from
 224      *     the file name of the JAR file as follows: </p>
 225      *
 226      *     <ul>
 227      *
 228      *         <li><p> The {@code .jar} suffix is removed. </p></li>
 229      *
 230      *         <li><p> If the name matches the regular expression {@code
 231      *         "-(\\d+(\\.|$))"} then the module name will be derived from the
 232      *         subsequence proceeding the hyphen of the first occurrence. The
 233      *         subsequence after the hyphen is parsed as a {@link
 234      *         ModuleDescriptor.Version} and ignored if it cannot be parsed as
 235      *         a {@code Version}. </p></li>
 236      *
 237      *         <li><p> For the module name, then all non-alphanumeric
 238      *         characters ({@code [^A-Za-z0-9])} are replaced with a dot
 239      *         ({@code "."}), all repeating dots are replaced with one dot,
 240      *         and all leading and trailing dots are removed. </p></li>
 241      *
 242      *         <li><p> As an example, a JAR file named {@code foo-bar.jar} will
 243      *         derive a module name {@code foo.bar} and no version. A JAR file
 244      *         named {@code foo-1.2.3-SNAPSHOT.jar} will derive a module name
 245      *         {@code foo} and {@code 1.2.3-SNAPSHOT} as the version. </p></li>
 246      *
 247      *     </ul></li>
 248      *
 249      *     <li><p> It {@link ModuleDescriptor#requires() requires} {@code
 250      *     java.base}. </p></li>
 251      *
 252      *     <li><p> All entries in the JAR file with names ending with {@code
 253      *     .class} are assumed to be class files where the name corresponds
 254      *     to the fully qualified name of the class. The packages of all
 255      *     classes are {@link ModuleDescriptor#exports() exported}. </p></li>
 256      *
 257      *     <li><p> The contents of all entries starting with {@code
 258      *     META-INF/services/} are assumed to be service configuration files
 259      *     (see {@link java.util.ServiceLoader}). The name of the file
 260      *     (that follows {@code META-INF/services/}) is assumed to be the
 261      *     fully-qualified binary name of a service type. The entries in the
 262      *     file are assumed to be the fully-qualified binary names of
 263      *     provider classes. </p></li>
 264      *
 265      *     <li><p> If the JAR file has a {@code Main-Class} attribute in its
 266      *     main manifest then its value is the {@link
 267      *     ModuleDescriptor#mainClass() main class}. </p></li>
 268      *
 269      * </ul>
 270      *
 271      * <p> If a {@code ModuleDescriptor} cannot be created (by means of the
 272      * {@link ModuleDescriptor.Builder ModuleDescriptor.Builder} API) for an
 273      * automatic module then {@code FindException} is thrown. This can arise,
 274      * for example, when a legal Java identifier name cannot be derived from
 275      * the file name of the JAR file or where a package name derived from an
 276      * entry ending with {@code .class} is not a legal Java identifier. </p>
 277      *
 278      * <p> In addition to JAR files, an implementation may also support modules
 279      * that are packaged in other implementation specific module formats. When
 280      * a file is encountered that is not recognized as a packaged module then
 281      * {@code FindException} is thrown. An implementation may choose to ignore
 282      * some files, {@link java.nio.file.Files#isHidden hidden} files for
 283      * example. Paths to files that do not exist are always ignored. </p>
 284      *
 285      * <p> As with automatic modules, the contents of a packaged or exploded
 286      * module may need to be <em>scanned</em> in order to determine the packages
 287      * in the module. If a {@code .class} file that corresponds to a class in an
 288      * unnamed package is encountered then {@code FindException} is thrown. </p>
 289      *
 290      * <p> Finders created by this method are lazy and do not eagerly check
 291      * that the given file paths are directories or packaged modules.
 292      * Consequently, the {@code find} or {@code findAll} methods will only
 293      * fail if invoking these methods results in searching a directory or
 294      * packaged module and an error is encountered. </p>
 295      *
 296      * @param entries
 297      *        A possibly-empty array of paths to directories of modules
 298      *        or paths to packaged or exploded modules
 299      *
 300      * @return A {@code ModuleFinder} that locates modules on the file system
 301      */
 302     static ModuleFinder of(Path... entries) {
 303         // special case zero entries
 304         if (entries.length == 0) {
 305             return new ModuleFinder() {
 306                 @Override
 307                 public Optional<ModuleReference> find(String name) {
 308                     Objects.requireNonNull(name);
 309                     return Optional.empty();
 310                 }
 311 
 312                 @Override
 313                 public Set<ModuleReference> findAll() {
 314                     return Collections.emptySet();
 315                 }
 316             };
 317         }
 318 
 319         return new ModulePath(entries);
 320     }
 321 
 322     /**
 323      * Returns a module finder that is composed from a sequence of zero or more
 324      * module finders. The {@link #find(String) find} method of the resulting
 325      * module finder will locate a module by invoking the {@code find} method
 326      * of each module finder, in array index order, until either the module is
 327      * found or all module finders have been searched. The {@link #findAll()
 328      * findAll} method of the resulting module finder will return a set of
 329      * modules that includes all modules located by the first module finder.
 330      * The set of modules will include all modules located by the second or
 331      * subsequent module finder that are not located by previous module finders
 332      * in the sequence.
 333      *
 334      * <p> When locating modules then any exceptions or errors thrown by the
 335      * {@code find} or {@code findAll} methods of the underlying module finders
 336      * will be propogated to the caller of the resulting module finder's
 337      * {@code find} or {@code findAll} methods. </p>
 338      *
 339      * @param finders
 340      *        The array of module finders
 341      *
 342      * @return A {@code ModuleFinder} that composes a sequence of module finders
 343      */
 344     static ModuleFinder compose(ModuleFinder... finders) {
 345         final List<ModuleFinder> finderList = Arrays.asList(finders);
 346         finderList.forEach(Objects::requireNonNull);
 347 
 348         return new ModuleFinder() {
 349             private final Map<String, ModuleReference> nameToModule = new HashMap<>();
 350             private Set<ModuleReference> allModules;
 351 
 352             @Override
 353             public Optional<ModuleReference> find(String name) {
 354                 // cached?
 355                 ModuleReference mref = nameToModule.get(name);
 356                 if (mref != null)
 357                     return Optional.of(mref);
 358                 Optional<ModuleReference> omref = finderList.stream()
 359                         .map(f -> f.find(name))
 360                         .flatMap(Optional::stream)
 361                         .findFirst();
 362                 omref.ifPresent(m -> nameToModule.put(name, m));
 363                 return omref;
 364             }
 365 
 366             @Override
 367             public Set<ModuleReference> findAll() {
 368                 if (allModules != null)
 369                     return allModules;
 370                 // seed with modules already found
 371                 Set<ModuleReference> result = new HashSet<>(nameToModule.values());
 372                 finderList.stream()
 373                           .flatMap(f -> f.findAll().stream())
 374                           .forEach(mref -> {
 375                               String name = mref.descriptor().name();
 376                               if (nameToModule.putIfAbsent(name, mref) == null) {
 377                                   result.add(mref);
 378                               }
 379                           });
 380                 allModules = Collections.unmodifiableSet(result);
 381                 return allModules;
 382             }
 383         };
 384     }
 385 
 386 }