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