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