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