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