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 if (options.modulePath.isEmpty()) { 255 throw taskHelper.newBadArgs("err.modulepath.must.be.specified") 256 .showUsage(true); 257 } 258 259 JlinkConfiguration config = initJlinkConfig(); 260 if (options.suggestProviders) { 261 suggestProviders(config, remaining); 262 } else { 263 createImage(config); 264 if (options.saveoptsfile != null) { 265 Files.write(Paths.get(options.saveoptsfile), getSaveOpts().getBytes()); 266 } 267 } 268 269 return EXIT_OK; 270 } catch (PluginException | IllegalArgumentException | 271 UncheckedIOException |IOException | FindException | ResolutionException e) { 272 log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage()); 273 if (DEBUG) { 274 e.printStackTrace(log); 275 } 276 return EXIT_ERROR; 277 } catch (BadArgs e) { 278 taskHelper.reportError(e.key, e.args); 279 if (e.showUsage) { 280 log.println(taskHelper.getMessage("main.usage.summary", PROGNAME)); 281 } 282 if (DEBUG) { 283 e.printStackTrace(log); 284 } 285 return EXIT_CMDERR; 286 } catch (Throwable x) { 287 log.println(taskHelper.getMessage("error.prefix") + " " + x.getMessage()); 288 x.printStackTrace(log); 289 return EXIT_ABNORMAL; 290 } finally { 291 log.flush(); 292 } 293 } 294 295 /* 296 * Jlink API entry point. 297 */ 298 public static void createImage(JlinkConfiguration config, 299 PluginsConfiguration plugins) 300 throws Exception { 301 Objects.requireNonNull(config); 302 Objects.requireNonNull(config.getOutput()); 303 plugins = plugins == null ? new PluginsConfiguration() : plugins; 304 305 // First create the image provider 306 ImageProvider imageProvider = 307 createImageProvider(config, 308 null, 309 IGNORE_SIGNING_DEFAULT, 310 false, 311 false, 312 null); 313 314 // Then create the Plugin Stack 315 ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration(plugins); 316 317 //Ask the stack to proceed; 318 stack.operate(imageProvider); 319 } 320 321 /* 322 * Jlink API entry point. 323 */ 324 public static void postProcessImage(ExecutableImage image, List<Plugin> postProcessorPlugins) 325 throws Exception { 326 Objects.requireNonNull(image); 327 Objects.requireNonNull(postProcessorPlugins); 328 PluginsConfiguration config = new PluginsConfiguration(postProcessorPlugins); 329 ImagePluginStack stack = ImagePluginConfiguration. 330 parseConfiguration(config); 331 332 stack.operate((ImagePluginStack stack1) -> image); 333 } 334 335 private void postProcessOnly(Path existingImage) throws Exception { 336 PluginsConfiguration config = taskHelper.getPluginsConfig(null, null); 337 ExecutableImage img = DefaultImageBuilder.getExecutableImage(existingImage); 338 if (img == null) { 339 throw taskHelper.newBadArgs("err.existing.image.invalid"); 340 } 341 postProcessImage(img, config.getPlugins()); 342 } 343 344 // the token for "all modules on the module path" 345 private static final String ALL_MODULE_PATH = "ALL-MODULE-PATH"; 346 private JlinkConfiguration initJlinkConfig() throws BadArgs { 347 Set<String> roots = new HashSet<>(); 348 for (String mod : options.addMods) { 349 if (mod.equals(ALL_MODULE_PATH)) { 350 Path[] entries = options.modulePath.toArray(new Path[0]); 351 ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries); 352 if (!options.limitMods.isEmpty()) { 353 // finder for the observable modules specified in 354 // the --module-path and --limit-modules options 355 finder = limitFinder(finder, options.limitMods, Collections.emptySet()); 356 } 357 358 // all observable modules are roots 359 finder.findAll() 360 .stream() 361 .map(ModuleReference::descriptor) 362 .map(ModuleDescriptor::name) 363 .forEach(mn -> roots.add(mn)); 364 } else { 365 roots.add(mod); 366 } 367 } 368 369 return new JlinkConfiguration(options.output, 370 options.modulePath, 371 roots, 372 options.limitMods, 373 options.endian); 374 } 375 376 private void createImage(JlinkConfiguration config) throws Exception { 377 if (options.output == null) { 378 throw taskHelper.newBadArgs("err.output.must.be.specified").showUsage(true); 379 } 380 if (options.addMods.isEmpty()) { 381 throw taskHelper.newBadArgs("err.mods.must.be.specified", "--add-modules") 382 .showUsage(true); 383 } 384 385 // First create the image provider 386 ImageProvider imageProvider = createImageProvider(config, 387 options.packagedModulesPath, 388 options.ignoreSigning, 389 options.bindServices, 390 options.verbose, 391 log); 392 393 // Then create the Plugin Stack 394 ImagePluginStack stack = ImagePluginConfiguration.parseConfiguration( 395 taskHelper.getPluginsConfig(options.output, options.launchers)); 396 397 //Ask the stack to proceed 398 stack.operate(imageProvider); 399 } 400 401 /* 402 * Returns a module finder of the given module path that limits 403 * the observable modules to those in the transitive closure of 404 * the modules specified in {@code limitMods} plus other modules 405 * specified in the {@code roots} set. 406 */ 407 public static ModuleFinder newModuleFinder(List<Path> paths, 408 Set<String> limitMods, 409 Set<String> roots) 410 { 411 Path[] entries = paths.toArray(new Path[0]); 412 ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries); 413 414 // if limitmods is specified then limit the universe 415 if (!limitMods.isEmpty()) { 416 finder = limitFinder(finder, limitMods, roots); 417 } 418 return finder; 419 } 420 421 private static Path toPathLocation(ResolvedModule m) { 422 Optional<URI> ouri = m.reference().location(); 423 if (!ouri.isPresent()) 424 throw new InternalError(m + " does not have a location"); 425 URI uri = ouri.get(); 426 return Paths.get(uri); 427 } 428 429 430 private static ImageProvider createImageProvider(JlinkConfiguration config, 431 Path retainModulesPath, 432 boolean ignoreSigning, 433 boolean bindService, 434 boolean verbose, 435 PrintWriter log) 436 throws IOException 437 { 438 Configuration cf = bindService ? config.resolveAndBind() 439 : config.resolve(); 440 441 ModuleFinder finder = config.finder(); 442 for (String root : config.getModules()) { 443 Optional<ModuleReference> modRef = finder.find(root); 444 if (modRef.isPresent()) { 445 ModuleDescriptor modDesc = modRef.get().descriptor(); 446 if (modDesc.isAutomatic()) { 447 throw new IllegalArgumentException(taskHelper.getMessage("err.automatic.module.as.root", modDesc.name())); 448 } 449 } 450 } 451 452 if (verbose && log != null) { 453 // print modules to be linked in 454 cf.modules().stream() 455 .sorted(Comparator.comparing(ResolvedModule::name)) 456 .forEach(rm -> log.format("%s %s%n", 457 rm.name(), rm.reference().location().get())); 458 459 // print provider info 460 Set<ModuleReference> references = cf.modules().stream() 461 .map(ResolvedModule::reference).collect(Collectors.toSet()); 462 463 String msg = String.format("%n%s:", taskHelper.getMessage("providers.header")); 464 printProviders(log, msg, references); 465 } 466 467 // emit a warning for any incubating modules in the configuration 468 if (log != null) { 469 String im = cf.modules() 470 .stream() 471 .map(ResolvedModule::reference) 472 .filter(ModuleResolution::hasIncubatingWarning) 473 .map(ModuleReference::descriptor) 474 .map(ModuleDescriptor::name) 475 .collect(Collectors.joining(", ")); 476 477 if (!"".equals(im)) 478 log.println("WARNING: Using incubator modules: " + im); 479 } 480 481 Map<String, Path> mods = cf.modules().stream() 482 .collect(Collectors.toMap(ResolvedModule::name, JlinkTask::toPathLocation)); 483 return new ImageHelper(cf, mods, config.getByteOrder(), retainModulesPath, ignoreSigning); 484 } 485 486 /* 487 * Returns a ModuleFinder that limits observability to the given root 488 * modules, their transitive dependences, plus a set of other modules. 489 */ 490 public static ModuleFinder limitFinder(ModuleFinder finder, 491 Set<String> roots, 492 Set<String> otherMods) { 493 494 // resolve all root modules 495 Configuration cf = Configuration.empty() 496 .resolve(finder, 497 ModuleFinder.of(), 498 roots); 499 500 // module name -> reference 501 Map<String, ModuleReference> map = new HashMap<>(); 502 cf.modules().forEach(m -> { 503 ModuleReference mref = m.reference(); 504 map.put(mref.descriptor().name(), mref); 505 }); 506 507 // add the other modules 508 otherMods.stream() 509 .map(finder::find) 510 .flatMap(Optional::stream) 511 .forEach(mref -> map.putIfAbsent(mref.descriptor().name(), mref)); 512 513 // set of modules that are observable 514 Set<ModuleReference> mrefs = new HashSet<>(map.values()); 515 516 return new ModuleFinder() { 517 @Override 518 public Optional<ModuleReference> find(String name) { 519 return Optional.ofNullable(map.get(name)); 520 } 521 522 @Override 523 public Set<ModuleReference> findAll() { 524 return mrefs; 525 } 526 }; 527 } 528 529 /* 530 * Returns a map of each service type to the modules that use it 531 * It will include services that are provided by a module but may not used 532 * by any of the observable modules. 533 */ 534 private static Map<String, Set<String>> uses(Set<ModuleReference> modules) { 535 // collects the services used by the modules and print uses 536 Map<String, Set<String>> services = new HashMap<>(); 537 modules.stream() 538 .map(ModuleReference::descriptor) 539 .forEach(md -> { 540 // include services that may not be used by any observable modules 541 md.provides().forEach(p -> 542 services.computeIfAbsent(p.service(), _k -> new HashSet<>())); 543 md.uses().forEach(s -> services.computeIfAbsent(s, _k -> new HashSet<>()) 544 .add(md.name())); 545 }); 546 return services; 547 } 548 549 private static void printProviders(PrintWriter log, 550 String header, 551 Set<ModuleReference> modules) { 552 printProviders(log, header, modules, uses(modules)); 553 } 554 555 /* 556 * Prints the providers that are used by the specified services. 557 * 558 * The specified services maps a service type name to the modules 559 * using the service type which may be empty if no observable module uses 560 * that service. 561 */ 562 private static void printProviders(PrintWriter log, 563 String header, 564 Set<ModuleReference> modules, 565 Map<String, Set<String>> serviceToUses) { 566 if (modules.isEmpty()) 567 return; 568 569 // Build a map of a service type to the provider modules 570 Map<String, Set<ModuleDescriptor>> providers = new HashMap<>(); 571 modules.stream() 572 .map(ModuleReference::descriptor) 573 .forEach(md -> { 574 md.provides().stream() 575 .filter(p -> serviceToUses.containsKey(p.service())) 576 .forEach(p -> providers.computeIfAbsent(p.service(), _k -> new HashSet<>()) 577 .add(md)); 578 }); 579 580 if (!providers.isEmpty()) { 581 log.println(header); 582 } 583 584 // print the providers of the service types used by the specified modules 585 // sorted by the service type name and then provider's module name 586 providers.entrySet().stream() 587 .sorted(Map.Entry.comparingByKey()) 588 .forEach(e -> { 589 String service = e.getKey(); 590 e.getValue().stream() 591 .sorted(Comparator.comparing(ModuleDescriptor::name)) 592 .forEach(md -> 593 md.provides().stream() 594 .filter(p -> p.service().equals(service)) 595 .forEach(p -> { 596 String usedBy; 597 if (serviceToUses.get(p.service()).isEmpty()) { 598 usedBy = "not used by any observable module"; 599 } else { 600 usedBy = serviceToUses.get(p.service()).stream() 601 .sorted() 602 .collect(Collectors.joining(",", "used by ", "")); 603 } 604 log.format(" %s provides %s %s%n", 605 md.name(), p.service(), usedBy); 606 }) 607 ); 608 }); 609 } 610 611 private void suggestProviders(JlinkConfiguration config, List<String> args) 612 throws BadArgs 613 { 614 if (args.size() > 1) { 615 throw taskHelper.newBadArgs("err.orphan.argument", 616 toString(args.subList(1, args.size()))) 617 .showUsage(true); 618 } 619 620 if (options.bindServices) { 621 log.println(taskHelper.getMessage("no.suggested.providers")); 622 return; 623 } 624 625 ModuleFinder finder = config.finder(); 626 if (args.isEmpty()) { 627 // print providers used by the observable modules without service binding 628 Set<ModuleReference> mrefs = finder.findAll(); 629 // print uses of the modules that would be linked into the image 630 mrefs.stream() 631 .sorted(Comparator.comparing(mref -> mref.descriptor().name())) 632 .forEach(mref -> { 633 ModuleDescriptor md = mref.descriptor(); 634 log.format("%s %s%n", md.name(), 635 mref.location().get()); 636 md.uses().stream().sorted() 637 .forEach(s -> log.format(" uses %s%n", s)); 638 }); 639 640 String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header")); 641 printProviders(log, msg, mrefs, uses(mrefs)); 642 643 } else { 644 // comma-separated service types, if specified 645 Set<String> names = Stream.of(args.get(0).split(",")) 646 .collect(Collectors.toSet()); 647 // find the modules that provide the specified service 648 Set<ModuleReference> mrefs = finder.findAll().stream() 649 .filter(mref -> mref.descriptor().provides().stream() 650 .map(ModuleDescriptor.Provides::service) 651 .anyMatch(names::contains)) 652 .collect(Collectors.toSet()); 653 654 // find the modules that uses the specified services 655 Map<String, Set<String>> uses = new HashMap<>(); 656 names.forEach(s -> uses.computeIfAbsent(s, _k -> new HashSet<>())); 657 finder.findAll().stream() 658 .map(ModuleReference::descriptor) 659 .forEach(md -> md.uses().stream() 660 .filter(names::contains) 661 .forEach(s -> uses.get(s).add(md.name()))); 662 663 // check if any name given on the command line are not provided by any module 664 mrefs.stream() 665 .flatMap(mref -> mref.descriptor().provides().stream() 666 .map(ModuleDescriptor.Provides::service)) 667 .forEach(names::remove); 668 if (!names.isEmpty()) { 669 log.println(taskHelper.getMessage("warn.provider.notfound", 670 toString(names))); 671 } 672 673 String msg = String.format("%n%s:", taskHelper.getMessage("suggested.providers.header")); 674 printProviders(log, msg, mrefs, uses); 675 } 676 } 677 678 private static String toString(Collection<String> collection) { 679 return collection.stream().sorted() 680 .collect(Collectors.joining(",")); 681 } 682 683 private String getSaveOpts() { 684 StringBuilder sb = new StringBuilder(); 685 sb.append('#').append(new Date()).append("\n"); 686 for (String c : optionsHelper.getInputCommand()) { 687 sb.append(c).append(" "); 688 } 689 690 return sb.toString(); 691 } 692 693 private static String getBomHeader() { 694 StringBuilder sb = new StringBuilder(); 695 sb.append("#").append(new Date()).append("\n"); 696 sb.append("#Please DO NOT Modify this file").append("\n"); 697 return sb.toString(); 698 } 699 700 private String genBOMContent() throws IOException { 701 StringBuilder sb = new StringBuilder(); 702 sb.append(getBomHeader()); 703 StringBuilder command = new StringBuilder(); 704 for (String c : optionsHelper.getInputCommand()) { 705 command.append(c).append(" "); 706 } 707 sb.append("command").append(" = ").append(command); 708 sb.append("\n"); 709 710 return sb.toString(); 711 } 712 713 private static String genBOMContent(JlinkConfiguration config, 714 PluginsConfiguration plugins) 715 throws IOException { 716 StringBuilder sb = new StringBuilder(); 717 sb.append(getBomHeader()); 718 sb.append(config); 719 sb.append(plugins); 720 return sb.toString(); 721 } 722 723 private static class ImageHelper implements ImageProvider { 724 final ByteOrder order; 725 final Path packagedModulesPath; 726 final boolean ignoreSigning; 727 final Set<Archive> archives; 728 729 ImageHelper(Configuration cf, 730 Map<String, Path> modsPaths, 731 ByteOrder order, 732 Path packagedModulesPath, 733 boolean ignoreSigning) throws IOException { 734 this.order = order; 735 this.packagedModulesPath = packagedModulesPath; 736 this.ignoreSigning = ignoreSigning; 737 this.archives = modsPaths.entrySet().stream() 738 .map(e -> newArchive(e.getKey(), e.getValue())) 739 .collect(Collectors.toSet()); 740 } 741 742 private Archive newArchive(String module, Path path) { 743 if (path.toString().endsWith(".jmod")) { 744 return new JmodArchive(module, path); 745 } else if (path.toString().endsWith(".jar")) { 746 ModularJarArchive modularJarArchive = new ModularJarArchive(module, path); 747 748 Stream<Archive.Entry> signatures = modularJarArchive.entries().filter((entry) -> { 749 String name = entry.name().toUpperCase(Locale.ENGLISH); 750 751 return name.startsWith("META-INF/") && name.indexOf('/', 9) == -1 && ( 752 name.endsWith(".SF") || 753 name.endsWith(".DSA") || 754 name.endsWith(".RSA") || 755 name.endsWith(".EC") || 756 name.startsWith("META-INF/SIG-") 757 ); 758 }); 759 760 if (signatures.count() != 0) { 761 if (ignoreSigning) { 762 System.err.println(taskHelper.getMessage("warn.signing", path)); 763 } else { 764 throw new IllegalArgumentException(taskHelper.getMessage("err.signing", path)); 765 } 766 } 767 768 return modularJarArchive; 769 } else if (Files.isDirectory(path)) { 770 return new DirArchive(path); 771 } else { 772 throw new IllegalArgumentException( 773 taskHelper.getMessage("err.not.modular.format", module, path)); 774 } 775 } 776 777 @Override 778 public ExecutableImage retrieve(ImagePluginStack stack) throws IOException { 779 ExecutableImage image = ImageFileCreator.create(archives, order, stack); 780 if (packagedModulesPath != null) { 781 // copy the packaged modules to the given path 782 Files.createDirectories(packagedModulesPath); 783 for (Archive a : archives) { 784 Path file = a.getPath(); 785 Path dest = packagedModulesPath.resolve(file.getFileName()); 786 Files.copy(file, dest); 787 } 788 } 789 return image; 790 } 791 } 792 }