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