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.PrintStream;
  29 import java.util.ArrayDeque;
  30 import java.util.ArrayList;
  31 import java.util.Collection;
  32 import java.util.Collections;
  33 import java.util.Deque;
  34 import java.util.HashSet;
  35 import java.util.List;
  36 import java.util.Map;
  37 import java.util.Map.Entry;
  38 import java.util.Objects;
  39 import java.util.Optional;
  40 import java.util.Set;
  41 import java.util.stream.Collectors;
  42 import java.util.stream.Stream;
  43 
  44 /**
  45  * A configuration that is the result of <a href="package-summary.html#resolution">
  46  * resolution</a> or resolution with <a href="package-summary.html#servicebinding">
  47  * service binding</a>.
  48  *
  49  * <p> A configuration encapsulates the <em>readability graph</em> that is the
  50  * output of resolution. A readability graph is a directed graph where the nodes
  51  * are of type {@link ResolvedModule} and the edges represent the readability
  52  * amongst the modules. {@code Configuration} defines the {@link #modules()
  53  * modules()} method to get the set of resolved modules in the graph. {@code
  54  * ResolvedModule} defines the {@link ResolvedModule#reads() reads()} method to
  55  * get the set of modules that a resolved module reads. The modules that are
  56  * read may be in the same configuration or may be in {@link #parents() parent}
  57  * configurations. </p>
  58  *
  59  * <p> Configuration defines the {@link #resolve(ModuleFinder,List,ModuleFinder,Collection)
  60  * resolve} method to resolve a collection of root modules, and the {@link
  61  * #resolveAndBind(ModuleFinder,List,ModuleFinder,Collection) resolveAndBind}
  62  * method to do resolution with service binding. There are instance and
  63  * static variants of both methods. The instance methods create a configuration
  64  * with the receiver as the parent configuration. The static methods are for
  65  * more advanced cases where there can be more than one parent configuration. </p>
  66  *
  67  * <p> Each {@link java.lang.reflect.Layer layer} of modules in the Java virtual
  68  * machine is created from a configuration. The configuration for the {@link
  69  * java.lang.reflect.Layer#boot() boot} layer is obtained by invoking {@code
  70  * Layer.boot().configuration()}. The configuration for the boot layer will
  71  * often be the parent when creating new configurations. </p>
  72  *
  73  * <h3> Example </h3>
  74  *
  75  * <p> The following example uses the {@link
  76  * #resolve(ModuleFinder,ModuleFinder,Collection) resolve} method to resolve a
  77  * module named <em>myapp</em> with the configuration for the boot layer as the
  78  * parent configuration. It prints the name of each resolved module and the
  79  * names of the modules that each module reads. </p>
  80  *
  81  * <pre>{@code
  82  *    ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
  83  *
  84  *    Configuration parent = Layer.boot().configuration();
  85  *
  86  *    Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("myapp"));
  87  *    cf.modules().forEach(m -> {
  88  *        System.out.format("%s -> %s%n",
  89  *            m.name(),
  90  *            m.reads().stream()
  91  *                .map(ResolvedModule::name)
  92  *                .collect(Collectors.joining(", ")));
  93  *    });
  94  * }</pre>
  95  *
  96  * @since 9
  97  * @spec JPMS
  98  * @see java.lang.reflect.Layer
  99  */
 100 public final class Configuration {
 101 
 102     // @see Configuration#empty()
 103     private static final Configuration EMPTY_CONFIGURATION = new Configuration();
 104 
 105     // parent configurations, in search order
 106     private final List<Configuration> parents;
 107 
 108     private final Map<ResolvedModule, Set<ResolvedModule>> graph;
 109     private final Set<ResolvedModule> modules;
 110     private final Map<String, ResolvedModule> nameToModule;
 111 
 112     // module constraints on target
 113     private final String osName;
 114     private final String osArch;
 115     private final String osVersion;
 116 
 117     String osName() { return osName; }
 118     String osArch() { return osArch; }
 119     String osVersion() { return osVersion; }
 120 
 121     private Configuration() {
 122         this.parents = Collections.emptyList();
 123         this.graph = Collections.emptyMap();
 124         this.modules = Collections.emptySet();
 125         this.nameToModule = Collections.emptyMap();
 126         this.osName = null;
 127         this.osArch = null;
 128         this.osVersion = null;
 129     }
 130 
 131     private Configuration(List<Configuration> parents,
 132                           Resolver resolver,
 133                           boolean check)
 134     {
 135         Map<ResolvedModule, Set<ResolvedModule>> g = resolver.finish(this, check);
 136 
 137         @SuppressWarnings(value = {"rawtypes", "unchecked"})
 138         Entry<String, ResolvedModule>[] nameEntries
 139             = (Entry<String, ResolvedModule>[])new Entry[g.size()];
 140         ResolvedModule[] moduleArray = new ResolvedModule[g.size()];
 141         int i = 0;
 142         for (ResolvedModule resolvedModule : g.keySet()) {
 143             moduleArray[i] = resolvedModule;
 144             nameEntries[i] = Map.entry(resolvedModule.name(), resolvedModule);
 145             i++;
 146         }
 147 
 148         this.parents = Collections.unmodifiableList(parents);
 149         this.graph = g;
 150         this.modules = Set.of(moduleArray);
 151         this.nameToModule = Map.ofEntries(nameEntries);
 152 
 153         this.osName = resolver.osName();
 154         this.osArch = resolver.osArch();
 155         this.osVersion = resolver.osVersion();
 156     }
 157 
 158     /**
 159      * Resolves a collection of root modules, with this configuration as its
 160      * parent, to create a new configuration. This method works exactly as
 161      * specified by the static {@link
 162      * #resolve(ModuleFinder,List,ModuleFinder,Collection) resolve}
 163      * method when invoked with this configuration as the parent. In other words,
 164      * if this configuration is {@code cf} then this method is equivalent to
 165      * invoking:
 166      * <pre> {@code
 167      *     Configuration.resolve(before, List.of(cf), after, roots);
 168      * }</pre>
 169      *
 170      * @param  before
 171      *         The <em>before</em> module finder to find modules
 172      * @param  after
 173      *         The <em>after</em> module finder to locate modules when not
 174      *         located by the {@code before} module finder or in parent
 175      *         configurations
 176      * @param  roots
 177      *         The possibly-empty collection of module names of the modules
 178      *         to resolve
 179      *
 180      * @return The configuration that is the result of resolving the given
 181      *         root modules
 182      *
 183      * @throws FindException
 184      *         If resolution fails for any of the observability-related reasons
 185      *         specified by the static {@code resolve} method
 186      * @throws ResolutionException
 187      *         If any of the post-resolution consistency checks specified by
 188      *         the  static {@code resolve} method fail
 189      * @throws SecurityException
 190      *         If locating a module is denied by the security manager
 191      */
 192     public Configuration resolve(ModuleFinder before,
 193                                  ModuleFinder after,
 194                                  Collection<String> roots)
 195     {
 196         return resolve(before, List.of(this), after, roots);
 197     }
 198 
 199 
 200     /**
 201      * Resolves a collection of root modules, with service binding, and with
 202      * this configuration as its parent, to create a new configuration.
 203      * This method works exactly as specified by the static {@link
 204      * #resolveAndBind(ModuleFinder,List,ModuleFinder,Collection)
 205      * resolveAndBind} method when invoked with this configuration
 206      * as the parent. In other words, if this configuration is {@code cf} then
 207      * this method is equivalent to invoking:
 208      * <pre> {@code
 209      *     Configuration.resolveAndBind(before, List.of(cf), after, roots);
 210      * }</pre>
 211      *
 212      *
 213      * @param  before
 214      *         The <em>before</em> module finder to find modules
 215      * @param  after
 216      *         The <em>after</em> module finder to locate modules when not
 217      *         located by the {@code before} module finder or in parent
 218      *         configurations
 219      * @param  roots
 220      *         The possibly-empty collection of module names of the modules
 221      *         to resolve
 222      *
 223      * @return The configuration that is the result of resolving, with service
 224      *         binding, the given root modules
 225      *
 226      * @throws FindException
 227      *         If resolution fails for any of the observability-related reasons
 228      *         specified by the static {@code resolve} method
 229      * @throws ResolutionException
 230      *         If any of the post-resolution consistency checks specified by
 231      *         the  static {@code resolve} method fail
 232      * @throws SecurityException
 233      *         If locating a module is denied by the security manager
 234      */
 235     public Configuration resolveAndBind(ModuleFinder before,
 236                                         ModuleFinder after,
 237                                         Collection<String> roots)
 238     {
 239         return resolveAndBind(before, List.of(this), after, roots);
 240     }
 241 
 242 
 243     /**
 244      * Resolves a collection of root modules, with service binding, and with
 245      * the empty configuration as its parent. The post resolution checks
 246      * are optionally run.
 247      *
 248      * This method is used to create the configuration for the boot layer.
 249      */
 250     static Configuration resolveAndBind(ModuleFinder finder,
 251                                         Collection<String> roots,
 252                                         boolean check,
 253                                         PrintStream traceOutput)
 254     {
 255         List<Configuration> parents = List.of(empty());
 256         Resolver resolver = new Resolver(finder, parents, ModuleFinder.of(), traceOutput);
 257         resolver.resolve(roots).bind();
 258 
 259         return new Configuration(parents, resolver, check);
 260     }
 261 
 262 
 263     /**
 264      * Resolves a collection of root modules to create a configuration.
 265      *
 266      * <p> Each root module is located using the given {@code before} module
 267      * finder. If a module is not found then it is located in the parent
 268      * configuration as if by invoking the {@link #findModule(String)
 269      * findModule} method on each parent in iteration order. If not found then
 270      * the module is located using the given {@code after} module finder. The
 271      * same search order is used to locate transitive dependences. Root modules
 272      * or dependences that are located in a parent configuration are resolved
 273      * no further and are not included in the resulting configuration. </p>
 274      *
 275      * <p> When all modules have been resolved then the resulting dependency
 276      * graph is checked to ensure that it does not contain cycles. A
 277      * readability graph is constructed, and in conjunction with the module
 278      * exports and service use, checked for consistency. </p>
 279      *
 280      * <p> Resolution may fail with {@code FindException} for the following
 281      * <em>observability-related</em> reasons: </p>
 282      *
 283      * <ul>
 284      *     <li><p> A root module, or a direct or transitive dependency, is not
 285      *     found. </p></li>
 286      *
 287      *     <li><p> An error occurs when attempting to find a module.
 288      *     Possible errors include I/O errors, errors detected parsing a module
 289      *     descriptor ({@code module-info.class}) or two versions of the same
 290      *     module are found in the same directory. </p></li>
 291      *
 292      *     <li><p> A module with the required name is found but the module
 293      *     requires a different {@link ModuleDescriptor#osName() operating
 294      *     system}, {@link ModuleDescriptor#osArch() architecture}, or {@link
 295      *     ModuleDescriptor#osVersion() version} to other modules that have
 296      *     been resolved for the new configuration or modules in the parent
 297      *     configurations. </p></li>
 298      *
 299      * </ul>
 300      *
 301      * <p> Post-resolution consistency checks may fail with {@code
 302      * ResolutionException} for the following reasons: </p>
 303      *
 304      * <ul>
 305      *
 306      *     <li><p> A cycle is detected, say where module {@code m1} requires
 307      *     module {@code m2} and {@code m2} requires {@code m1}. </p></li>
 308      *
 309      *     <li><p> Two or more modules in the configuration export the same
 310      *     package to a module that reads both. This includes the case where a
 311      *     module {@code M} containing package {@code p} reads another module
 312      *     that exports {@code p} to {@code M}. </p></li>
 313      *
 314      *     <li><p> A module {@code M} declares that it "{@code uses p.S}" or
 315      *     "{@code provides p.S with ...}" but package {@code p} is neither in
 316      *     module {@code M} nor exported to {@code M} by any module that
 317      *     {@code M} reads. </p></li>
 318      *
 319      * </ul>
 320      *
 321      * @implNote In the implementation then observability of modules may depend
 322      * on referential integrity checks that ensure that different builds of
 323      * tightly coupled modules cannot be combined in the same configuration.
 324      *
 325      * @param  before
 326      *         The <em>before</em> module finder to find modules
 327      * @param  parents
 328      *         The list parent configurations in search order
 329      * @param  after
 330      *         The <em>after</em> module finder to locate modules when not
 331      *         located by the {@code before} module finder or in parent
 332      *         configurations
 333      * @param  roots
 334      *         The possibly-empty collection of module names of the modules
 335      *         to resolve
 336      *
 337      * @return The configuration that is the result of resolving the given
 338      *         root modules
 339      *
 340      * @throws FindException
 341      *         If resolution fails for an observability-related reason
 342      * @throws ResolutionException
 343      *         If a post-resolution consistency checks fails
 344      * @throws IllegalArgumentException
 345      *         If the list of parents is empty, or the list has two or more
 346      *         parents with modules for different target operating systems,
 347      *         architectures, or versions
 348      *
 349      * @throws SecurityException
 350      *         If locating a module is denied by the security manager
 351      */
 352     public static Configuration resolve(ModuleFinder before,
 353                                         List<Configuration> parents,
 354                                         ModuleFinder after,
 355                                         Collection<String> roots)
 356     {
 357         Objects.requireNonNull(before);
 358         Objects.requireNonNull(after);
 359         Objects.requireNonNull(roots);
 360 
 361         List<Configuration> parentList = new ArrayList<>(parents);
 362         if (parentList.isEmpty())
 363             throw new IllegalArgumentException("'parents' is empty");
 364 
 365         Resolver resolver = new Resolver(before, parentList, after, null);
 366         resolver.resolve(roots);
 367 
 368         return new Configuration(parentList, resolver, true);
 369     }
 370 
 371     /**
 372      * Resolves a collection of root modules, with service binding, to create
 373      * configuration.
 374      *
 375      * <p> This method works exactly as specified by {@link
 376      * #resolve(ModuleFinder,List,ModuleFinder,Collection)
 377      * resolve} except that the graph of resolved modules is augmented
 378      * with modules induced by the service-use dependence relation. </p>
 379      *
 380      * <p> More specifically, the root modules are resolved as if by calling
 381      * {@code resolve}. The resolved modules, and all modules in the
 382      * parent configurations, with {@link ModuleDescriptor#uses() service
 383      * dependences} are then examined. All modules found by the given module
 384      * finders that {@link ModuleDescriptor#provides() provide} an
 385      * implementation of one or more of the service types are added to the
 386      * module graph and then resolved as if by calling the {@code
 387      * resolve} method. Adding modules to the module graph may introduce new
 388      * service-use dependences and so the process works iteratively until no
 389      * more modules are added. </p>
 390      *
 391      * <p> As service binding involves resolution then it may fail with {@code
 392      * FindException} or {@code ResolutionException} for exactly the same
 393      * reasons specified in {@code resolve}. </p>
 394      *
 395      * @param  before
 396      *         The <em>before</em> module finder to find modules
 397      * @param  parents
 398      *         The list parent configurations in search order
 399      * @param  after
 400      *         The <em>after</em> module finder to locate modules when not
 401      *         located by the {@code before} module finder or in parent
 402      *         configurations
 403      * @param  roots
 404      *         The possibly-empty collection of module names of the modules
 405      *         to resolve
 406      *
 407      * @return The configuration that is the result of resolving, with service
 408      *         binding, the given root modules
 409      *
 410      * @throws FindException
 411      *         If resolution fails for any of the observability-related reasons
 412      *         specified by the static {@code resolve} method
 413      * @throws ResolutionException
 414      *         If any of the post-resolution consistency checks specified by
 415      *         the  static {@code resolve} method fail
 416      * @throws IllegalArgumentException
 417      *         If the list of parents is empty, or the list has two or more
 418      *         parents with modules for different target operating systems,
 419      *         architectures, or versions
 420      * @throws SecurityException
 421      *         If locating a module is denied by the security manager
 422      */
 423     public static Configuration resolveAndBind(ModuleFinder before,
 424                                                List<Configuration> parents,
 425                                                ModuleFinder after,
 426                                                Collection<String> roots)
 427     {
 428         Objects.requireNonNull(before);
 429         Objects.requireNonNull(after);
 430         Objects.requireNonNull(roots);
 431 
 432         List<Configuration> parentList = new ArrayList<>(parents);
 433         if (parentList.isEmpty())
 434             throw new IllegalArgumentException("'parents' is empty");
 435 
 436         Resolver resolver = new Resolver(before, parentList, after, null);
 437         resolver.resolve(roots).bind();
 438 
 439         return new Configuration(parentList, resolver, true);
 440     }
 441 
 442 
 443     /**
 444      * Returns the <em>empty</em> configuration. There are no modules in the
 445      * empty configuration. It has no parents.
 446      *
 447      * @return The empty configuration
 448      */
 449     public static Configuration empty() {
 450         return EMPTY_CONFIGURATION;
 451     }
 452 
 453 
 454     /**
 455      * Returns an unmodifiable list of this configuration's parents, in search
 456      * order. If this is the {@linkplain #empty empty configuration} then an
 457      * empty list is returned.
 458      *
 459      * @return A possibly-empty unmodifiable list of this parent configurations
 460      */
 461     public List<Configuration> parents() {
 462         return parents;
 463     }
 464 
 465 
 466     /**
 467      * Returns an immutable set of the resolved modules in this configuration.
 468      *
 469      * @return A possibly-empty unmodifiable set of the resolved modules
 470      *         in this configuration
 471      */
 472     public Set<ResolvedModule> modules() {
 473         return modules;
 474     }
 475 
 476 
 477     /**
 478      * Finds a resolved module in this configuration, or if not in this
 479      * configuration, the {@linkplain #parents parent} configurations.
 480      * Finding a module in parent configurations is equivalent to invoking
 481      * {@code findModule} on each parent, in search order, until the module
 482      * is found or all parents have been searched. In a <em>tree of
 483      * configurations</em> then this is equivalent to a depth-first search.
 484      *
 485      * @param  name
 486      *         The module name of the resolved module to find
 487      *
 488      * @return The resolved module with the given name or an empty {@code
 489      *         Optional} if there isn't a module with this name in this
 490      *         configuration or any parent configurations
 491      */
 492     public Optional<ResolvedModule> findModule(String name) {
 493         Objects.requireNonNull(name);
 494         ResolvedModule m = nameToModule.get(name);
 495         if (m != null)
 496             return Optional.of(m);
 497 
 498         if (!parents.isEmpty()) {
 499             return configurations()
 500                     .skip(1)  // skip this configuration
 501                     .map(cf -> cf.nameToModule)
 502                     .filter(map -> map.containsKey(name))
 503                     .map(map -> map.get(name))
 504                     .findFirst();
 505         }
 506 
 507         return Optional.empty();
 508     }
 509 
 510 
 511     Set<ModuleDescriptor> descriptors() {
 512         if (modules.isEmpty()) {
 513             return Collections.emptySet();
 514         } else {
 515             return modules.stream()
 516                     .map(ResolvedModule::reference)
 517                     .map(ModuleReference::descriptor)
 518                     .collect(Collectors.toSet());
 519         }
 520     }
 521 
 522     Set<ResolvedModule> reads(ResolvedModule m) {
 523         return Collections.unmodifiableSet(graph.get(m));
 524     }
 525 
 526     /**
 527      * Returns an ordered stream of configurations. The first element is this
 528      * configuration, the remaining elements are the parent configurations
 529      * in DFS order.
 530      *
 531      * @implNote For now, the assumption is that the number of elements will
 532      * be very low and so this method does not use a specialized spliterator.
 533      */
 534     Stream<Configuration> configurations() {
 535         List<Configuration> allConfigurations = this.allConfigurations;
 536         if (allConfigurations == null) {
 537             allConfigurations = new ArrayList<>();
 538             Set<Configuration> visited = new HashSet<>();
 539             Deque<Configuration> stack = new ArrayDeque<>();
 540             visited.add(this);
 541             stack.push(this);
 542             while (!stack.isEmpty()) {
 543                 Configuration layer = stack.pop();
 544                 allConfigurations.add(layer);
 545 
 546                 // push in reverse order
 547                 for (int i = layer.parents.size() - 1; i >= 0; i--) {
 548                     Configuration parent = layer.parents.get(i);
 549                     if (!visited.contains(parent)) {
 550                         visited.add(parent);
 551                         stack.push(parent);
 552                     }
 553                 }
 554             }
 555             this.allConfigurations = Collections.unmodifiableList(allConfigurations);
 556         }
 557         return allConfigurations.stream();
 558     }
 559 
 560     private volatile List<Configuration> allConfigurations;
 561 
 562 
 563     /**
 564      * Returns a string describing this configuration.
 565      *
 566      * @return A possibly empty string describing this configuration
 567      */
 568     @Override
 569     public String toString() {
 570         return modules().stream()
 571                 .map(ResolvedModule::name)
 572                 .collect(Collectors.joining(", "));
 573     }
 574 }