1 /*
   2  * Copyright (c) 2015, 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 package jdk.tools.jlink.internal;
  26 
  27 import java.io.File;
  28 import java.io.IOException;
  29 import java.io.PrintWriter;
  30 import java.io.UncheckedIOException;
  31 import java.lang.module.Configuration;
  32 import java.lang.module.FindException;
  33 import java.lang.module.ModuleDescriptor;
  34 import java.lang.module.ModuleFinder;
  35 import java.lang.module.ModuleReference;
  36 import java.lang.module.ResolutionException;
  37 import java.lang.module.ResolvedModule;
  38 import java.net.URI;
  39 import java.nio.ByteOrder;
  40 import java.nio.file.Files;
  41 import java.nio.file.Path;
  42 import java.nio.file.Paths;
  43 import java.util.ArrayList;
  44 import java.util.Arrays;
  45 import java.util.Collection;
  46 import java.util.Collections;
  47 import java.util.Comparator;
  48 import java.util.Date;
  49 import java.util.HashMap;
  50 import java.util.HashSet;
  51 import java.util.List;
  52 import java.util.Locale;
  53 import java.util.Map;
  54 import java.util.Objects;
  55 import java.util.Optional;
  56 import java.util.Set;
  57 import java.util.stream.Collectors;
  58 import java.util.stream.Stream;
  59 
  60 import jdk.tools.jlink.internal.TaskHelper.BadArgs;
  61 import static jdk.tools.jlink.internal.TaskHelper.JLINK_BUNDLE;
  62 import jdk.tools.jlink.internal.Jlink.JlinkConfiguration;
  63 import jdk.tools.jlink.internal.Jlink.PluginsConfiguration;
  64 import jdk.tools.jlink.internal.TaskHelper.Option;
  65 import jdk.tools.jlink.internal.TaskHelper.OptionsHelper;
  66 import jdk.tools.jlink.internal.ImagePluginStack.ImageProvider;
  67 import jdk.tools.jlink.plugin.PluginException;
  68 import jdk.tools.jlink.builder.DefaultImageBuilder;
  69 import jdk.tools.jlink.plugin.Plugin;
  70 import jdk.internal.module.ModulePath;
  71 import jdk.internal.module.ModuleResolution;
  72 
  73 /**
  74  * Implementation for the jlink tool.
  75  *
  76  * ## Should use jdk.joptsimple some day.
  77  */
  78 public class JlinkTask {
  79     static final boolean DEBUG = Boolean.getBoolean("jlink.debug");
  80 
  81     // jlink API ignores by default. Remove when signing is implemented.
  82     static final boolean IGNORE_SIGNING_DEFAULT = true;
  83 
  84     private static final TaskHelper taskHelper
  85             = new TaskHelper(JLINK_BUNDLE);
  86 
  87     private static final Option<?>[] recognizedOptions = {
  88         new Option<JlinkTask>(false, (task, opt, arg) -> {
  89             task.options.help = true;
  90         }, "--help", "-h"),
  91         new Option<JlinkTask>(true, (task, opt, arg) -> {
  92             // if used multiple times, the last one wins!
  93             // So, clear previous values, if any.
  94             task.options.modulePath.clear();
  95             String[] dirs = arg.split(File.pathSeparator);
  96             int i = 0;
  97             Arrays.stream(dirs)
  98                   .map(Paths::get)
  99                   .forEach(task.options.modulePath::add);
 100         }, "--module-path", "-p"),
 101         new Option<JlinkTask>(true, (task, opt, arg) -> {
 102             // if used multiple times, the last one wins!
 103             // So, clear previous values, if any.
 104             task.options.limitMods.clear();
 105             for (String mn : arg.split(",")) {
 106                 if (mn.isEmpty()) {
 107                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 108                             "--limit-modules");
 109                 }
 110                 task.options.limitMods.add(mn);
 111             }
 112         }, "--limit-modules"),
 113         new Option<JlinkTask>(true, (task, opt, arg) -> {
 114             for (String mn : arg.split(",")) {
 115                 if (mn.isEmpty()) {
 116                     throw taskHelper.newBadArgs("err.mods.must.be.specified",
 117                             "--add-modules");
 118                 }
 119                 task.options.addMods.add(mn);
 120             }
 121         }, "--add-modules"),
 122         new Option<JlinkTask>(true, (task, opt, arg) -> {
 123             Path path = Paths.get(arg);
 124             task.options.output = path;
 125         }, "--output"),
 126         new Option<JlinkTask>(false, (task, opt, arg) -> {
 127             task.options.bindServices = true;
 128         }, "--bind-services"),
 129         new Option<JlinkTask>(false, (task, opt, arg) -> {
 130             task.options.suggestProviders = true;
 131         }, "--suggest-providers", "", true),
 132         new Option<JlinkTask>(true, (task, opt, arg) -> {
 133             String[] values = arg.split("=");
 134             // check values
 135             if (values.length != 2 || values[0].isEmpty() || values[1].isEmpty()) {
 136                 throw taskHelper.newBadArgs("err.launcher.value.format", arg);
 137             } else {
 138                 String commandName = values[0];
 139                 String moduleAndMain = values[1];
 140                 int idx = moduleAndMain.indexOf("/");
 141                 if (idx != -1) {
 142                     if (moduleAndMain.substring(0, idx).isEmpty()) {
 143                         throw taskHelper.newBadArgs("err.launcher.module.name.empty", arg);
 144                     }
 145 
 146                     if (moduleAndMain.substring(idx + 1).isEmpty()) {
 147                         throw taskHelper.newBadArgs("err.launcher.main.class.empty", arg);
 148                     }
 149                 }
 150                 task.options.launchers.put(commandName, moduleAndMain);
 151             }
 152         }, "--launcher"),
 153         new Option<JlinkTask>(true, (task, opt, arg) -> {
 154             if ("little".equals(arg)) {
 155                 task.options.endian = ByteOrder.LITTLE_ENDIAN;
 156             } else if ("big".equals(arg)) {
 157                 task.options.endian = ByteOrder.BIG_ENDIAN;
 158             } else {
 159                 throw taskHelper.newBadArgs("err.unknown.byte.order", arg);
 160             }
 161         }, "--endian"),
 162         new Option<JlinkTask>(false, (task, opt, arg) -> {
 163             task.options.verbose = true;
 164         }, "--verbose", "-v"),
 165         new Option<JlinkTask>(false, (task, opt, arg) -> {
 166             task.options.version = true;
 167         }, "--version"),
 168         new Option<JlinkTask>(true, (task, opt, arg) -> {
 169             Path path = Paths.get(arg);
 170             if (Files.exists(path)) {
 171                 throw taskHelper.newBadArgs("err.dir.exists", path);
 172             }
 173             task.options.packagedModulesPath = path;
 174         }, true, "--keep-packaged-modules"),
 175         new Option<JlinkTask>(true, (task, opt, arg) -> {
 176             task.options.saveoptsfile = arg;
 177         }, "--save-opts"),
 178         new Option<JlinkTask>(false, (task, opt, arg) -> {
 179             task.options.fullVersion = true;
 180         }, true, "--full-version"),
 181         new Option<JlinkTask>(false, (task, opt, arg) -> {
 182             task.options.ignoreSigning = true;
 183         }, "--ignore-signing-information"),};
 184 
 185     private static final String PROGNAME = "jlink";
 186     private final OptionsValues options = new OptionsValues();
 187 
 188     private static final OptionsHelper<JlinkTask> optionsHelper
 189             = taskHelper.newOptionsHelper(JlinkTask.class, recognizedOptions);
 190     private PrintWriter log;
 191 
 192     void setLog(PrintWriter out, PrintWriter err) {
 193         log = out;
 194         taskHelper.setLog(log);
 195     }
 196 
 197     /**
 198      * Result codes.
 199      */
 200     static final int
 201             EXIT_OK = 0, // Completed with no errors.
 202             EXIT_ERROR = 1, // Completed but reported errors.
 203             EXIT_CMDERR = 2, // Bad command-line arguments
 204             EXIT_SYSERR = 3, // System error or resource exhaustion.
 205             EXIT_ABNORMAL = 4;// terminated abnormally
 206 
 207     static class OptionsValues {
 208         boolean help;
 209         String  saveoptsfile;
 210         boolean verbose;
 211         boolean version;
 212         boolean fullVersion;
 213         final List<Path> modulePath = new ArrayList<>();
 214         final Set<String> limitMods = new HashSet<>();
 215         final Set<String> addMods = new HashSet<>();
 216         Path output;
 217         final Map<String, String> launchers = new HashMap<>();
 218         Path packagedModulesPath;
 219         ByteOrder endian = ByteOrder.nativeOrder();
 220         boolean ignoreSigning = false;
 221         boolean bindServices = false;
 222         boolean suggestProviders = false;
 223     }
 224 
 225     int run(String[] args) {
 226         if (log == null) {
 227             setLog(new PrintWriter(System.out, true),
 228                    new PrintWriter(System.err, true));
 229         }
 230         try {
 231             List<String> remaining = optionsHelper.handleOptions(this, args);
 232             if (remaining.size() > 0 && !options.suggestProviders) {
 233                 throw taskHelper.newBadArgs("err.orphan.arguments", toString(remaining))
 234                                 .showUsage(true);
 235             }
 236             if (options.help) {
 237                 optionsHelper.showHelp(PROGNAME);
 238                 return EXIT_OK;
 239             }
 240             if (optionsHelper.shouldListPlugins()) {
 241                 optionsHelper.listPlugins();
 242                 return EXIT_OK;
 243             }
 244             if (options.version || options.fullVersion) {
 245                 taskHelper.showVersion(options.fullVersion);
 246                 return EXIT_OK;
 247             }
 248 
 249             if (taskHelper.getExistingImage() != null) {
 250                 postProcessOnly(taskHelper.getExistingImage());
 251                 return EXIT_OK;
 252             }
 253 
 254 
 255             if (options.modulePath.isEmpty()) {
 256                 // no --module-path specified - try to set $JAVA_HOME/jmods if that exists
 257                 Path jmods = getDefaultModulePath();
 258                 if (jmods != null) {
 259                     options.modulePath.add(jmods);
 260                 }
 261 
 262                 if (options.modulePath.isEmpty()) {
 263                      throw taskHelper.newBadArgs("err.modulepath.must.be.specified")
 264                                  .showUsage(true);
 265                 }
 266             }
 267 
 268             JlinkConfiguration config = initJlinkConfig();
 269             if (options.suggestProviders) {
 270                 suggestProviders(config, remaining);
 271             } else {
 272                 createImage(config);
 273                 if (options.saveoptsfile != null) {
 274                     Files.write(Paths.get(options.saveoptsfile), getSaveOpts().getBytes());
 275                 }
 276             }
 277 
 278             return EXIT_OK;
 279         } catch (PluginException | IllegalArgumentException |
 280                  UncheckedIOException |IOException | FindException | ResolutionException e) {
 281             log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage());
 282             if (DEBUG) {
 283                 e.printStackTrace(log);
 284             }
 285             return EXIT_ERROR;
 286         } catch (BadArgs e) {
 287             taskHelper.reportError(e.key, e.args);
 288             if (e.showUsage) {
 289                 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME));
 290             }
 291             if (DEBUG) {
 292                 e.printStackTrace(log);
 293             }
 294             return EXIT_CMDERR;
 295         } catch (Throwable x) {
 296             log.println(taskHelper.getMessage("error.prefix") + " " + x.getMessage());
 297             x.printStackTrace(log);
 298             return EXIT_ABNORMAL;
 299         } finally {
 300             log.flush();
 301         }
 302     }
 303 
 304     /*
 305      * Jlink API entry point.
 306      */
 307     public static void createImage(JlinkConfiguration config,
 308                                    PluginsConfiguration plugins)
 309             throws Exception {
 310         Objects.requireNonNull(config);
 311         Objects.requireNonNull(config.getOutput());
 312         plugins = plugins == null ? new PluginsConfiguration() : plugins;
 313 
 314         // First create the image provider
 315         ImageProvider imageProvider =
 316                 createImageProvider(config,
 317                                     null,
 318                                     IGNORE_SIGNING_DEFAULT,
 319                                     false,
 320                                     false,
 321                                     null);
 322 
 323         // Then create the Plugin Stack
 324         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins);
 325 
 326         //Ask the stack to proceed;
 327         stack.operate(imageProvider);
 328     }
 329 
 330     /*
 331      * Jlink API entry point.
 332      */
 333     public static void postProcessImage(ExecutableImage image, List<Plugin> postProcessorPlugins)
 334             throws Exception {
 335         Objects.requireNonNull(image);
 336         Objects.requireNonNull(postProcessorPlugins);
 337         PluginsConfiguration config = new PluginsConfiguration(postProcessorPlugins);
 338         ImagePluginStack stack = ImagePluginConfiguration.
 339                 parseConfiguration(config);
 340 
 341         stack.operate((ImagePluginStack stack1) -> image);
 342     }
 343 
 344     private void postProcessOnly(Path existingImage) throws Exception {
 345         PluginsConfiguration config = taskHelper.getPluginsConfig(null, null);
 346         ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage);
 347         if (img == null) {
 348             throw taskHelper.newBadArgs("err.existing.image.invalid");
 349         }
 350         postProcessImage(img, config.getPlugins());
 351     }
 352 
 353     // the token for "all modules on the module path"
 354     private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH";
 355     private JlinkConfiguration initJlinkConfig() throws BadArgs {
 356         Set<String> roots = new HashSet<>();
 357         for (String mod : options.addMods) {
 358             if (mod.equals(ALL_MODULE_PATH)) {
 359                 Path[] entries = options.modulePath.toArray(new Path[0]);
 360                 ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
 361                 if (!options.limitMods.isEmpty()) {
 362                     // finder for the observable modules specified in
 363                     // the --module-path and --limit-modules options
 364                     finder = limitFinder(finder, options.limitMods, Collections.emptySet());
 365                 }
 366 
 367                 // all observable modules are roots
 368                 finder.findAll()
 369                       .stream()
 370                       .map(ModuleReference::descriptor)
 371                       .map(ModuleDescriptor::name)
 372                       .forEach(mn -> roots.add(mn));
 373             } else {
 374                 roots.add(mod);
 375             }
 376         }
 377 
 378         ModuleFinder finder = newModuleFinder(options.modulePath, options.limitMods, roots);
 379         if (!finder.find("java.base").isPresent()) {
 380             Path defModPath = getDefaultModulePath();
 381             if (defModPath != null) {
 382                 options.modulePath.add(defModPath);
 383             }
 384             finder = newModuleFinder(options.modulePath, options.limitMods, roots);
 385         }
 386 
 387         return new JlinkConfiguration(options.output,

 388                                       roots,
 389                                       options.endian,
 390                                       finder);
 391     }
 392 
 393     private void createImage(JlinkConfiguration config) throws Exception {
 394         if (options.output == null) {
 395             throw taskHelper.newBadArgs("err.output.must.be.specified").showUsage(true);
 396         }
 397         if (options.addMods.isEmpty()) {
 398             throw taskHelper.newBadArgs("err.mods.must.be.specified", "--add-modules")
 399                             .showUsage(true);
 400         }
 401 
 402         // First create the image provider
 403         ImageProvider imageProvider = createImageProvider(config,
 404                                                           options.packagedModulesPath,
 405                                                           options.ignoreSigning,
 406                                                           options.bindServices,
 407                                                           options.verbose,
 408                                                           log);
 409 
 410         // Then create the Plugin Stack
 411         ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(
 412             taskHelper.getPluginsConfig(options.output, options.launchers));
 413 
 414         //Ask the stack to proceed
 415         stack.operate(imageProvider);
 416     }
 417 
 418     /**
 419      * @return the system module path or null
 420      */
 421     public static Path getDefaultModulePath() {
 422         Path jmods = Paths.get(System.getProperty("java.home"), "jmods");
 423         return Files.isDirectory(jmods)? jmods : null;
 424     }
 425 
 426     /*
 427      * Returns a module finder of the given module path that limits
 428      * the observable modules to those in the transitive closure of
 429      * the modules specified in {@code limitMods} plus other modules
 430      * specified in the {@code roots} set.
 431      */
 432     public static ModuleFinder newModuleFinder(List<Path> paths,
 433                                                Set<String> limitMods,
 434                                                Set<String> roots)
 435     {
 436         if (Objects.requireNonNull(paths).isEmpty()) {
 437              throw new IllegalArgumentException("Empty module path");
 438         }
 439         Path[] entries = paths.toArray(new Path[0]);
 440         ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
 441 
 442         // if limitmods is specified then limit the universe
 443         if (limitMods != null && !limitMods.isEmpty()) {
 444             finder = limitFinder(finder, limitMods, Objects.requireNonNull(roots));
 445         }
 446         return finder;
 447     }
 448 
 449     private static Path toPathLocation(ResolvedModule m) {
 450         Optional<URI> ouri = m.reference().location();
 451         if (!ouri.isPresent())
 452             throw new InternalError(m + " does not have a location");
 453         URI uri = ouri.get();
 454         return Paths.get(uri);
 455     }
 456 
 457 
 458     private static ImageProvider createImageProvider(JlinkConfiguration config,
 459                                                      Path retainModulesPath,
 460                                                      boolean ignoreSigning,
 461                                                      boolean bindService,
 462                                                      boolean verbose,
 463                                                      PrintWriter log)
 464             throws IOException
 465     {
 466         Configuration cf = bindService ? config.resolveAndBind()
 467                                        : config.resolve();
 468 
 469         cf.modules().stream()
 470             .map(ResolvedModule::reference)
 471             .filter(mref -> mref.descriptor().isAutomatic())
 472             .findAny()
 473             .ifPresent(mref -> {
 474                 String loc = mref.location().map(URI::toString).orElse("<unknown>");
 475                 throw new IllegalArgumentException(
 476                     taskHelper.getMessage("err.automatic.module", mref.descriptor().name(), loc));
 477             });
 478 
 479         if (verbose && log != null) {
 480             // print modules to be linked in
 481             cf.modules().stream()
 482               .sorted(Comparator.comparing(ResolvedModule::name))
 483               .forEach(rm -> log.format("%s %s%n",
 484                                         rm.name(), rm.reference().location().get()));
 485 
 486             // print provider info
 487             Set<ModuleReference> references = cf.modules().stream()
 488                 .map(ResolvedModule::reference).collect(Collectors.toSet());
 489 
 490             String msg = String.format("%n%s:", taskHelper.getMessage("providers.header"));
 491             printProviders(log, msg, references);
 492         }
 493 
 494         // emit a warning for any incubating modules in the configuration
 495         if (log != null) {
 496             String im = cf.modules()
 497                           .stream()
 498                           .map(ResolvedModule::reference)
 499                           .filter(ModuleResolution::hasIncubatingWarning)
 500                           .map(ModuleReference::descriptor)
 501                           .map(ModuleDescriptor::name)
 502                           .collect(Collectors.joining(", "));
 503 
 504             if (!"".equals(im))
 505                 log.println("WARNING: Using incubator modules: " + im);
 506         }
 507 
 508         Map<String, Path> mods = cf.modules().stream()
 509             .collect(Collectors.toMap(ResolvedModule::name, JlinkTask::toPathLocation));
 510         return new ImageHelper(cf, mods, config.getByteOrder(), retainModulesPath, ignoreSigning);
 511     }
 512 
 513     /*
 514      * Returns a ModuleFinder that limits observability to the given root
 515      * modules, their transitive dependences, plus a set of other modules.
 516      */
 517     public static ModuleFinder limitFinder(ModuleFinder finder,
 518                                            Set<String> roots,
 519                                            Set<String> otherMods) {
 520 
 521         // resolve all root modules
 522         Configuration cf = Configuration.empty()
 523                 .resolve(finder,
 524                          ModuleFinder.of(),
 525                          roots);
 526 
 527         // module name -> reference
 528         Map<String, ModuleReference> map = new HashMap<>();
 529         cf.modules().forEach(m -> {
 530             ModuleReference mref = m.reference();
 531             map.put(mref.descriptor().name(), mref);
 532         });
 533 
 534         // add the other modules
 535         otherMods.stream()
 536             .map(finder::find)
 537             .flatMap(Optional::stream)
 538             .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref));
 539 
 540         // set of modules that are observable
 541         Set<ModuleReference> mrefs = new HashSet<>(map.values());
 542 
 543         return new ModuleFinder() {
 544             @Override
 545             public Optional<ModuleReference> find(String name) {
 546                 return Optional.ofNullable(map.get(name));
 547             }
 548 
 549             @Override
 550             public Set<ModuleReference> findAll() {
 551                 return mrefs;
 552             }
 553         };
 554     }
 555 
 556     /*
 557      * Returns a map of each service type to the modules that use it
 558      * It will include services that are provided by a module but may not used
 559      * by any of the observable modules.
 560      */
 561     private static Map<String, Set<String>> uses(Set<ModuleReference> modules) {
 562         // collects the services used by the modules and print uses
 563         Map<String, Set<String>> services = new HashMap<>();
 564         modules.stream()
 565                .map(ModuleReference::descriptor)
 566                .forEach(md -> {
 567                    // include services that may not be used by any observable modules
 568                    md.provides().forEach(p ->
 569                        services.computeIfAbsent(p.service(), _k -> new HashSet<>()));
 570                    md.uses().forEach(s -> services.computeIfAbsent(s, _k -> new HashSet<>())
 571                                                   .add(md.name()));
 572                });
 573         return services;
 574     }
 575 
 576     private static void printProviders(PrintWriter log,
 577                                        String header,
 578                                        Set<ModuleReference> modules) {
 579         printProviders(log, header, modules, uses(modules));
 580     }
 581 
 582     /*
 583      * Prints the providers that are used by the specified services.
 584      *
 585      * The specified services maps a service type name to the modules
 586      * using the service type which may be empty if no observable module uses
 587      * that service.
 588      */
 589     private static void printProviders(PrintWriter log,
 590                                        String header,
 591                                        Set<ModuleReference> modules,
 592                                        Map<String, Set<String>> serviceToUses) {
 593         if (modules.isEmpty())
 594             return;
 595 
 596         // Build a map of a service type to the provider modules
 597         Map<String, Set<ModuleDescriptor>> providers = new HashMap<>();
 598         modules.stream()
 599             .map(ModuleReference::descriptor)
 600             .forEach(md -> {
 601                 md.provides().stream()
 602                   .filter(p -> serviceToUses.containsKey(p.service()))
 603                   .forEach(p -> providers.computeIfAbsent(p.service(), _k -> new HashSet<>())
 604                                          .add(md));
 605             });
 606 
 607         if (!providers.isEmpty()) {
 608             log.println(header);
 609         }
 610 
 611         // print the providers of the service types used by the specified modules
 612         // sorted by the service type name and then provider's module name
 613         providers.entrySet().stream()
 614             .sorted(Map.Entry.comparingByKey())
 615             .forEach(e -> {
 616                 String service = e.getKey();
 617                 e.getValue().stream()
 618                  .sorted(Comparator.comparing(ModuleDescriptor::name))
 619                  .forEach(md ->
 620                      md.provides().stream()
 621                        .filter(p -> p.service().equals(service))
 622                        .forEach(p -> {
 623                            String usedBy;
 624                            if (serviceToUses.get(p.service()).isEmpty()) {
 625                                usedBy = "not used by any observable module";
 626                            } else {
 627                                usedBy = serviceToUses.get(p.service()).stream()
 628                                             .sorted()
 629                                             .collect(Collectors.joining(",", "used by ", ""));
 630                            }
 631                            log.format("  %s provides %s %s%n",
 632                                       md.name(), p.service(), usedBy);
 633                        })
 634                  );
 635             });
 636     }
 637 
 638     private void suggestProviders(JlinkConfiguration config, List<String> args)
 639         throws BadArgs
 640     {
 641         if (args.size() > 1) {
 642             throw taskHelper.newBadArgs("err.orphan.argument",
 643                                         toString(args.subList(1, args.size())))
 644                             .showUsage(true);
 645         }
 646 
 647         if (options.bindServices) {
 648             log.println(taskHelper.getMessage("no.suggested.providers"));
 649             return;
 650         }
 651 
 652         ModuleFinder finder = config.finder();
 653         if (args.isEmpty()) {
 654             // print providers used by the observable modules without service binding
 655             Set<ModuleReference> mrefs = finder.findAll();
 656             // print uses of the modules that would be linked into the image
 657             mrefs.stream()
 658                  .sorted(Comparator.comparing(mref -> mref.descriptor().name()))
 659                  .forEach(mref -> {
 660                      ModuleDescriptor md = mref.descriptor();
 661                      log.format("%s %s%n", md.name(),
 662                                 mref.location().get());
 663                      md.uses().stream().sorted()
 664                        .forEach(s -> log.format("    uses %s%n", s));
 665                  });
 666 
 667             String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header"));
 668             printProviders(log, msg, mrefs, uses(mrefs));
 669 
 670         } else {
 671             // comma-separated service types, if specified
 672             Set<String> names = Stream.of(args.get(0).split(","))
 673                 .collect(Collectors.toSet());
 674             // find the modules that provide the specified service
 675             Set<ModuleReference> mrefs = finder.findAll().stream()
 676                 .filter(mref -> mref.descriptor().provides().stream()
 677                                     .map(ModuleDescriptor.Provides::service)
 678                                     .anyMatch(names::contains))
 679                 .collect(Collectors.toSet());
 680 
 681             // find the modules that uses the specified services
 682             Map<String, Set<String>> uses = new HashMap<>();
 683             names.forEach(s -> uses.computeIfAbsent(s, _k -> new HashSet<>()));
 684             finder.findAll().stream()
 685                   .map(ModuleReference::descriptor)
 686                   .forEach(md -> md.uses().stream()
 687                                    .filter(names::contains)
 688                                    .forEach(s -> uses.get(s).add(md.name())));
 689 
 690             // check if any name given on the command line are not provided by any module
 691             mrefs.stream()
 692                  .flatMap(mref -> mref.descriptor().provides().stream()
 693                                       .map(ModuleDescriptor.Provides::service))
 694                  .forEach(names::remove);
 695             if (!names.isEmpty()) {
 696                 log.println(taskHelper.getMessage("warn.provider.notfound",
 697                                                   toString(names)));
 698             }
 699 
 700             String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header"));
 701             printProviders(log, msg, mrefs, uses);
 702         }
 703     }
 704 
 705     private static String toString(Collection<String> collection) {
 706         return collection.stream().sorted()
 707                          .collect(Collectors.joining(","));
 708     }
 709 
 710     private String getSaveOpts() {
 711         StringBuilder sb = new StringBuilder();
 712         sb.append('#').append(new Date()).append("\n");
 713         for (String c : optionsHelper.getInputCommand()) {
 714             sb.append(c).append(" ");
 715         }
 716 
 717         return sb.toString();
 718     }
 719 
 720     private static String getBomHeader() {
 721         StringBuilder sb = new StringBuilder();
 722         sb.append("#").append(new Date()).append("\n");
 723         sb.append("#Please DO NOT Modify this file").append("\n");
 724         return sb.toString();
 725     }
 726 
 727     private String genBOMContent() throws IOException {
 728         StringBuilder sb = new StringBuilder();
 729         sb.append(getBomHeader());
 730         StringBuilder command = new StringBuilder();
 731         for (String c : optionsHelper.getInputCommand()) {
 732             command.append(c).append(" ");
 733         }
 734         sb.append("command").append(" = ").append(command);
 735         sb.append("\n");
 736 
 737         return sb.toString();
 738     }
 739 
 740     private static String genBOMContent(JlinkConfiguration config,
 741             PluginsConfiguration plugins)
 742             throws IOException {
 743         StringBuilder sb = new StringBuilder();
 744         sb.append(getBomHeader());
 745         sb.append(config);
 746         sb.append(plugins);
 747         return sb.toString();
 748     }
 749 
 750     private static class ImageHelper implements ImageProvider {
 751         final ByteOrder order;
 752         final Path packagedModulesPath;
 753         final boolean ignoreSigning;
 754         final Set<Archive> archives;
 755 
 756         ImageHelper(Configuration cf,
 757                     Map<String, Path> modsPaths,
 758                     ByteOrder order,
 759                     Path packagedModulesPath,
 760                     boolean ignoreSigning) throws IOException {
 761             this.order = order;
 762             this.packagedModulesPath = packagedModulesPath;
 763             this.ignoreSigning = ignoreSigning;
 764             this.archives = modsPaths.entrySet().stream()
 765                                 .map(e -> newArchive(e.getKey(), e.getValue()))
 766                                 .collect(Collectors.toSet());
 767         }
 768 
 769         private Archive newArchive(String module, Path path) {
 770             if (path.toString().endsWith(".jmod")) {
 771                 return new JmodArchive(module, path);
 772             } else if (path.toString().endsWith(".jar")) {
 773                 ModularJarArchive modularJarArchive = new ModularJarArchive(module, path);
 774 
 775                 Stream<Archive.Entry> signatures = modularJarArchive.entries().filter((entry) -> {
 776                     String name = entry.name().toUpperCase(Locale.ENGLISH);
 777 
 778                     return name.startsWith("META-INF/") && name.indexOf('/', 9) == -1 && (
 779                                 name.endsWith(".SF") ||
 780                                 name.endsWith(".DSA") ||
 781                                 name.endsWith(".RSA") ||
 782                                 name.endsWith(".EC") ||
 783                                 name.startsWith("META-INF/SIG-")
 784                             );
 785                 });
 786 
 787                 if (signatures.count() != 0) {
 788                     if (ignoreSigning) {
 789                         System.err.println(taskHelper.getMessage("warn.signing", path));
 790                     } else {
 791                         throw new IllegalArgumentException(taskHelper.getMessage("err.signing", path));
 792                     }
 793                 }
 794 
 795                 return modularJarArchive;
 796             } else if (Files.isDirectory(path)) {
 797                 return new DirArchive(path);
 798             } else {
 799                 throw new IllegalArgumentException(
 800                     taskHelper.getMessage("err.not.modular.format", module, path));
 801             }
 802         }
 803 
 804         @Override
 805         public ExecutableImage retrieve(ImagePluginStack stack) throws IOException {
 806             ExecutableImage image = ImageFileCreator.create(archives, order, stack);
 807             if (packagedModulesPath != null) {
 808                 // copy the packaged modules to the given path
 809                 Files.createDirectories(packagedModulesPath);
 810                 for (Archive a : archives) {
 811                     Path file = a.getPath();
 812                     Path dest = packagedModulesPath.resolve(file.getFileName());
 813                     Files.copy(file, dest);
 814                 }
 815             }
 816             return image;
 817         }
 818     }
 819 }
--- EOF ---